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
////////////////////////////////////////////////////////////////////////////// // oxygensizegrip.cpp // bottom right size grip for borderless windows // ------------------- // // Copyright (c) 2009 Hugo Pereira Da Costa <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. ////////////////////////////////////////////////////////////////////////////// #include "oxygensizegrip.h" #include "oxygenbutton.h" #include "oxygenclient.h" #include <cassert> #include <QtGui/QPainter> #include <QtGui/QPolygon> #include <QtCore/QTimer> #include <QtGui/QX11Info> #include <X11/Xlib.h> namespace Oxygen { //_____________________________________________ SizeGrip::SizeGrip( Client* client ): QWidget(0), _client( client ) { setAttribute(Qt::WA_NoSystemBackground ); setAutoFillBackground( false ); // cursor setCursor( Qt::SizeFDiagCursor ); // size setFixedSize( QSize( GRIP_SIZE, GRIP_SIZE ) ); // mask QPolygon p; p << QPoint( 0, GRIP_SIZE ) << QPoint( GRIP_SIZE, 0 ) << QPoint( GRIP_SIZE, GRIP_SIZE ) << QPoint( 0, GRIP_SIZE ); setMask( QRegion( p ) ); // embed embed(); updatePosition(); // event filter client->widget()->installEventFilter( this ); // show show(); } //_____________________________________________ SizeGrip::~SizeGrip( void ) {} //_____________________________________________ void SizeGrip::activeChange( void ) { XMapRaised( QX11Info::display(), winId() ); } //_____________________________________________ void SizeGrip::embed( void ) { WId window_id = client().windowId(); if( client().isPreview() ) { setParent( client().widget() ); } else if( window_id ) { WId current = window_id; while( true ) { WId root, parent = 0; WId *children = 0L; uint child_count = 0; XQueryTree(QX11Info::display(), current, &root, &parent, &children, &child_count); if( parent && parent != root && parent != current ) current = parent; else break; } // reparent XReparentWindow( QX11Info::display(), winId(), current, 0, 0 ); } else { hide(); } } //_____________________________________________ bool SizeGrip::eventFilter( QObject*, QEvent* event ) { if ( event->type() == QEvent::Resize) updatePosition(); return false; } //_____________________________________________ void SizeGrip::paintEvent( QPaintEvent* ) { // get relevant colors QColor base( client().backgroundColor( this, palette(), client().isActive() ) ); QColor light( client().helper().calcDarkColor( base ) ); QColor dark( client().helper().calcDarkColor( base.darker(150) ) ); // create and configure painter QPainter painter(this); painter.setRenderHints(QPainter::Antialiasing ); painter.setPen( Qt::NoPen ); painter.setBrush( base ); // polygon QPolygon p; p << QPoint( 0, GRIP_SIZE ) << QPoint( GRIP_SIZE, 0 ) << QPoint( GRIP_SIZE, GRIP_SIZE ) << QPoint( 0, GRIP_SIZE ); painter.drawPolygon( p ); // diagonal border painter.setBrush( Qt::NoBrush ); painter.setPen( QPen( dark, 3 ) ); painter.drawLine( QPoint( 0, GRIP_SIZE ), QPoint( GRIP_SIZE, 0 ) ); // side borders painter.setPen( QPen( light, 1.5 ) ); painter.drawLine( QPoint( 1, GRIP_SIZE ), QPoint( GRIP_SIZE, GRIP_SIZE ) ); painter.drawLine( QPoint( GRIP_SIZE, 1 ), QPoint( GRIP_SIZE, GRIP_SIZE ) ); painter.end(); } //_____________________________________________ void SizeGrip::mousePressEvent( QMouseEvent* event ) { switch (event->button()) { case Qt::RightButton: { hide(); QTimer::singleShot(5000, this, SLOT(show())); break; } case Qt::MidButton: { hide(); break; } case Qt::LeftButton: if( rect().contains( event->pos() ) ) { // check client window id if( !client().windowId() ) break; client().widget()->setFocus(); if( client().decoration() ) { client().decoration()->performWindowOperation( KDecorationDefines::ResizeOp ); } } break; default: break; } return; } //_______________________________________________________________________________ void SizeGrip::updatePosition( void ) { QPoint position( client().width() - GRIP_SIZE - OFFSET, client().height() - GRIP_SIZE - OFFSET ); if( client().isPreview() ) { position -= QPoint( client().layoutMetric( Client::LM_BorderRight )+ client().layoutMetric( Client::LM_OuterPaddingRight ), client().layoutMetric( Client::LM_OuterPaddingBottom )+ client().layoutMetric( Client::LM_BorderBottom ) ); } else { position -= QPoint( client().layoutMetric( Client::LM_BorderRight ), client().layoutMetric( Client::LM_BorderBottom ) ); } move( position ); } }
mgottschlag/kwin-tiling
kwin/clients/oxygen/oxygensizegrip.cpp
C++
gpl-2.0
6,748
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; namespace gokiTagDB { public class Settings { public static float[] zoomLevels = new float[7] { .25f, .50f, .75f, 1.0f, 1.25f, 1.5f, 2.0f }; public static int[] updateIntervals = new int[] { 15, 30, 100 }; private string fileFilter; public string FileFilter { get { return fileFilter; } set { fileFilter = value; } } private SortType sortType; public SortType SortType { get { return sortType; } set { sortType = value; } } private SelectionMode selectionMode; public SelectionMode SelectionMode { get { return selectionMode; } set { selectionMode = value; } } private int thumbnailWidth; public int ThumbnailWidth { get { return thumbnailWidth; } set { thumbnailWidth = value; } } private int thumbnailHeight; public int ThumbnailHeight { get { return thumbnailHeight; } set { thumbnailHeight = value; } } private int zoomIndex; public int ZoomIndex { get { return zoomIndex; } set { zoomIndex = value; } } private int updateInterval; public int UpdateInterval { get { return updateInterval; } set { updateInterval = value; } } private Padding panelPadding ; public Padding PanelPadding { get { return panelPadding; } set { panelPadding = value; } } private Padding entryMargin; public Padding EntryMargin { get { return entryMargin; } set { entryMargin = value; } } private Padding entryPadding; public Padding EntryPadding { get { return entryPadding; } set { entryPadding = value; } } private int borderSize; public int BorderSize { get { return borderSize; } set { borderSize = value; if (borderSize < 1) { borderSize = 1; } } } private long approximateMemoryUsage; public long ApproximateMemoryUsage { get { return approximateMemoryUsage; } set { approximateMemoryUsage = value; } } private int maximumSuggestions; public int MaximumSuggestions { get { return maximumSuggestions; } set { maximumSuggestions = value; } } private ThumbnailGenerationMethod thumbnailGenerationMethod; public ThumbnailGenerationMethod ThumbnailGenerationMethod { get { return thumbnailGenerationMethod; } set { thumbnailGenerationMethod = value; } } public Settings() { FileFilter = @".*(\.jpeg|\.jpg|\.png|\.gif|\.bmp|\.webm)"; SortType = SortType.Location; SelectionMode = SelectionMode.Explorer; ThumbnailWidth = 200; ThumbnailHeight = 200; ZoomIndex = 3; UpdateInterval = updateIntervals[0]; PanelPadding = new Padding(2); EntryMargin = new Padding(1); EntryPadding = new Padding(1); BorderSize = 1; ApproximateMemoryUsage = 100000000; MaximumSuggestions = 10; ThumbnailGenerationMethod = gokiTagDB.ThumbnailGenerationMethod.Smart; } } }
gokiburikin/gokiTagDB
gokiTagDB/Settings.cs
C#
gpl-2.0
3,782
using JBB.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JBB.DAL.EF { public class JBInitializer : System.Data.Entity.DropCreateDatabaseIfModelChanges<JBContext> { protected override void Seed(JBContext context) { //base.Seed(context); var companies = new List<Company> { new Company{Name="Haagi Mettals"}, new Company{Name="Morkels Manufacture Pty Ltd"} }; companies.ForEach(c => context.Companies.Add(c)); context.SaveChanges(); var offers = new List<Offer> { new Offer{Company=companies[0],ShortDescription="Motor Maintenance", LongDescription="A student is required to maintain electric motors for the companies manufacturing division."}, new Offer{Company=companies[0], ShortDescription="Quality Assurance", LongDescription="A student is required to test the diameter of the product. Tcl/Tk and basic electronic skills (soldering) required."}, new Offer{Company=companies[1], ShortDescription="Lathe Operator", LongDescription="Partime work to earn some extras cash by operating a lathe in our furniture workshop in Doornfontein."} }; offers.ForEach(o => context.Offers.Add(o)); context.SaveChanges(); } } }
relyah/JB
JobBourseBackend/JBB.DAL.EF/JBInitializer.cs
C#
gpl-2.0
1,266
<link href="./resource/style/emoji.css" rel="stylesheet"> <style> .icon-selection h3{padding-left:1em;padding-bottom:0.2em} .icon-selection a{display:block;float:left;overflow:hidden;margin:3px;padding:5px;border:1px #EEE solid;} .icon-selection a:hover{text-decoration:none; border-color:rgb(66, 139, 202);} .icon-selection a i{display:block;font-size:2em;color:#000;} .icon-selection a span{display:block;width:20px;height:20px;overflow:hidden;word-break:break-all;} .icon-selection a > span{display:none;} </style> <script type="text/javascript"> function insertEmoji(obj) { var subindex = $('#menu-index').attr('data-subindex'); if (subindex == '') { var title = $('.menu').eq($('#menu-index').val()).find('input')[0]; } else { var title = $('.submenu').eq($('#menu-index').val()).find('input').eq(subindex)[0]; } if (title.selectionStart == 0) { title.selectionStart = title.value.length; } title.focus(); var unshift = '::' + obj.find('span').text() + '::'; var newstart = title.selectionStart + unshift.length; var insertval = title.value.substr(0,title.selectionStart) + unshift + title.value.substring(title.selectionEnd); title.value = insertval; title.selectionStart = newstart; title.selectionEnd = newstart; w = selectEmoji(); w.modal('hide'); } </script> <div class="icon-selection"> <div class="clearfix"> <a href='javascript:;' onClick="insertEmoji($(this));" title="black sun with rays"><div><span class="emoji emoji2600"></span></div><span>2600</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="cloud"><div><span class="emoji emoji2601"></span></div><span>2601</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="umbrella with rain drops"><div><span class="emoji emoji2614"></span></div><span>2614</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="snowman without snow"><div><span class="emoji emoji26c4"></span></div><span>26C4</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="high voltage sign"><div><span class="emoji emoji26a1"></span></div><span>26A1</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="cyclone"><div><span class="emoji emoji1f300"></span></div><span>1F300</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="foggy"><div><span class="emoji emoji1f301"></span></div><span>1F301</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="closed umbrella"><div><span class="emoji emoji1f302"></span></div><span>1F302</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="night with stars"><div><span class="emoji emoji1f303"></span></div><span>1F303</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="sunrise over mountains"><div><span class="emoji emoji1f304"></span></div><span>1F304</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="sunrise"><div><span class="emoji emoji1f305"></span></div><span>1F305</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="cityscape at dusk"><div><span class="emoji emoji1f306"></span></div><span>1F306</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="sunset over buildings"><div><span class="emoji emoji1f307"></span></div><span>1F307</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="rainbow"><div><span class="emoji emoji1f308"></span></div><span>1F308</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="snowflake"><div><span class="emoji emoji2744"></span></div><span>2744</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="sun behind cloud"><div><span class="emoji emoji26c5"></span></div><span>26C5</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bridge at night"><div><span class="emoji emoji1f309"></span></div><span>1F309</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="water wave"><div><span class="emoji emoji1f30a"></span></div><span>1F30A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="volcano"><div><span class="emoji emoji1f30b"></span></div><span>1F30B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="milky way"><div><span class="emoji emoji1f30c"></span></div><span>1F30C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="earth globe asia-australia"><div><span class="emoji emoji1f30f"></span></div><span>1F30F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="new moon symbol"><div><span class="emoji emoji1f311"></span></div><span>1F311</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="waxing gibbous moon symbol"><div><span class="emoji emoji1f314"></span></div><span>1F314</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="first quarter moon symbol"><div><span class="emoji emoji1f313"></span></div><span>1F313</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="crescent moon"><div><span class="emoji emoji1f319"></span></div><span>1F319</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="full moon symbol"><div><span class="emoji emoji1f315"></span></div><span>1F315</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="first quarter moon with face"><div><span class="emoji emoji1f31b"></span></div><span>1F31B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="glowing star"><div><span class="emoji emoji1f31f"></span></div><span>1F31F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="shooting star"><div><span class="emoji emoji1f320"></span></div><span>1F320</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="clock face one oclock"><div><span class="emoji emoji1f550"></span></div><span>1F550</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="clock face two oclock"><div><span class="emoji emoji1f551"></span></div><span>1F551</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="clock face three oclock"><div><span class="emoji emoji1f552"></span></div><span>1F552</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="clock face four oclock"><div><span class="emoji emoji1f553"></span></div><span>1F553</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="clock face five oclock"><div><span class="emoji emoji1f554"></span></div><span>1F554</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="clock face six oclock"><div><span class="emoji emoji1f555"></span></div><span>1F555</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="clock face seven oclock"><div><span class="emoji emoji1f556"></span></div><span>1F556</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="clock face eight oclock"><div><span class="emoji emoji1f557"></span></div><span>1F557</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="clock face nine oclock"><div><span class="emoji emoji1f558"></span></div><span>1F558</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="clock face ten oclock"><div><span class="emoji emoji1f559"></span></div><span>1F559</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="clock face eleven oclock"><div><span class="emoji emoji1f55a"></span></div><span>1F55A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="clock face twelve oclock"><div><span class="emoji emoji1f55b"></span></div><span>1F55B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="watch"><div><span class="emoji emoji231a"></span></div><span>231A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="hourglass"><div><span class="emoji emoji231b"></span></div><span>231B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="alarm clock"><div><span class="emoji emoji23f0"></span></div><span>23F0</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="hourglass with flowing sand"><div><span class="emoji emoji23f3"></span></div><span>23F3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="aries"><div><span class="emoji emoji2648"></span></div><span>2648</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="taurus"><div><span class="emoji emoji2649"></span></div><span>2649</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="gemini"><div><span class="emoji emoji264a"></span></div><span>264A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="cancer"><div><span class="emoji emoji264b"></span></div><span>264B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="leo"><div><span class="emoji emoji264c"></span></div><span>264C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="virgo"><div><span class="emoji emoji264d"></span></div><span>264D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="libra"><div><span class="emoji emoji264e"></span></div><span>264E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="scorpius"><div><span class="emoji emoji264f"></span></div><span>264F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="sagittarius"><div><span class="emoji emoji2650"></span></div><span>2650</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="capricorn"><div><span class="emoji emoji2651"></span></div><span>2651</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="aquarius"><div><span class="emoji emoji2652"></span></div><span>2652</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="pisces"><div><span class="emoji emoji2653"></span></div><span>2653</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="ophiuchus"><div><span class="emoji emoji26ce"></span></div><span>26CE</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="four leaf clover"><div><span class="emoji emoji1f340"></span></div><span>1F340</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="tulip"><div><span class="emoji emoji1f337"></span></div><span>1F337</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="seedling"><div><span class="emoji emoji1f331"></span></div><span>1F331</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="maple leaf"><div><span class="emoji emoji1f341"></span></div><span>1F341</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="cherry blossom"><div><span class="emoji emoji1f338"></span></div><span>1F338</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="rose"><div><span class="emoji emoji1f339"></span></div><span>1F339</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="fallen leaf"><div><span class="emoji emoji1f342"></span></div><span>1F342</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="leaf fluttering in wind"><div><span class="emoji emoji1f343"></span></div><span>1F343</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="hibiscus"><div><span class="emoji emoji1f33a"></span></div><span>1F33A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="sunflower"><div><span class="emoji emoji1f33b"></span></div><span>1F33B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="palm tree"><div><span class="emoji emoji1f334"></span></div><span>1F334</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="cactus"><div><span class="emoji emoji1f335"></span></div><span>1F335</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="ear of rice"><div><span class="emoji emoji1f33e"></span></div><span>1F33E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="ear of maize"><div><span class="emoji emoji1f33d"></span></div><span>1F33D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="mushroom"><div><span class="emoji emoji1f344"></span></div><span>1F344</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="chestnut"><div><span class="emoji emoji1f330"></span></div><span>1F330</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="blossom"><div><span class="emoji emoji1f33c"></span></div><span>1F33C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="herb"><div><span class="emoji emoji1f33f"></span></div><span>1F33F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="cherries"><div><span class="emoji emoji1f352"></span></div><span>1F352</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="banana"><div><span class="emoji emoji1f34c"></span></div><span>1F34C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="red apple"><div><span class="emoji emoji1f34e"></span></div><span>1F34E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="tangerine"><div><span class="emoji emoji1f34a"></span></div><span>1F34A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="strawberry"><div><span class="emoji emoji1f353"></span></div><span>1F353</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="watermelon"><div><span class="emoji emoji1f349"></span></div><span>1F349</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="tomato"><div><span class="emoji emoji1f345"></span></div><span>1F345</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="aubergine"><div><span class="emoji emoji1f346"></span></div><span>1F346</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="melon"><div><span class="emoji emoji1f348"></span></div><span>1F348</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="pineapple"><div><span class="emoji emoji1f34d"></span></div><span>1F34D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="grapes"><div><span class="emoji emoji1f347"></span></div><span>1F347</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="peach"><div><span class="emoji emoji1f351"></span></div><span>1F351</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="green apple"><div><span class="emoji emoji1f34f"></span></div><span>1F34F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="eyes"><div><span class="emoji emoji1f440"></span></div><span>1F440</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="ear"><div><span class="emoji emoji1f442"></span></div><span>1F442</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="nose"><div><span class="emoji emoji1f443"></span></div><span>1F443</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="mouth"><div><span class="emoji emoji1f444"></span></div><span>1F444</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="tongue"><div><span class="emoji emoji1f445"></span></div><span>1F445</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="lipstick"><div><span class="emoji emoji1f484"></span></div><span>1F484</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="nail polish"><div><span class="emoji emoji1f485"></span></div><span>1F485</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="face massage"><div><span class="emoji emoji1f486"></span></div><span>1F486</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="haircut"><div><span class="emoji emoji1f487"></span></div><span>1F487</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="barber pole"><div><span class="emoji emoji1f488"></span></div><span>1F488</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bust in silhouette"><div><span class="emoji emoji1f464"></span></div><span>1F464</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="boy"><div><span class="emoji emoji1f466"></span></div><span>1F466</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="girl"><div><span class="emoji emoji1f467"></span></div><span>1F467</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="man"><div><span class="emoji emoji1f468"></span></div><span>1F468</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="woman"><div><span class="emoji emoji1f469"></span></div><span>1F469</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="family"><div><span class="emoji emoji1f46a"></span></div><span>1F46A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="man and woman holding hands"><div><span class="emoji emoji1f46b"></span></div><span>1F46B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="police officer"><div><span class="emoji emoji1f46e"></span></div><span>1F46E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="woman with bunny ears"><div><span class="emoji emoji1f46f"></span></div><span>1F46F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bride with veil"><div><span class="emoji emoji1f470"></span></div><span>1F470</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="person with blond hair"><div><span class="emoji emoji1f471"></span></div><span>1F471</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="man with gua pi mao"><div><span class="emoji emoji1f472"></span></div><span>1F472</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="man with turban"><div><span class="emoji emoji1f473"></span></div><span>1F473</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="older man"><div><span class="emoji emoji1f474"></span></div><span>1F474</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="older woman"><div><span class="emoji emoji1f475"></span></div><span>1F475</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="baby"><div><span class="emoji emoji1f476"></span></div><span>1F476</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="construction worker"><div><span class="emoji emoji1f477"></span></div><span>1F477</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="princess"><div><span class="emoji emoji1f478"></span></div><span>1F478</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="japanese ogre"><div><span class="emoji emoji1f479"></span></div><span>1F479</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="japanese goblin"><div><span class="emoji emoji1f47a"></span></div><span>1F47A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="ghost"><div><span class="emoji emoji1f47b"></span></div><span>1F47B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="baby angel"><div><span class="emoji emoji1f47c"></span></div><span>1F47C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="extraterrestrial alien"><div><span class="emoji emoji1f47d"></span></div><span>1F47D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="alien monster"><div><span class="emoji emoji1f47e"></span></div><span>1F47E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="imp"><div><span class="emoji emoji1f47f"></span></div><span>1F47F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="skull"><div><span class="emoji emoji1f480"></span></div><span>1F480</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="information desk person"><div><span class="emoji emoji1f481"></span></div><span>1F481</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="guardsman"><div><span class="emoji emoji1f482"></span></div><span>1F482</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="dancer"><div><span class="emoji emoji1f483"></span></div><span>1F483</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="snail"><div><span class="emoji emoji1f40c"></span></div><span>1F40C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="snake"><div><span class="emoji emoji1f40d"></span></div><span>1F40D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="horse"><div><span class="emoji emoji1f40e"></span></div><span>1F40E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="chicken"><div><span class="emoji emoji1f414"></span></div><span>1F414</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="boar"><div><span class="emoji emoji1f417"></span></div><span>1F417</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bactrian camel"><div><span class="emoji emoji1f42b"></span></div><span>1F42B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="elephant"><div><span class="emoji emoji1f418"></span></div><span>1F418</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="koala"><div><span class="emoji emoji1f428"></span></div><span>1F428</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="monkey"><div><span class="emoji emoji1f412"></span></div><span>1F412</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="sheep"><div><span class="emoji emoji1f411"></span></div><span>1F411</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="octopus"><div><span class="emoji emoji1f419"></span></div><span>1F419</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="spiral shell"><div><span class="emoji emoji1f41a"></span></div><span>1F41A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bug"><div><span class="emoji emoji1f41b"></span></div><span>1F41B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="ant"><div><span class="emoji emoji1f41c"></span></div><span>1F41C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="honeybee"><div><span class="emoji emoji1f41d"></span></div><span>1F41D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="lady beetle"><div><span class="emoji emoji1f41e"></span></div><span>1F41E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="tropical fish"><div><span class="emoji emoji1f420"></span></div><span>1F420</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="blowfish"><div><span class="emoji emoji1f421"></span></div><span>1F421</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="turtle"><div><span class="emoji emoji1f422"></span></div><span>1F422</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="baby chick"><div><span class="emoji emoji1f424"></span></div><span>1F424</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="front-facing baby chick"><div><span class="emoji emoji1f425"></span></div><span>1F425</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bird"><div><span class="emoji emoji1f426"></span></div><span>1F426</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="hatching chick"><div><span class="emoji emoji1f423"></span></div><span>1F423</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="penguin"><div><span class="emoji emoji1f427"></span></div><span>1F427</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="poodle"><div><span class="emoji emoji1f429"></span></div><span>1F429</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="fish"><div><span class="emoji emoji1f41f"></span></div><span>1F41F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="dolphin"><div><span class="emoji emoji1f42c"></span></div><span>1F42C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="mouse face"><div><span class="emoji emoji1f42d"></span></div><span>1F42D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="tiger face"><div><span class="emoji emoji1f42f"></span></div><span>1F42F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="cat face"><div><span class="emoji emoji1f431"></span></div><span>1F431</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="spouting whale"><div><span class="emoji emoji1f433"></span></div><span>1F433</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="horse face"><div><span class="emoji emoji1f434"></span></div><span>1F434</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="monkey face"><div><span class="emoji emoji1f435"></span></div><span>1F435</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="dog face"><div><span class="emoji emoji1f436"></span></div><span>1F436</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="pig face"><div><span class="emoji emoji1f437"></span></div><span>1F437</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bear face"><div><span class="emoji emoji1f43b"></span></div><span>1F43B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="hamster face"><div><span class="emoji emoji1f439"></span></div><span>1F439</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="wolf face"><div><span class="emoji emoji1f43a"></span></div><span>1F43A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="cow face"><div><span class="emoji emoji1f42e"></span></div><span>1F42E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="rabbit face"><div><span class="emoji emoji1f430"></span></div><span>1F430</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="frog face"><div><span class="emoji emoji1f438"></span></div><span>1F438</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="paw prints"><div><span class="emoji emoji1f43e"></span></div><span>1F43E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="dragon face"><div><span class="emoji emoji1f432"></span></div><span>1F432</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="panda face"><div><span class="emoji emoji1f43c"></span></div><span>1F43C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="pig nose"><div><span class="emoji emoji1f43d"></span></div><span>1F43D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="angry face"><div><span class="emoji emoji1f620"></span></div><span>1F620</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="weary face"><div><span class="emoji emoji1f629"></span></div><span>1F629</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="astonished face"><div><span class="emoji emoji1f632"></span></div><span>1F632</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="disappointed face"><div><span class="emoji emoji1f61e"></span></div><span>1F61E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="dizzy face"><div><span class="emoji emoji1f635"></span></div><span>1F635</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="face with open mouth and cold sweat"><div><span class="emoji emoji1f630"></span></div><span>1F630</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="unamused face"><div><span class="emoji emoji1f612"></span></div><span>1F612</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="smiling face with heart-shaped eyes"><div><span class="emoji emoji1f60d"></span></div><span>1F60D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="face with look of triumph"><div><span class="emoji emoji1f624"></span></div><span>1F624</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="face with stuck-out tongue and winking eye"><div><span class="emoji emoji1f61c"></span></div><span>1F61C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="face with stuck-out tongue and tightly-closed eyes"><div><span class="emoji emoji1f61d"></span></div><span>1F61D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="face savouring delicious food"><div><span class="emoji emoji1f60b"></span></div><span>1F60B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="face throwing a kiss"><div><span class="emoji emoji1f618"></span></div><span>1F618</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="kissing face with closed eyes"><div><span class="emoji emoji1f61a"></span></div><span>1F61A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="face with medical mask"><div><span class="emoji emoji1f637"></span></div><span>1F637</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="flushed face"><div><span class="emoji emoji1f633"></span></div><span>1F633</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="smiling face with open mouth"><div><span class="emoji emoji1f603"></span></div><span>1F603</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="smiling face with open mouth and cold sweat"><div><span class="emoji emoji1f605"></span></div><span>1F605</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="smiling face with open mouth and tightly-closed eyes"><div><span class="emoji emoji1f606"></span></div><span>1F606</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="grinning face with smiling eyes"><div><span class="emoji emoji1f601"></span></div><span>1F601</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="face with tears of joy"><div><span class="emoji emoji1f602"></span></div><span>1F602</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="smiling face with smiling eyes"><div><span class="emoji emoji1f60a"></span></div><span>1F60A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="white smiling face"><div><span class="emoji emoji263a"></span></div><span>263A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="smiling face with open mouth and smiling eyes"><div><span class="emoji emoji1f604"></span></div><span>1F604</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="crying face"><div><span class="emoji emoji1f622"></span></div><span>1F622</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="loudly crying face"><div><span class="emoji emoji1f62d"></span></div><span>1F62D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="fearful face"><div><span class="emoji emoji1f628"></span></div><span>1F628</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="persevering face"><div><span class="emoji emoji1f623"></span></div><span>1F623</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="pouting face"><div><span class="emoji emoji1f621"></span></div><span>1F621</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="relieved face"><div><span class="emoji emoji1f60c"></span></div><span>1F60C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="confounded face"><div><span class="emoji emoji1f616"></span></div><span>1F616</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="pensive face"><div><span class="emoji emoji1f614"></span></div><span>1F614</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="face screaming in fear"><div><span class="emoji emoji1f631"></span></div><span>1F631</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="sleepy face"><div><span class="emoji emoji1f62a"></span></div><span>1F62A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="smirking face"><div><span class="emoji emoji1f60f"></span></div><span>1F60F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="face with cold sweat"><div><span class="emoji emoji1f613"></span></div><span>1F613</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="disappointed but relieved face"><div><span class="emoji emoji1f625"></span></div><span>1F625</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="tired face"><div><span class="emoji emoji1f62b"></span></div><span>1F62B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="winking face"><div><span class="emoji emoji1f609"></span></div><span>1F609</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="smiling cat face with open mouth"><div><span class="emoji emoji1f63a"></span></div><span>1F63A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="grinning cat face with smiling eyes"><div><span class="emoji emoji1f638"></span></div><span>1F638</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="cat face with tears of joy"><div><span class="emoji emoji1f639"></span></div><span>1F639</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="kissing cat face with closed eyes"><div><span class="emoji emoji1f63d"></span></div><span>1F63D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="smiling cat face with heart-shaped eyes"><div><span class="emoji emoji1f63b"></span></div><span>1F63B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="crying cat face"><div><span class="emoji emoji1f63f"></span></div><span>1F63F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="pouting cat face"><div><span class="emoji emoji1f63e"></span></div><span>1F63E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="cat face with wry smile"><div><span class="emoji emoji1f63c"></span></div><span>1F63C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="weary cat face"><div><span class="emoji emoji1f640"></span></div><span>1F640</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="face with no good gesture"><div><span class="emoji emoji1f645"></span></div><span>1F645</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="face with ok gesture"><div><span class="emoji emoji1f646"></span></div><span>1F646</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="person bowing deeply"><div><span class="emoji emoji1f647"></span></div><span>1F647</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="see-no-evil monkey"><div><span class="emoji emoji1f648"></span></div><span>1F648</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="speak-no-evil monkey"><div><span class="emoji emoji1f64a"></span></div><span>1F64A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="hear-no-evil monkey"><div><span class="emoji emoji1f649"></span></div><span>1F649</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="happy person raising one hand"><div><span class="emoji emoji1f64b"></span></div><span>1F64B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="person raising both hands in celebration"><div><span class="emoji emoji1f64c"></span></div><span>1F64C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="person frowning"><div><span class="emoji emoji1f64d"></span></div><span>1F64D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="person with pouting face"><div><span class="emoji emoji1f64e"></span></div><span>1F64E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="person with folded hands"><div><span class="emoji emoji1f64f"></span></div><span>1F64F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="house building"><div><span class="emoji emoji1f3e0"></span></div><span>1F3E0</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="house with garden"><div><span class="emoji emoji1f3e1"></span></div><span>1F3E1</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="office building"><div><span class="emoji emoji1f3e2"></span></div><span>1F3E2</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="japanese post office"><div><span class="emoji emoji1f3e3"></span></div><span>1F3E3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="hospital"><div><span class="emoji emoji1f3e5"></span></div><span>1F3E5</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bank"><div><span class="emoji emoji1f3e6"></span></div><span>1F3E6</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="automated teller machine"><div><span class="emoji emoji1f3e7"></span></div><span>1F3E7</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="hotel"><div><span class="emoji emoji1f3e8"></span></div><span>1F3E8</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="love hotel"><div><span class="emoji emoji1f3e9"></span></div><span>1F3E9</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="convenience store"><div><span class="emoji emoji1f3ea"></span></div><span>1F3EA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="school"><div><span class="emoji emoji1f3eb"></span></div><span>1F3EB</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="church"><div><span class="emoji emoji26ea"></span></div><span>26EA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="fountain"><div><span class="emoji emoji26f2"></span></div><span>26F2</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="department store"><div><span class="emoji emoji1f3ec"></span></div><span>1F3EC</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="japanese castle"><div><span class="emoji emoji1f3ef"></span></div><span>1F3EF</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="european castle"><div><span class="emoji emoji1f3f0"></span></div><span>1F3F0</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="factory"><div><span class="emoji emoji1f3ed"></span></div><span>1F3ED</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="anchor"><div><span class="emoji emoji2693"></span></div><span>2693</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="izakaya lantern"><div><span class="emoji emoji1f3ee"></span></div><span>1F3EE</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="mount fuji"><div><span class="emoji emoji1f5fb"></span></div><span>1F5FB</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="tokyo tower"><div><span class="emoji emoji1f5fc"></span></div><span>1F5FC</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="statue of liberty"><div><span class="emoji emoji1f5fd"></span></div><span>1F5FD</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="silhouette of japan"><div><span class="emoji emoji1f5fe"></span></div><span>1F5FE</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="moyai"><div><span class="emoji emoji1f5ff"></span></div><span>1F5FF</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="mans shoe"><div><span class="emoji emoji1f45e"></span></div><span>1F45E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="athletic shoe"><div><span class="emoji emoji1f45f"></span></div><span>1F45F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="high-heeled shoe"><div><span class="emoji emoji1f460"></span></div><span>1F460</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="womans sandal"><div><span class="emoji emoji1f461"></span></div><span>1F461</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="womans boots"><div><span class="emoji emoji1f462"></span></div><span>1F462</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="footprints"><div><span class="emoji emoji1f463"></span></div><span>1F463</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="eyeglasses"><div><span class="emoji emoji1f453"></span></div><span>1F453</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="t-shirt"><div><span class="emoji emoji1f455"></span></div><span>1F455</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="jeans"><div><span class="emoji emoji1f456"></span></div><span>1F456</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="crown"><div><span class="emoji emoji1f451"></span></div><span>1F451</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="necktie"><div><span class="emoji emoji1f454"></span></div><span>1F454</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="womans hat"><div><span class="emoji emoji1f452"></span></div><span>1F452</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="dress"><div><span class="emoji emoji1f457"></span></div><span>1F457</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="kimono"><div><span class="emoji emoji1f458"></span></div><span>1F458</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bikini"><div><span class="emoji emoji1f459"></span></div><span>1F459</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="womans clothes"><div><span class="emoji emoji1f45a"></span></div><span>1F45A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="purse"><div><span class="emoji emoji1f45b"></span></div><span>1F45B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="handbag"><div><span class="emoji emoji1f45c"></span></div><span>1F45C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="pouch"><div><span class="emoji emoji1f45d"></span></div><span>1F45D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="money bag"><div><span class="emoji emoji1f4b0"></span></div><span>1F4B0</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="currency exchange"><div><span class="emoji emoji1f4b1"></span></div><span>1F4B1</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="chart with upwards trend and yen sign"><div><span class="emoji emoji1f4b9"></span></div><span>1F4B9</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="heavy dollar sign"><div><span class="emoji emoji1f4b2"></span></div><span>1F4B2</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="credit card"><div><span class="emoji emoji1f4b3"></span></div><span>1F4B3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="banknote with yen sign"><div><span class="emoji emoji1f4b4"></span></div><span>1F4B4</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="banknote with dollar sign"><div><span class="emoji emoji1f4b5"></span></div><span>1F4B5</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="money with wings"><div><span class="emoji emoji1f4b8"></span></div><span>1F4B8</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="regional indicator symbol letters cn"><div><span class="emoji emoji1f1e81f1f3"></span></div><span>1F1E8 U+1F1F3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="regional indicator symbol letters de"><div><span class="emoji emoji1f1e91f1ea"></span></div><span>1F1E9 U+1F1EA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="regional indicator symbol letters es"><div><span class="emoji emoji1f1ea1f1f8"></span></div><span>1F1EA U+1F1F8</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="regional indicator symbol letters fr"><div><span class="emoji emoji1f1eb1f1f7"></span></div><span>1F1EB U+1F1F7</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="regional indicator symbol letters gb"><div><span class="emoji emoji1f1ec1f1e7"></span></div><span>1F1EC U+1F1E7</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="regional indicator symbol letters it"><div><span class="emoji emoji1f1ee1f1f9"></span></div><span>1F1EE U+1F1F9</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="regional indicator symbol letters jp"><div><span class="emoji emoji1f1ef1f1f5"></span></div><span>1F1EF U+1F1F5</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="regional indicator symbol letters kr"><div><span class="emoji emoji1f1f01f1f7"></span></div><span>1F1F0 U+1F1F7</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="regional indicator symbol letters ru"><div><span class="emoji emoji1f1f71f1fa"></span></div><span>1F1F7 U+1F1FA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="regional indicator symbol letters us"><div><span class="emoji emoji1f1fa1f1f8"></span></div><span>1F1FA U+1F1F8</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="fire"><div><span class="emoji emoji1f525"></span></div><span>1F525</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="electric torch"><div><span class="emoji emoji1f526"></span></div><span>1F526</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="wrench"><div><span class="emoji emoji1f527"></span></div><span>1F527</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="hammer"><div><span class="emoji emoji1f528"></span></div><span>1F528</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="nut and bolt"><div><span class="emoji emoji1f529"></span></div><span>1F529</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="hocho"><div><span class="emoji emoji1f52a"></span></div><span>1F52A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="pistol"><div><span class="emoji emoji1f52b"></span></div><span>1F52B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="crystal ball"><div><span class="emoji emoji1f52e"></span></div><span>1F52E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="six pointed star with middle dot"><div><span class="emoji emoji1f52f"></span></div><span>1F52F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="japanese symbol for beginner"><div><span class="emoji emoji1f530"></span></div><span>1F530</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="trident emblem"><div><span class="emoji emoji1f531"></span></div><span>1F531</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="syringe"><div><span class="emoji emoji1f489"></span></div><span>1F489</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="pill"><div><span class="emoji emoji1f48a"></span></div><span>1F48A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="negative squared latin capital letter a"><div><span class="emoji emoji1f170"></span></div><span>1F170</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="negative squared latin capital letter b"><div><span class="emoji emoji1f171"></span></div><span>1F171</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="negative squared ab"><div><span class="emoji emoji1f18e"></span></div><span>1F18E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="negative squared latin capital letter o"><div><span class="emoji emoji1f17e"></span></div><span>1F17E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="ribbon"><div><span class="emoji emoji1f380"></span></div><span>1F380</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="wrapped present"><div><span class="emoji emoji1f381"></span></div><span>1F381</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="birthday cake"><div><span class="emoji emoji1f382"></span></div><span>1F382</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="christmas tree"><div><span class="emoji emoji1f384"></span></div><span>1F384</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="father christmas"><div><span class="emoji emoji1f385"></span></div><span>1F385</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="crossed flags"><div><span class="emoji emoji1f38c"></span></div><span>1F38C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="fireworks"><div><span class="emoji emoji1f386"></span></div><span>1F386</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="balloon"><div><span class="emoji emoji1f388"></span></div><span>1F388</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="party popper"><div><span class="emoji emoji1f389"></span></div><span>1F389</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="pine decoration"><div><span class="emoji emoji1f38d"></span></div><span>1F38D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="japanese dolls"><div><span class="emoji emoji1f38e"></span></div><span>1F38E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="graduation cap"><div><span class="emoji emoji1f393"></span></div><span>1F393</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="school satchel"><div><span class="emoji emoji1f392"></span></div><span>1F392</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="carp streamer"><div><span class="emoji emoji1f38f"></span></div><span>1F38F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="firework sparkler"><div><span class="emoji emoji1f387"></span></div><span>1F387</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="wind chime"><div><span class="emoji emoji1f390"></span></div><span>1F390</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="jack-o-lantern"><div><span class="emoji emoji1f383"></span></div><span>1F383</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="confetti ball"><div><span class="emoji emoji1f38a"></span></div><span>1F38A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="tanabata tree"><div><span class="emoji emoji1f38b"></span></div><span>1F38B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="moon viewing ceremony"><div><span class="emoji emoji1f391"></span></div><span>1F391</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="pager"><div><span class="emoji emoji1f4df"></span></div><span>1F4DF</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black telephone"><div><span class="emoji emoji260e"></span></div><span>260E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="telephone receiver"><div><span class="emoji emoji1f4de"></span></div><span>1F4DE</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="mobile phone"><div><span class="emoji emoji1f4f1"></span></div><span>1F4F1</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="mobile phone with rightwards arrow at left"><div><span class="emoji emoji1f4f2"></span></div><span>1F4F2</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="memo"><div><span class="emoji emoji1f4dd"></span></div><span>1F4DD</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="fax machine"><div><span class="emoji emoji1f4e0"></span></div><span>1F4E0</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="envelope"><div><span class="emoji emoji2709"></span></div><span>2709</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="incoming envelope"><div><span class="emoji emoji1f4e8"></span></div><span>1F4E8</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="envelope with downwards arrow above"><div><span class="emoji emoji1f4e9"></span></div><span>1F4E9</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="closed mailbox with lowered flag"><div><span class="emoji emoji1f4ea"></span></div><span>1F4EA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="closed mailbox with raised flag"><div><span class="emoji emoji1f4eb"></span></div><span>1F4EB</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="postbox"><div><span class="emoji emoji1f4ee"></span></div><span>1F4EE</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="newspaper"><div><span class="emoji emoji1f4f0"></span></div><span>1F4F0</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="public address loudspeaker"><div><span class="emoji emoji1f4e2"></span></div><span>1F4E2</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="cheering megaphone"><div><span class="emoji emoji1f4e3"></span></div><span>1F4E3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="satellite antenna"><div><span class="emoji emoji1f4e1"></span></div><span>1F4E1</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="outbox tray"><div><span class="emoji emoji1f4e4"></span></div><span>1F4E4</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="inbox tray"><div><span class="emoji emoji1f4e5"></span></div><span>1F4E5</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="package"><div><span class="emoji emoji1f4e6"></span></div><span>1F4E6</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="e-mail symbol"><div><span class="emoji emoji1f4e7"></span></div><span>1F4E7</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="input symbol for latin capital letters"><div><span class="emoji emoji1f520"></span></div><span>1F520</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="input symbol for latin small letters"><div><span class="emoji emoji1f521"></span></div><span>1F521</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="input symbol for numbers"><div><span class="emoji emoji1f522"></span></div><span>1F522</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="input symbol for symbols"><div><span class="emoji emoji1f523"></span></div><span>1F523</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="input symbol for latin letters"><div><span class="emoji emoji1f524"></span></div><span>1F524</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black nib"><div><span class="emoji emoji2712"></span></div><span>2712</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="seat"><div><span class="emoji emoji1f4ba"></span></div><span>1F4BA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="personal computer"><div><span class="emoji emoji1f4bb"></span></div><span>1F4BB</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="pencil"><div><span class="emoji emoji270f"></span></div><span>270F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="paperclip"><div><span class="emoji emoji1f4ce"></span></div><span>1F4CE</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="briefcase"><div><span class="emoji emoji1f4bc"></span></div><span>1F4BC</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="minidisc"><div><span class="emoji emoji1f4bd"></span></div><span>1F4BD</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="floppy disk"><div><span class="emoji emoji1f4be"></span></div><span>1F4BE</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="optical disc"><div><span class="emoji emoji1f4bf"></span></div><span>1F4BF</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="dvd"><div><span class="emoji emoji1f4c0"></span></div><span>1F4C0</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black scissors"><div><span class="emoji emoji2702"></span></div><span>2702</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="round pushpin"><div><span class="emoji emoji1f4cd"></span></div><span>1F4CD</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="page with curl"><div><span class="emoji emoji1f4c3"></span></div><span>1F4C3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="page facing up"><div><span class="emoji emoji1f4c4"></span></div><span>1F4C4</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="calendar"><div><span class="emoji emoji1f4c5"></span></div><span>1F4C5</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="file folder"><div><span class="emoji emoji1f4c1"></span></div><span>1F4C1</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="open file folder"><div><span class="emoji emoji1f4c2"></span></div><span>1F4C2</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="notebook"><div><span class="emoji emoji1f4d3"></span></div><span>1F4D3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="open book"><div><span class="emoji emoji1f4d6"></span></div><span>1F4D6</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="notebook with decorative cover"><div><span class="emoji emoji1f4d4"></span></div><span>1F4D4</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="closed book"><div><span class="emoji emoji1f4d5"></span></div><span>1F4D5</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="green book"><div><span class="emoji emoji1f4d7"></span></div><span>1F4D7</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="blue book"><div><span class="emoji emoji1f4d8"></span></div><span>1F4D8</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="orange book"><div><span class="emoji emoji1f4d9"></span></div><span>1F4D9</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="books"><div><span class="emoji emoji1f4da"></span></div><span>1F4DA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="name badge"><div><span class="emoji emoji1f4db"></span></div><span>1F4DB</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="scroll"><div><span class="emoji emoji1f4dc"></span></div><span>1F4DC</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="clipboard"><div><span class="emoji emoji1f4cb"></span></div><span>1F4CB</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="tear-off calendar"><div><span class="emoji emoji1f4c6"></span></div><span>1F4C6</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bar chart"><div><span class="emoji emoji1f4ca"></span></div><span>1F4CA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="chart with upwards trend"><div><span class="emoji emoji1f4c8"></span></div><span>1F4C8</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="chart with downwards trend"><div><span class="emoji emoji1f4c9"></span></div><span>1F4C9</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="card index"><div><span class="emoji emoji1f4c7"></span></div><span>1F4C7</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="pushpin"><div><span class="emoji emoji1f4cc"></span></div><span>1F4CC</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="ledger"><div><span class="emoji emoji1f4d2"></span></div><span>1F4D2</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="straight ruler"><div><span class="emoji emoji1f4cf"></span></div><span>1F4CF</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="triangular ruler"><div><span class="emoji emoji1f4d0"></span></div><span>1F4D0</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bookmark tabs"><div><span class="emoji emoji1f4d1"></span></div><span>1F4D1</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="running shirt with sash"><div><span class="emoji emoji1f3bd"></span></div><span>1F3BD</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="baseball"><div><span class="emoji emoji26be"></span></div><span>26BE</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="flag in hole"><div><span class="emoji emoji26f3"></span></div><span>26F3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="tennis racquet and ball"><div><span class="emoji emoji1f3be"></span></div><span>1F3BE</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="soccer ball"><div><span class="emoji emoji26bd"></span></div><span>26BD</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="ski and ski boot"><div><span class="emoji emoji1f3bf"></span></div><span>1F3BF</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="basketball and hoop"><div><span class="emoji emoji1f3c0"></span></div><span>1F3C0</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="chequered flag"><div><span class="emoji emoji1f3c1"></span></div><span>1F3C1</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="snowboarder"><div><span class="emoji emoji1f3c2"></span></div><span>1F3C2</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="runner"><div><span class="emoji emoji1f3c3"></span></div><span>1F3C3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="surfer"><div><span class="emoji emoji1f3c4"></span></div><span>1F3C4</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="trophy"><div><span class="emoji emoji1f3c6"></span></div><span>1F3C6</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="american football"><div><span class="emoji emoji1f3c8"></span></div><span>1F3C8</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="swimmer"><div><span class="emoji emoji1f3ca"></span></div><span>1F3CA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="railway car"><div><span class="emoji emoji1f683"></span></div><span>1F683</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="metro"><div><span class="emoji emoji1f687"></span></div><span>1F687</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="circled latin capital letter m"><div><span class="emoji emoji24c2"></span></div><span>24C2</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="high-speed train"><div><span class="emoji emoji1f684"></span></div><span>1F684</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="high-speed train with bullet nose"><div><span class="emoji emoji1f685"></span></div><span>1F685</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="automobile"><div><span class="emoji emoji1f697"></span></div><span>1F697</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="recreational vehicle"><div><span class="emoji emoji1f699"></span></div><span>1F699</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bus"><div><span class="emoji emoji1f68c"></span></div><span>1F68C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bus stop"><div><span class="emoji emoji1f68f"></span></div><span>1F68F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="ship"><div><span class="emoji emoji1f6a2"></span></div><span>1F6A2</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="airplane"><div><span class="emoji emoji2708"></span></div><span>2708</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="sailboat"><div><span class="emoji emoji26f5"></span></div><span>26F5</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="station"><div><span class="emoji emoji1f689"></span></div><span>1F689</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="rocket"><div><span class="emoji emoji1f680"></span></div><span>1F680</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="speedboat"><div><span class="emoji emoji1f6a4"></span></div><span>1F6A4</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="taxi"><div><span class="emoji emoji1f695"></span></div><span>1F695</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="delivery truck"><div><span class="emoji emoji1f69a"></span></div><span>1F69A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="fire engine"><div><span class="emoji emoji1f692"></span></div><span>1F692</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="ambulance"><div><span class="emoji emoji1f691"></span></div><span>1F691</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="police car"><div><span class="emoji emoji1f693"></span></div><span>1F693</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="fuel pump"><div><span class="emoji emoji26fd"></span></div><span>26FD</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="negative squared latin capital letter p"><div><span class="emoji emoji1f17f"></span></div><span>1F17F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="horizontal traffic light"><div><span class="emoji emoji1f6a5"></span></div><span>1F6A5</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="construction sign"><div><span class="emoji emoji1f6a7"></span></div><span>1F6A7</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="police cars revolving light"><div><span class="emoji emoji1f6a8"></span></div><span>1F6A8</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="hot springs"><div><span class="emoji emoji2668"></span></div><span>2668</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="tent"><div><span class="emoji emoji26fa"></span></div><span>26FA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="carousel horse"><div><span class="emoji emoji1f3a0"></span></div><span>1F3A0</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="ferris wheel"><div><span class="emoji emoji1f3a1"></span></div><span>1F3A1</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="roller coaster"><div><span class="emoji emoji1f3a2"></span></div><span>1F3A2</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="fishing pole and fish"><div><span class="emoji emoji1f3a3"></span></div><span>1F3A3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="microphone"><div><span class="emoji emoji1f3a4"></span></div><span>1F3A4</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="movie camera"><div><span class="emoji emoji1f3a5"></span></div><span>1F3A5</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="cinema"><div><span class="emoji emoji1f3a6"></span></div><span>1F3A6</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="headphone"><div><span class="emoji emoji1f3a7"></span></div><span>1F3A7</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="artist palette"><div><span class="emoji emoji1f3a8"></span></div><span>1F3A8</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="top hat"><div><span class="emoji emoji1f3a9"></span></div><span>1F3A9</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="circus tent"><div><span class="emoji emoji1f3aa"></span></div><span>1F3AA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="ticket"><div><span class="emoji emoji1f3ab"></span></div><span>1F3AB</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="clapper board"><div><span class="emoji emoji1f3ac"></span></div><span>1F3AC</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="performing arts"><div><span class="emoji emoji1f3ad"></span></div><span>1F3AD</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="video game"><div><span class="emoji emoji1f3ae"></span></div><span>1F3AE</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="mahjong tile red dragon"><div><span class="emoji emoji1f004"></span></div><span>1F004</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="direct hit"><div><span class="emoji emoji1f3af"></span></div><span>1F3AF</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="slot machine"><div><span class="emoji emoji1f3b0"></span></div><span>1F3B0</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="billiards"><div><span class="emoji emoji1f3b1"></span></div><span>1F3B1</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="game die"><div><span class="emoji emoji1f3b2"></span></div><span>1F3B2</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bowling"><div><span class="emoji emoji1f3b3"></span></div><span>1F3B3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="flower playing cards"><div><span class="emoji emoji1f3b4"></span></div><span>1F3B4</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="playing card black joker"><div><span class="emoji emoji1f0cf"></span></div><span>1F0CF</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="musical note"><div><span class="emoji emoji1f3b5"></span></div><span>1F3B5</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="multiple musical notes"><div><span class="emoji emoji1f3b6"></span></div><span>1F3B6</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="saxophone"><div><span class="emoji emoji1f3b7"></span></div><span>1F3B7</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="guitar"><div><span class="emoji emoji1f3b8"></span></div><span>1F3B8</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="musical keyboard"><div><span class="emoji emoji1f3b9"></span></div><span>1F3B9</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="trumpet"><div><span class="emoji emoji1f3ba"></span></div><span>1F3BA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="violin"><div><span class="emoji emoji1f3bb"></span></div><span>1F3BB</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="musical score"><div><span class="emoji emoji1f3bc"></span></div><span>1F3BC</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="part alternation mark"><div><span class="emoji emoji303d"></span></div><span>303D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="camera"><div><span class="emoji emoji1f4f7"></span></div><span>1F4F7</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="video camera"><div><span class="emoji emoji1f4f9"></span></div><span>1F4F9</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="television"><div><span class="emoji emoji1f4fa"></span></div><span>1F4FA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="radio"><div><span class="emoji emoji1f4fb"></span></div><span>1F4FB</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="videocassette"><div><span class="emoji emoji1f4fc"></span></div><span>1F4FC</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="kiss mark"><div><span class="emoji emoji1f48b"></span></div><span>1F48B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="love letter"><div><span class="emoji emoji1f48c"></span></div><span>1F48C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="ring"><div><span class="emoji emoji1f48d"></span></div><span>1F48D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="gem stone"><div><span class="emoji emoji1f48e"></span></div><span>1F48E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="kiss"><div><span class="emoji emoji1f48f"></span></div><span>1F48F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bouquet"><div><span class="emoji emoji1f490"></span></div><span>1F490</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="couple with heart"><div><span class="emoji emoji1f491"></span></div><span>1F491</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="wedding"><div><span class="emoji emoji1f492"></span></div><span>1F492</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="no one under eighteen symbol"><div><span class="emoji emoji1f51e"></span></div><span>1F51E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="copyright sign"><div><span class="emoji emojia9"></span></div><span>00A9</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="registered sign"><div><span class="emoji emojiae"></span></div><span>00AE</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="trade mark sign"><div><span class="emoji emoji2122"></span></div><span>2122</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="information source"><div><span class="emoji emoji2139"></span></div><span>2139</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="hash key"><div><span class="emoji emoji2320e3"></span></div><span>0023 U+20E3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="keycap 1"><div><span class="emoji emoji3120e3"></span></div><span>0031 U+20E3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="keycap 2"><div><span class="emoji emoji3220e3"></span></div><span>0032 U+20E3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="keycap 3"><div><span class="emoji emoji3320e3"></span></div><span>0033 U+20E3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="keycap 4"><div><span class="emoji emoji3420e3"></span></div><span>0034 U+20E3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="keycap 5"><div><span class="emoji emoji3520e3"></span></div><span>0035 U+20E3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="keycap 6"><div><span class="emoji emoji3620e3"></span></div><span>0036 U+20E3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="keycap 7"><div><span class="emoji emoji3720e3"></span></div><span>0037 U+20E3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="keycap 8"><div><span class="emoji emoji3820e3"></span></div><span>0038 U+20E3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="keycap 9"><div><span class="emoji emoji3920e3"></span></div><span>0039 U+20E3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="keycap 0"><div><span class="emoji emoji3020e3"></span></div><span>0030 U+20E3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="keycap ten"><div><span class="emoji emoji1f51f"></span></div><span>1F51F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="antenna with bars"><div><span class="emoji emoji1f4f6"></span></div><span>1F4F6</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="vibration mode"><div><span class="emoji emoji1f4f3"></span></div><span>1F4F3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="mobile phone off"><div><span class="emoji emoji1f4f4"></span></div><span>1F4F4</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="hamburger"><div><span class="emoji emoji1f354"></span></div><span>1F354</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="rice ball"><div><span class="emoji emoji1f359"></span></div><span>1F359</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="shortcake"><div><span class="emoji emoji1f370"></span></div><span>1F370</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="steaming bowl"><div><span class="emoji emoji1f35c"></span></div><span>1F35C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bread"><div><span class="emoji emoji1f35e"></span></div><span>1F35E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="cooking"><div><span class="emoji emoji1f373"></span></div><span>1F373</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="soft ice cream"><div><span class="emoji emoji1f366"></span></div><span>1F366</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="french fries"><div><span class="emoji emoji1f35f"></span></div><span>1F35F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="dango"><div><span class="emoji emoji1f361"></span></div><span>1F361</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="rice cracker"><div><span class="emoji emoji1f358"></span></div><span>1F358</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="cooked rice"><div><span class="emoji emoji1f35a"></span></div><span>1F35A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="spaghetti"><div><span class="emoji emoji1f35d"></span></div><span>1F35D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="curry and rice"><div><span class="emoji emoji1f35b"></span></div><span>1F35B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="oden"><div><span class="emoji emoji1f362"></span></div><span>1F362</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="sushi"><div><span class="emoji emoji1f363"></span></div><span>1F363</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bento box"><div><span class="emoji emoji1f371"></span></div><span>1F371</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="pot of food"><div><span class="emoji emoji1f372"></span></div><span>1F372</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="shaved ice"><div><span class="emoji emoji1f367"></span></div><span>1F367</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="meat on bone"><div><span class="emoji emoji1f356"></span></div><span>1F356</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="fish cake with swirl design"><div><span class="emoji emoji1f365"></span></div><span>1F365</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="roasted sweet potato"><div><span class="emoji emoji1f360"></span></div><span>1F360</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="slice of pizza"><div><span class="emoji emoji1f355"></span></div><span>1F355</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="poultry leg"><div><span class="emoji emoji1f357"></span></div><span>1F357</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="ice cream"><div><span class="emoji emoji1f368"></span></div><span>1F368</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="doughnut"><div><span class="emoji emoji1f369"></span></div><span>1F369</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="cookie"><div><span class="emoji emoji1f36a"></span></div><span>1F36A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="chocolate bar"><div><span class="emoji emoji1f36b"></span></div><span>1F36B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="candy"><div><span class="emoji emoji1f36c"></span></div><span>1F36C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="lollipop"><div><span class="emoji emoji1f36d"></span></div><span>1F36D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="custard"><div><span class="emoji emoji1f36e"></span></div><span>1F36E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="honey pot"><div><span class="emoji emoji1f36f"></span></div><span>1F36F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="fried shrimp"><div><span class="emoji emoji1f364"></span></div><span>1F364</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="fork and knife"><div><span class="emoji emoji1f374"></span></div><span>1F374</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="hot beverage"><div><span class="emoji emoji2615"></span></div><span>2615</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="cocktail glass"><div><span class="emoji emoji1f378"></span></div><span>1F378</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="beer mug"><div><span class="emoji emoji1f37a"></span></div><span>1F37A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="teacup without handle"><div><span class="emoji emoji1f375"></span></div><span>1F375</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="sake bottle and cup"><div><span class="emoji emoji1f376"></span></div><span>1F376</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="wine glass"><div><span class="emoji emoji1f377"></span></div><span>1F377</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="clinking beer mugs"><div><span class="emoji emoji1f37b"></span></div><span>1F37B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="tropical drink"><div><span class="emoji emoji1f379"></span></div><span>1F379</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="north east arrow"><div><span class="emoji emoji2197"></span></div><span>2197</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="south east arrow"><div><span class="emoji emoji2198"></span></div><span>2198</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="north west arrow"><div><span class="emoji emoji2196"></span></div><span>2196</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="south west arrow"><div><span class="emoji emoji2199"></span></div><span>2199</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="arrow pointing rightwards then curving upwards"><div><span class="emoji emoji2934"></span></div><span>2934</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="arrow pointing rightwards then curving downwards"><div><span class="emoji emoji2935"></span></div><span>2935</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="left right arrow"><div><span class="emoji emoji2194"></span></div><span>2194</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="up down arrow"><div><span class="emoji emoji2195"></span></div><span>2195</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="upwards black arrow"><div><span class="emoji emoji2b06"></span></div><span>2B06</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="downwards black arrow"><div><span class="emoji emoji2b07"></span></div><span>2B07</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black rightwards arrow"><div><span class="emoji emoji27a1"></span></div><span>27A1</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="leftwards black arrow"><div><span class="emoji emoji2b05"></span></div><span>2B05</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black right-pointing triangle"><div><span class="emoji emoji25b6"></span></div><span>25B6</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black left-pointing triangle"><div><span class="emoji emoji25c0"></span></div><span>25C0</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black right-pointing double triangle"><div><span class="emoji emoji23e9"></span></div><span>23E9</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black left-pointing double triangle"><div><span class="emoji emoji23ea"></span></div><span>23EA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black up-pointing double triangle"><div><span class="emoji emoji23eb"></span></div><span>23EB</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black down-pointing double triangle"><div><span class="emoji emoji23ec"></span></div><span>23EC</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="up-pointing red triangle"><div><span class="emoji emoji1f53a"></span></div><span>1F53A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="down-pointing red triangle"><div><span class="emoji emoji1f53b"></span></div><span>1F53B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="up-pointing small red triangle"><div><span class="emoji emoji1f53c"></span></div><span>1F53C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="down-pointing small red triangle"><div><span class="emoji emoji1f53d"></span></div><span>1F53D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="heavy large circle"><div><span class="emoji emoji2b55"></span></div><span>2B55</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="cross mark"><div><span class="emoji emoji274c"></span></div><span>274C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="negative squared cross mark"><div><span class="emoji emoji274e"></span></div><span>274E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="heavy exclamation mark symbol"><div><span class="emoji emoji2757"></span></div><span>2757</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="exclamation question mark"><div><span class="emoji emoji2049"></span></div><span>2049</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="double exclamation mark"><div><span class="emoji emoji203c"></span></div><span>203C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black question mark ornament"><div><span class="emoji emoji2753"></span></div><span>2753</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="white question mark ornament"><div><span class="emoji emoji2754"></span></div><span>2754</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="white exclamation mark ornament"><div><span class="emoji emoji2755"></span></div><span>2755</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="wavy dash"><div><span class="emoji emoji3030"></span></div><span>3030</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="curly loop"><div><span class="emoji emoji27b0"></span></div><span>27B0</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="double curly loop"><div><span class="emoji emoji27bf"></span></div><span>27BF</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="heavy black heart"><div><span class="emoji emoji2764"></span></div><span>2764</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="beating heart"><div><span class="emoji emoji1f493"></span></div><span>1F493</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="broken heart"><div><span class="emoji emoji1f494"></span></div><span>1F494</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="two hearts"><div><span class="emoji emoji1f495"></span></div><span>1F495</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="sparkling heart"><div><span class="emoji emoji1f496"></span></div><span>1F496</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="growing heart"><div><span class="emoji emoji1f497"></span></div><span>1F497</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="heart with arrow"><div><span class="emoji emoji1f498"></span></div><span>1F498</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="blue heart"><div><span class="emoji emoji1f499"></span></div><span>1F499</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="green heart"><div><span class="emoji emoji1f49a"></span></div><span>1F49A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="yellow heart"><div><span class="emoji emoji1f49b"></span></div><span>1F49B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="purple heart"><div><span class="emoji emoji1f49c"></span></div><span>1F49C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="heart with ribbon"><div><span class="emoji emoji1f49d"></span></div><span>1F49D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="revolving hearts"><div><span class="emoji emoji1f49e"></span></div><span>1F49E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="heart decoration"><div><span class="emoji emoji1f49f"></span></div><span>1F49F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black heart suit"><div><span class="emoji emoji2665"></span></div><span>2665</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black spade suit"><div><span class="emoji emoji2660"></span></div><span>2660</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black diamond suit"><div><span class="emoji emoji2666"></span></div><span>2666</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black club suit"><div><span class="emoji emoji2663"></span></div><span>2663</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="smoking symbol"><div><span class="emoji emoji1f6ac"></span></div><span>1F6AC</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="no smoking symbol"><div><span class="emoji emoji1f6ad"></span></div><span>1F6AD</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="wheelchair symbol"><div><span class="emoji emoji267f"></span></div><span>267F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="triangular flag on post"><div><span class="emoji emoji1f6a9"></span></div><span>1F6A9</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="warning sign"><div><span class="emoji emoji26a0"></span></div><span>26A0</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="no entry"><div><span class="emoji emoji26d4"></span></div><span>26D4</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black universal recycling symbol"><div><span class="emoji emoji267b"></span></div><span>267B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bicycle"><div><span class="emoji emoji1f6b2"></span></div><span>1F6B2</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="pedestrian"><div><span class="emoji emoji1f6b6"></span></div><span>1F6B6</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="mens symbol"><div><span class="emoji emoji1f6b9"></span></div><span>1F6B9</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="womens symbol"><div><span class="emoji emoji1f6ba"></span></div><span>1F6BA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bath"><div><span class="emoji emoji1f6c0"></span></div><span>1F6C0</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="restroom"><div><span class="emoji emoji1f6bb"></span></div><span>1F6BB</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="toilet"><div><span class="emoji emoji1f6bd"></span></div><span>1F6BD</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="water closet"><div><span class="emoji emoji1f6be"></span></div><span>1F6BE</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="baby symbol"><div><span class="emoji emoji1f6bc"></span></div><span>1F6BC</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="door"><div><span class="emoji emoji1f6aa"></span></div><span>1F6AA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="no entry sign"><div><span class="emoji emoji1f6ab"></span></div><span>1F6AB</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="heavy check mark"><div><span class="emoji emoji2714"></span></div><span>2714</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared cl"><div><span class="emoji emoji1f191"></span></div><span>1F191</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared cool"><div><span class="emoji emoji1f192"></span></div><span>1F192</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared free"><div><span class="emoji emoji1f193"></span></div><span>1F193</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared id"><div><span class="emoji emoji1f194"></span></div><span>1F194</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared new"><div><span class="emoji emoji1f195"></span></div><span>1F195</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared ng"><div><span class="emoji emoji1f196"></span></div><span>1F196</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared ok"><div><span class="emoji emoji1f197"></span></div><span>1F197</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared sos"><div><span class="emoji emoji1f198"></span></div><span>1F198</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared up with exclamation mark"><div><span class="emoji emoji1f199"></span></div><span>1F199</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared vs"><div><span class="emoji emoji1f19a"></span></div><span>1F19A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared katakana koko"><div><span class="emoji emoji1f201"></span></div><span>1F201</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared katakana sa"><div><span class="emoji emoji1f202"></span></div><span>1F202</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared cjk unified ideograph-7981"><div><span class="emoji emoji1f232"></span></div><span>1F232</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared cjk unified ideograph-7a7a"><div><span class="emoji emoji1f233"></span></div><span>1F233</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared cjk unified ideograph-5408"><div><span class="emoji emoji1f234"></span></div><span>1F234</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared cjk unified ideograph-6e80"><div><span class="emoji emoji1f235"></span></div><span>1F235</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared cjk unified ideograph-6709"><div><span class="emoji emoji1f236"></span></div><span>1F236</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared cjk unified ideograph-7121"><div><span class="emoji emoji1f21a"></span></div><span>1F21A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared cjk unified ideograph-6708"><div><span class="emoji emoji1f237"></span></div><span>1F237</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared cjk unified ideograph-7533"><div><span class="emoji emoji1f238"></span></div><span>1F238</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared cjk unified ideograph-5272"><div><span class="emoji emoji1f239"></span></div><span>1F239</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared cjk unified ideograph-6307"><div><span class="emoji emoji1f22f"></span></div><span>1F22F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared cjk unified ideograph-55b6"><div><span class="emoji emoji1f23a"></span></div><span>1F23A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="circled ideograph secret"><div><span class="emoji emoji3299"></span></div><span>3299</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="circled ideograph congratulation"><div><span class="emoji emoji3297"></span></div><span>3297</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="circled ideograph advantage"><div><span class="emoji emoji1f250"></span></div><span>1F250</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="circled ideograph accept"><div><span class="emoji emoji1f251"></span></div><span>1F251</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="heavy plus sign"><div><span class="emoji emoji2795"></span></div><span>2795</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="heavy minus sign"><div><span class="emoji emoji2796"></span></div><span>2796</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="heavy multiplication x"><div><span class="emoji emoji2716"></span></div><span>2716</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="heavy division sign"><div><span class="emoji emoji2797"></span></div><span>2797</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="diamond shape with a dot inside"><div><span class="emoji emoji1f4a0"></span></div><span>1F4A0</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="electric light bulb"><div><span class="emoji emoji1f4a1"></span></div><span>1F4A1</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="anger symbol"><div><span class="emoji emoji1f4a2"></span></div><span>1F4A2</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bomb"><div><span class="emoji emoji1f4a3"></span></div><span>1F4A3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="sleeping symbol"><div><span class="emoji emoji1f4a4"></span></div><span>1F4A4</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="collision symbol"><div><span class="emoji emoji1f4a5"></span></div><span>1F4A5</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="splashing sweat symbol"><div><span class="emoji emoji1f4a6"></span></div><span>1F4A6</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="droplet"><div><span class="emoji emoji1f4a7"></span></div><span>1F4A7</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="dash symbol"><div><span class="emoji emoji1f4a8"></span></div><span>1F4A8</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="pile of poo"><div><span class="emoji emoji1f4a9"></span></div><span>1F4A9</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="flexed biceps"><div><span class="emoji emoji1f4aa"></span></div><span>1F4AA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="dizzy symbol"><div><span class="emoji emoji1f4ab"></span></div><span>1F4AB</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="speech balloon"><div><span class="emoji emoji1f4ac"></span></div><span>1F4AC</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="sparkles"><div><span class="emoji emoji2728"></span></div><span>2728</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="eight pointed black star"><div><span class="emoji emoji2734"></span></div><span>2734</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="eight spoked asterisk"><div><span class="emoji emoji2733"></span></div><span>2733</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="medium white circle"><div><span class="emoji emoji26aa"></span></div><span>26AA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="medium black circle"><div><span class="emoji emoji26ab"></span></div><span>26AB</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="large red circle"><div><span class="emoji emoji1f534"></span></div><span>1F534</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="large blue circle"><div><span class="emoji emoji1f535"></span></div><span>1F535</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black square button"><div><span class="emoji emoji1f532"></span></div><span>1F532</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="white square button"><div><span class="emoji emoji1f533"></span></div><span>1F533</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="white medium star"><div><span class="emoji emoji2b50"></span></div><span>2B50</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="white large square"><div><span class="emoji emoji2b1c"></span></div><span>2B1C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black large square"><div><span class="emoji emoji2b1b"></span></div><span>2B1B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="white small square"><div><span class="emoji emoji25ab"></span></div><span>25AB</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black small square"><div><span class="emoji emoji25aa"></span></div><span>25AA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="white medium small square"><div><span class="emoji emoji25fd"></span></div><span>25FD</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black medium small square"><div><span class="emoji emoji25fe"></span></div><span>25FE</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="white medium square"><div><span class="emoji emoji25fb"></span></div><span>25FB</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black medium square"><div><span class="emoji emoji25fc"></span></div><span>25FC</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="large orange diamond"><div><span class="emoji emoji1f536"></span></div><span>1F536</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="large blue diamond"><div><span class="emoji emoji1f537"></span></div><span>1F537</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="small orange diamond"><div><span class="emoji emoji1f538"></span></div><span>1F538</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="small blue diamond"><div><span class="emoji emoji1f539"></span></div><span>1F539</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="sparkle"><div><span class="emoji emoji2747"></span></div><span>2747</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="white flower"><div><span class="emoji emoji1f4ae"></span></div><span>1F4AE</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="hundred points symbol"><div><span class="emoji emoji1f4af"></span></div><span>1F4AF</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="leftwards arrow with hook"><div><span class="emoji emoji21a9"></span></div><span>21A9</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="rightwards arrow with hook"><div><span class="emoji emoji21aa"></span></div><span>21AA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="clockwise downwards and upwards open circle arrows"><div><span class="emoji emoji1f503"></span></div><span>1F503</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="speaker with three sound waves"><div><span class="emoji emoji1f50a"></span></div><span>1F50A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="battery"><div><span class="emoji emoji1f50b"></span></div><span>1F50B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="electric plug"><div><span class="emoji emoji1f50c"></span></div><span>1F50C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="left-pointing magnifying glass"><div><span class="emoji emoji1f50d"></span></div><span>1F50D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="right-pointing magnifying glass"><div><span class="emoji emoji1f50e"></span></div><span>1F50E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="lock"><div><span class="emoji emoji1f512"></span></div><span>1F512</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="open lock"><div><span class="emoji emoji1f513"></span></div><span>1F513</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="lock with ink pen"><div><span class="emoji emoji1f50f"></span></div><span>1F50F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="closed lock with key"><div><span class="emoji emoji1f510"></span></div><span>1F510</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="key"><div><span class="emoji emoji1f511"></span></div><span>1F511</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bell"><div><span class="emoji emoji1f514"></span></div><span>1F514</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="ballot box with check"><div><span class="emoji emoji2611"></span></div><span>2611</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="radio button"><div><span class="emoji emoji1f518"></span></div><span>1F518</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bookmark"><div><span class="emoji emoji1f516"></span></div><span>1F516</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="link symbol"><div><span class="emoji emoji1f517"></span></div><span>1F517</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="back with leftwards arrow above"><div><span class="emoji emoji1f519"></span></div><span>1F519</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="end with leftwards arrow above"><div><span class="emoji emoji1f51a"></span></div><span>1F51A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="on with exclamation mark with left right arrow above"><div><span class="emoji emoji1f51b"></span></div><span>1F51B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="soon with rightwards arrow above"><div><span class="emoji emoji1f51c"></span></div><span>1F51C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="top with upwards arrow above"><div><span class="emoji emoji1f51d"></span></div><span>1F51D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="white heavy check mark"><div><span class="emoji emoji2705"></span></div><span>2705</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="raised fist"><div><span class="emoji emoji270a"></span></div><span>270A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="raised hand"><div><span class="emoji emoji270b"></span></div><span>270B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="victory hand"><div><span class="emoji emoji270c"></span></div><span>270C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="fisted hand sign"><div><span class="emoji emoji1f44a"></span></div><span>1F44A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="thumbs up sign"><div><span class="emoji emoji1f44d"></span></div><span>1F44D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="white up pointing index"><div><span class="emoji emoji261d"></span></div><span>261D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="white up pointing backhand index"><div><span class="emoji emoji1f446"></span></div><span>1F446</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="white down pointing backhand index"><div><span class="emoji emoji1f447"></span></div><span>1F447</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="white left pointing backhand index"><div><span class="emoji emoji1f448"></span></div><span>1F448</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="white right pointing backhand index"><div><span class="emoji emoji1f449"></span></div><span>1F449</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="waving hand sign"><div><span class="emoji emoji1f44b"></span></div><span>1F44B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="clapping hands sign"><div><span class="emoji emoji1f44f"></span></div><span>1F44F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="ok hand sign"><div><span class="emoji emoji1f44c"></span></div><span>1F44C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="thumbs down sign"><div><span class="emoji emoji1f44e"></span></div><span>1F44E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="open hands sign"><div><span class="emoji emoji1f450"></span></div><span>1F450</span></a> </div> </div>
JoelPub/wordpress-amazon
order/themes/web/default/site/emoji.html
HTML
gpl-2.0
111,701
{{#each this}} <dl> <dt>ID: {{this}}</dt> <dd><button data-sincro-id="{{this}}" type="button" class="btn btn-md btn-default sincro-resultados-btn"><span class="glyphicon glyphicon-send" data-sincro-id="{{this}}"></span></button></dd> {{/each}}
mrvik/estudio
cont/sincro-resultados.html
HTML
gpl-2.0
249
/**************************************************************************** Copyright 2011 Jeff Lamarche Copyright 2012 Goffredo Marocchi Copyright 2012 Ricardo Quesada Copyright 2012 cocos2d-x.org Copyright 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef __CCGLPROGRAM_H__ #define __CCGLPROGRAM_H__ #include <unordered_map> #include "base/ccMacros.h" #include "base/CCRef.h" #include "base/ccTypes.h" #include "platform/CCGL.h" #include "math/CCMath.h" NS_CC_BEGIN /** * @addtogroup shaders * @{ */ struct _hashUniformEntry; class GLProgram; typedef void (*GLInfoFunction)(GLuint program, GLenum pname, GLint* params); typedef void (*GLLogFunction) (GLuint program, GLsizei bufsize, GLsizei* length, GLchar* infolog); struct VertexAttrib { GLuint index; GLint size; GLenum type; std::string name; }; struct Uniform { GLint location; GLint size; GLenum type; std::string name; }; /** GLProgram Class that implements a glProgram @since v2.0.0 */ class CC_DLL GLProgram : public Ref { friend class GLProgramState; public: enum { VERTEX_ATTRIB_POSITION, VERTEX_ATTRIB_COLOR, VERTEX_ATTRIB_TEX_COORD, VERTEX_ATTRIB_TEX_COORD1, VERTEX_ATTRIB_TEX_COORD2, VERTEX_ATTRIB_TEX_COORD3, VERTEX_ATTRIB_TEX_COORD4, VERTEX_ATTRIB_TEX_COORD5, VERTEX_ATTRIB_TEX_COORD6, VERTEX_ATTRIB_TEX_COORD7, VERTEX_ATTRIB_NORMAL, VERTEX_ATTRIB_BLEND_WEIGHT, VERTEX_ATTRIB_BLEND_INDEX, VERTEX_ATTRIB_MAX, // backward compatibility VERTEX_ATTRIB_TEX_COORDS = VERTEX_ATTRIB_TEX_COORD, }; enum { UNIFORM_P_MATRIX, UNIFORM_MV_MATRIX, UNIFORM_MVP_MATRIX, UNIFORM_TIME, UNIFORM_SIN_TIME, UNIFORM_COS_TIME, UNIFORM_RANDOM01, UNIFORM_SAMPLER0, UNIFORM_SAMPLER1, UNIFORM_SAMPLER2, UNIFORM_SAMPLER3, UNIFORM_MAX, }; static const char* SHADER_NAME_POSITION_TEXTURE_COLOR; static const char* SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP; static const char* SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST; static const char* SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST_NO_MV; static const char* SHADER_NAME_POSITION_COLOR; static const char* SHADER_NAME_POSITION_COLOR_NO_MVP; static const char* SHADER_NAME_POSITION_TEXTURE; static const char* SHADER_NAME_POSITION_TEXTURE_U_COLOR; static const char* SHADER_NAME_POSITION_TEXTURE_A8_COLOR; static const char* SHADER_NAME_POSITION_U_COLOR; static const char* SHADER_NAME_POSITION_LENGTH_TEXTURE_COLOR; static const char* SHADER_NAME_LABEL_NORMAL; static const char* SHADER_NAME_LABEL_OUTLINE; static const char* SHADER_NAME_LABEL_DISTANCEFIELD_NORMAL; static const char* SHADER_NAME_LABEL_DISTANCEFIELD_GLOW; //3D static const char* SHADER_3D_POSITION; static const char* SHADER_3D_POSITION_TEXTURE; static const char* SHADER_3D_SKINPOSITION_TEXTURE; // uniform names static const char* UNIFORM_NAME_P_MATRIX; static const char* UNIFORM_NAME_MV_MATRIX; static const char* UNIFORM_NAME_MVP_MATRIX; static const char* UNIFORM_NAME_TIME; static const char* UNIFORM_NAME_SIN_TIME; static const char* UNIFORM_NAME_COS_TIME; static const char* UNIFORM_NAME_RANDOM01; static const char* UNIFORM_NAME_SAMPLER0; static const char* UNIFORM_NAME_SAMPLER1; static const char* UNIFORM_NAME_SAMPLER2; static const char* UNIFORM_NAME_SAMPLER3; static const char* UNIFORM_NAME_ALPHA_TEST_VALUE; // Attribute names static const char* ATTRIBUTE_NAME_COLOR; static const char* ATTRIBUTE_NAME_POSITION; static const char* ATTRIBUTE_NAME_TEX_COORD; static const char* ATTRIBUTE_NAME_TEX_COORD1; static const char* ATTRIBUTE_NAME_TEX_COORD2; static const char* ATTRIBUTE_NAME_TEX_COORD3; static const char* ATTRIBUTE_NAME_TEX_COORD4; static const char* ATTRIBUTE_NAME_TEX_COORD5; static const char* ATTRIBUTE_NAME_TEX_COORD6; static const char* ATTRIBUTE_NAME_TEX_COORD7; static const char* ATTRIBUTE_NAME_NORMAL; static const char* ATTRIBUTE_NAME_BLEND_WEIGHT; static const char* ATTRIBUTE_NAME_BLEND_INDEX; GLProgram(); virtual ~GLProgram(); /** Initializes the GLProgram with a vertex and fragment with bytes array * @js initWithString * @lua initWithString */ #if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) /** Initializes the CCGLProgram with precompiled shader program */ static GLProgram* createWithPrecompiledProgramByteArray(const GLchar* vShaderByteArray, const GLchar* fShaderByteArray); bool initWithPrecompiledProgramByteArray(const GLchar* vShaderByteArray, const GLchar* fShaderByteArray); #endif /** Initializes the GLProgram with a vertex and fragment with bytes array * @js initWithString * @lua initWithString */ static GLProgram* createWithByteArrays(const GLchar* vShaderByteArray, const GLchar* fShaderByteArray); bool initWithByteArrays(const GLchar* vShaderByteArray, const GLchar* fShaderByteArray); /** Initializes the GLProgram with a vertex and fragment with contents of filenames * @js init * @lua init */ static GLProgram* createWithFilenames(const std::string& vShaderFilename, const std::string& fShaderFilename); bool initWithFilenames(const std::string& vShaderFilename, const std::string& fShaderFilename); //void bindUniform(std::string uniformName, int value); Uniform* getUniform(const std::string& name); VertexAttrib* getVertexAttrib(const std::string& name); /** It will add a new attribute to the shader by calling glBindAttribLocation */ void bindAttribLocation(const std::string& attributeName, GLuint index) const; /** calls glGetAttribLocation */ GLint getAttribLocation(const std::string& attributeName) const; /** calls glGetUniformLocation() */ GLint getUniformLocation(const std::string& attributeName) const; /** links the glProgram */ bool link(); /** it will call glUseProgram() */ void use(); /** It will create 4 uniforms: - kUniformPMatrix - kUniformMVMatrix - kUniformMVPMatrix - GLProgram::UNIFORM_SAMPLER And it will bind "GLProgram::UNIFORM_SAMPLER" to 0 */ void updateUniforms(); /** calls retrieves the named uniform location for this shader program. */ GLint getUniformLocationForName(const char* name) const; /** calls glUniform1i only if the values are different than the previous call for this same shader program. * @js setUniformLocationI32 * @lua setUniformLocationI32 */ void setUniformLocationWith1i(GLint location, GLint i1); /** calls glUniform2i only if the values are different than the previous call for this same shader program. */ void setUniformLocationWith2i(GLint location, GLint i1, GLint i2); /** calls glUniform3i only if the values are different than the previous call for this same shader program. */ void setUniformLocationWith3i(GLint location, GLint i1, GLint i2, GLint i3); /** calls glUniform4i only if the values are different than the previous call for this same shader program. */ void setUniformLocationWith4i(GLint location, GLint i1, GLint i2, GLint i3, GLint i4); /** calls glUniform2iv only if the values are different than the previous call for this same shader program. */ void setUniformLocationWith2iv(GLint location, GLint* ints, unsigned int numberOfArrays); /** calls glUniform3iv only if the values are different than the previous call for this same shader program. */ void setUniformLocationWith3iv(GLint location, GLint* ints, unsigned int numberOfArrays); /** calls glUniform4iv only if the values are different than the previous call for this same shader program. */ void setUniformLocationWith4iv(GLint location, GLint* ints, unsigned int numberOfArrays); /** calls glUniform1f only if the values are different than the previous call for this same shader program. * In js or lua,please use setUniformLocationF32 * @js NA */ void setUniformLocationWith1f(GLint location, GLfloat f1); /** calls glUniform2f only if the values are different than the previous call for this same shader program. * In js or lua,please use setUniformLocationF32 * @js NA */ void setUniformLocationWith2f(GLint location, GLfloat f1, GLfloat f2); /** calls glUniform3f only if the values are different than the previous call for this same shader program. * In js or lua,please use setUniformLocationF32 * @js NA */ void setUniformLocationWith3f(GLint location, GLfloat f1, GLfloat f2, GLfloat f3); /** calls glUniform4f only if the values are different than the previous call for this same shader program. * In js or lua,please use setUniformLocationF32 * @js NA */ void setUniformLocationWith4f(GLint location, GLfloat f1, GLfloat f2, GLfloat f3, GLfloat f4); /** calls glUniform2fv only if the values are different than the previous call for this same shader program. */ void setUniformLocationWith2fv(GLint location, const GLfloat* floats, unsigned int numberOfArrays); /** calls glUniform3fv only if the values are different than the previous call for this same shader program. */ void setUniformLocationWith3fv(GLint location, const GLfloat* floats, unsigned int numberOfArrays); /** calls glUniform4fv only if the values are different than the previous call for this same shader program. */ void setUniformLocationWith4fv(GLint location, const GLfloat* floats, unsigned int numberOfArrays); /** calls glUniformMatrix2fv only if the values are different than the previous call for this same shader program. */ void setUniformLocationWithMatrix2fv(GLint location, const GLfloat* matrixArray, unsigned int numberOfMatrices); /** calls glUniformMatrix3fv only if the values are different than the previous call for this same shader program. */ void setUniformLocationWithMatrix3fv(GLint location, const GLfloat* matrixArray, unsigned int numberOfMatrices); /** calls glUniformMatrix4fv only if the values are different than the previous call for this same shader program. */ void setUniformLocationWithMatrix4fv(GLint location, const GLfloat* matrixArray, unsigned int numberOfMatrices); /** will update the builtin uniforms if they are different than the previous call for this same shader program. */ void setUniformsForBuiltins(); void setUniformsForBuiltins(const Mat4 &modelView); // Attribute /** returns the vertexShader error log */ std::string getVertexShaderLog() const; /** returns the fragmentShader error log */ std::string getFragmentShaderLog() const; /** returns the program error log */ std::string getProgramLog() const; // reload all shaders, this function is designed for android // when opengl context lost, so don't call it. void reset(); inline const GLuint getProgram() const { return _program; } // DEPRECATED CC_DEPRECATED_ATTRIBUTE bool initWithVertexShaderByteArray(const GLchar* vertexByteArray, const GLchar* fragByteArray) { return initWithByteArrays(vertexByteArray, fragByteArray); } CC_DEPRECATED_ATTRIBUTE bool initWithVertexShaderFilename(const std::string &vertexFilename, const std::string& fragFilename) { return initWithFilenames(vertexFilename, fragFilename); } CC_DEPRECATED_ATTRIBUTE void addAttribute(const std::string &attributeName, GLuint index) const { return bindAttribLocation(attributeName, index); } protected: bool updateUniformLocation(GLint location, const GLvoid* data, unsigned int bytes); virtual std::string getDescription() const; void bindPredefinedVertexAttribs(); void parseVertexAttribs(); void parseUniforms(); bool compileShader(GLuint * shader, GLenum type, const GLchar* source); std::string logForOpenGLObject(GLuint object, GLInfoFunction infoFunc, GLLogFunction logFunc) const; GLuint _program; GLuint _vertShader; GLuint _fragShader; GLint _builtInUniforms[UNIFORM_MAX]; struct _hashUniformEntry* _hashForUniforms; bool _hasShaderCompiler; #if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) std::string _shaderId; #endif struct flag_struct { unsigned int usesTime:1; unsigned int usesMVP:1; unsigned int usesMV:1; unsigned int usesP:1; unsigned int usesRandom:1; // handy way to initialize the bitfield flag_struct() { memset(this, 0, sizeof(*this)); } } _flags; std::unordered_map<std::string, Uniform> _userUniforms; std::unordered_map<std::string, VertexAttrib> _vertexAttribs; }; NS_CC_END #endif /* __CCGLPROGRAM_H__ */
SubwayRocketTeam/Prototype
cocos2d/cocos/renderer/CCGLProgram.h
C
gpl-2.0
14,252
package com.tachys.moneyshare.dataaccess.db.contracts; import android.provider.BaseColumns; public class SettlementContract { public SettlementContract() { } public static class SettlementEntry implements BaseColumns { public static final String TABLE_NAME = "settlement"; public static final String COLUMN_NAME_PAYERID = "payer"; public static final String COLUMN_NAME_PAYEEID = "payee"; public static final String COLUMN_NAME_AMOUNT = "amount"; } }
StrawHatPirates/MoneyShare
src/app/src/main/java/com/tachys/moneyshare/dataaccess/db/contracts/SettlementContract.java
Java
gpl-2.0
502
<?php namespace UmnLib\Core\XmlRecord; class NlmCatalog extends Record { // Must be an id type that uniquely identifies the record, // usually the record-creating organization's id. public static function primaryIdType() { return 'nlm'; } // Must return array( 'type' => $type, 'value' => $value ) pairs. public function ids() { if (!isset($this->ids)) { // output $ids = array(); $array = $this->asArray(); // TODO: Not sure this array key lookup will work with Titon... $nlmUniqueId = $array['NlmUniqueID']; $ids[] = array('type' => 'nlm', 'value' => $nlmUniqueId); if (array_key_exists('OtherID', $array)) { $otherIds = $array['OtherID']; if (!array_key_exists(0, $otherIds)) { $otherIds = array($otherIds); } foreach ($otherIds as $otherId) { if ('OCLC' == $otherId['attributes']['Source']) { $oclcId = trim($otherId['value']); // For some goofy reason, some of the OCLC ids are prefixed with 'ocm': $oclcId = preg_replace('/^ocm/', '', $oclcId); $ids[] = array('type' => 'oclc', 'value' => $oclcId); } } } $this->ids = $ids; } return $this->ids; } }
UMNLibraries/xml-record-php
src/NlmCatalog.php
PHP
gpl-2.0
1,268
my_inf = float('Inf') print 99999999 > my_inf # False my_neg_inf = float('-Inf') print my_neg_inf < -99999999 # True
jabbalaci/PrimCom
data/python/infinity.py
Python
gpl-2.0
118
cmd_kernel/irq/handle.o := arm-linux-gnueabi-gcc -Wp,-MD,kernel/irq/.handle.o.d -nostdinc -isystem /usr/lib/gcc-cross/arm-linux-gnueabi/4.7/include -Iinclude -I/home/benoit/kernel_android/32/es209ra/arch/arm/include -include include/linux/autoconf.h -D__KERNEL__ -mlittle-endian -Iarch/arm/mach-msm/include -Wall -Wundef -Wstrict-prototypes -Wno-trigraphs -Os -marm -mabi=aapcs-linux -mno-thumb-interwork -funwind-tables -D__LINUX_ARM_ARCH__=7 -march=armv7-a -msoft-float -Uarm -Wframe-larger-than=2048 -fno-stack-protector -fomit-frame-pointer -g -Wdeclaration-after-statement -Wno-pointer-sign -fno-strict-overflow -fno-dwarf2-cfi-asm -fconserve-stack -D"KBUILD_STR(s)=\#s" -D"KBUILD_BASENAME=KBUILD_STR(handle)" -D"KBUILD_MODNAME=KBUILD_STR(handle)" -c -o kernel/irq/handle.o kernel/irq/handle.c deps_kernel/irq/handle.o := \ kernel/irq/handle.c \ $(wildcard include/config/smp.h) \ $(wildcard include/config/generic/hardirqs.h) \ $(wildcard include/config/sparse/irq.h) \ $(wildcard include/config/generic/hardirqs/no//do/irq.h) \ $(wildcard include/config/enable/warn/deprecated.h) \ include/linux/irq.h \ $(wildcard include/config/s390.h) \ $(wildcard include/config/irq/per/cpu.h) \ $(wildcard include/config/irq/release/method.h) \ $(wildcard include/config/intr/remap.h) \ $(wildcard include/config/generic/pending/irq.h) \ $(wildcard include/config/proc/fs.h) \ $(wildcard include/config/numa/irq/desc.h) \ $(wildcard include/config/cpumask/offstack.h) \ $(wildcard include/config/cpumasks/offstack.h) \ include/linux/smp.h \ $(wildcard include/config/use/generic/smp/helpers.h) \ $(wildcard include/config/debug/preempt.h) \ include/linux/errno.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/errno.h \ include/asm-generic/errno.h \ include/asm-generic/errno-base.h \ include/linux/types.h \ $(wildcard include/config/uid16.h) \ $(wildcard include/config/lbdaf.h) \ $(wildcard include/config/phys/addr/t/64bit.h) \ $(wildcard include/config/64bit.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/types.h \ include/asm-generic/int-ll64.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/bitsperlong.h \ include/asm-generic/bitsperlong.h \ include/linux/posix_types.h \ include/linux/stddef.h \ include/linux/compiler.h \ $(wildcard include/config/trace/branch/profiling.h) \ $(wildcard include/config/profile/all/branches.h) \ $(wildcard include/config/enable/must/check.h) \ include/linux/compiler-gcc.h \ $(wildcard include/config/arch/supports/optimized/inlining.h) \ $(wildcard include/config/optimize/inlining.h) \ include/linux/compiler-gcc4.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/posix_types.h \ include/linux/list.h \ $(wildcard include/config/debug/list.h) \ include/linux/poison.h \ include/linux/prefetch.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/processor.h \ $(wildcard include/config/mmu.h) \ $(wildcard include/config/cpu/32v6k.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/ptrace.h \ $(wildcard include/config/cpu/endian/be8.h) \ $(wildcard include/config/arm/thumb.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/hwcap.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/cache.h \ $(wildcard include/config/arm/l1/cache/shift.h) \ $(wildcard include/config/aeabi.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/system.h \ $(wildcard include/config/cpu/xsc3.h) \ $(wildcard include/config/cpu/fa526.h) \ $(wildcard include/config/arch/msm.h) \ $(wildcard include/config/cpu/sa1100.h) \ $(wildcard include/config/cpu/sa110.h) \ include/linux/linkage.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/linkage.h \ include/linux/irqflags.h \ $(wildcard include/config/trace/irqflags.h) \ $(wildcard include/config/irqsoff/tracer.h) \ $(wildcard include/config/preempt/tracer.h) \ $(wildcard include/config/trace/irqflags/support.h) \ $(wildcard include/config/x86.h) \ include/linux/typecheck.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/irqflags.h \ include/asm-generic/cmpxchg-local.h \ include/linux/cpumask.h \ $(wildcard include/config/hotplug/cpu.h) \ $(wildcard include/config/debug/per/cpu/maps.h) \ $(wildcard include/config/disable/obsolete/cpumask/functions.h) \ include/linux/kernel.h \ $(wildcard include/config/preempt/voluntary.h) \ $(wildcard include/config/debug/spinlock/sleep.h) \ $(wildcard include/config/prove/locking.h) \ $(wildcard include/config/printk.h) \ $(wildcard include/config/dynamic/debug.h) \ $(wildcard include/config/ring/buffer.h) \ $(wildcard include/config/tracing.h) \ $(wildcard include/config/numa.h) \ $(wildcard include/config/ftrace/mcount/record.h) \ /usr/lib/gcc-cross/arm-linux-gnueabi/4.7/include/stdarg.h \ include/linux/bitops.h \ $(wildcard include/config/generic/find/first/bit.h) \ $(wildcard include/config/generic/find/last/bit.h) \ $(wildcard include/config/generic/find/next/bit.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/bitops.h \ include/asm-generic/bitops/non-atomic.h \ include/asm-generic/bitops/fls64.h \ include/asm-generic/bitops/sched.h \ include/asm-generic/bitops/hweight.h \ include/asm-generic/bitops/lock.h \ include/linux/log2.h \ $(wildcard include/config/arch/has/ilog2/u32.h) \ $(wildcard include/config/arch/has/ilog2/u64.h) \ include/linux/ratelimit.h \ include/linux/param.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/param.h \ $(wildcard include/config/hz.h) \ include/linux/dynamic_debug.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/byteorder.h \ include/linux/byteorder/little_endian.h \ include/linux/swab.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/swab.h \ include/linux/byteorder/generic.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/bug.h \ $(wildcard include/config/bug.h) \ $(wildcard include/config/debug/bugverbose.h) \ include/asm-generic/bug.h \ $(wildcard include/config/generic/bug.h) \ $(wildcard include/config/generic/bug/relative/pointers.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/div64.h \ include/linux/threads.h \ $(wildcard include/config/nr/cpus.h) \ $(wildcard include/config/base/small.h) \ include/linux/bitmap.h \ include/linux/string.h \ $(wildcard include/config/binary/printf.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/string.h \ include/linux/cache.h \ $(wildcard include/config/arch/has/cache/line/size.h) \ include/linux/spinlock.h \ $(wildcard include/config/debug/spinlock.h) \ $(wildcard include/config/generic/lockbreak.h) \ $(wildcard include/config/preempt.h) \ $(wildcard include/config/debug/lock/alloc.h) \ include/linux/preempt.h \ $(wildcard include/config/preempt/notifiers.h) \ include/linux/thread_info.h \ $(wildcard include/config/compat.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/thread_info.h \ $(wildcard include/config/arm/thumbee.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/fpstate.h \ $(wildcard include/config/vfpv3.h) \ $(wildcard include/config/iwmmxt.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/domain.h \ $(wildcard include/config/verify/permission/fault.h) \ $(wildcard include/config/io/36.h) \ include/linux/stringify.h \ include/linux/bottom_half.h \ include/linux/spinlock_types.h \ include/linux/spinlock_types_up.h \ include/linux/lockdep.h \ $(wildcard include/config/lockdep.h) \ $(wildcard include/config/lock/stat.h) \ include/linux/spinlock_up.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/atomic.h \ include/asm-generic/atomic-long.h \ include/linux/spinlock_api_up.h \ include/linux/gfp.h \ $(wildcard include/config/kmemcheck.h) \ $(wildcard include/config/highmem.h) \ $(wildcard include/config/zone/dma.h) \ $(wildcard include/config/zone/dma32.h) \ $(wildcard include/config/debug/vm.h) \ include/linux/mmzone.h \ $(wildcard include/config/force/max/zoneorder.h) \ $(wildcard include/config/memory/hotplug.h) \ $(wildcard include/config/sparsemem.h) \ $(wildcard include/config/arch/populates/node/map.h) \ $(wildcard include/config/discontigmem.h) \ $(wildcard include/config/flat/node/mem/map.h) \ $(wildcard include/config/cgroup/mem/res/ctlr.h) \ $(wildcard include/config/have/memory/present.h) \ $(wildcard include/config/need/node/memmap/size.h) \ $(wildcard include/config/need/multiple/nodes.h) \ $(wildcard include/config/have/arch/early/pfn/to/nid.h) \ $(wildcard include/config/flatmem.h) \ $(wildcard include/config/sparsemem/extreme.h) \ $(wildcard include/config/nodes/span/other/nodes.h) \ $(wildcard include/config/holes/in/zone.h) \ $(wildcard include/config/arch/has/holes/memorymodel.h) \ include/linux/wait.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/current.h \ include/linux/numa.h \ $(wildcard include/config/nodes/shift.h) \ include/linux/init.h \ $(wildcard include/config/modules.h) \ $(wildcard include/config/hotplug.h) \ include/linux/seqlock.h \ include/linux/nodemask.h \ include/linux/pageblock-flags.h \ $(wildcard include/config/hugetlb/page.h) \ $(wildcard include/config/hugetlb/page/size/variable.h) \ include/linux/bounds.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/page.h \ $(wildcard include/config/cpu/copy/v3.h) \ $(wildcard include/config/cpu/copy/v4wt.h) \ $(wildcard include/config/cpu/copy/v4wb.h) \ $(wildcard include/config/cpu/copy/feroceon.h) \ $(wildcard include/config/cpu/copy/fa.h) \ $(wildcard include/config/cpu/xscale.h) \ $(wildcard include/config/cpu/copy/v6.h) \ $(wildcard include/config/memory/hotplug/sparse.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/glue.h \ $(wildcard include/config/cpu/arm610.h) \ $(wildcard include/config/cpu/arm710.h) \ $(wildcard include/config/cpu/abrt/lv4t.h) \ $(wildcard include/config/cpu/abrt/ev4.h) \ $(wildcard include/config/cpu/abrt/ev4t.h) \ $(wildcard include/config/cpu/abrt/ev5tj.h) \ $(wildcard include/config/cpu/abrt/ev5t.h) \ $(wildcard include/config/cpu/abrt/ev6.h) \ $(wildcard include/config/cpu/abrt/ev7.h) \ $(wildcard include/config/cpu/pabrt/legacy.h) \ $(wildcard include/config/cpu/pabrt/v6.h) \ $(wildcard include/config/cpu/pabrt/v7.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/memory.h \ $(wildcard include/config/page/offset.h) \ $(wildcard include/config/thumb2/kernel.h) \ $(wildcard include/config/dram/size.h) \ $(wildcard include/config/dram/base.h) \ include/linux/const.h \ arch/arm/mach-msm/include/mach/memory.h \ $(wildcard include/config/phys/offset.h) \ $(wildcard include/config/arch/msm7x30.h) \ $(wildcard include/config/vmsplit/3g.h) \ $(wildcard include/config/arch/msm/arm11.h) \ $(wildcard include/config/cache/l2x0.h) \ $(wildcard include/config/arch/msm/scorpion.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/sizes.h \ include/asm-generic/memory_model.h \ $(wildcard include/config/sparsemem/vmemmap.h) \ include/asm-generic/getorder.h \ include/linux/memory_hotplug.h \ $(wildcard include/config/have/arch/nodedata/extension.h) \ $(wildcard include/config/memory/hotremove.h) \ include/linux/notifier.h \ include/linux/mutex.h \ $(wildcard include/config/debug/mutexes.h) \ include/linux/rwsem.h \ $(wildcard include/config/rwsem/generic/spinlock.h) \ include/linux/rwsem-spinlock.h \ include/linux/srcu.h \ include/linux/topology.h \ $(wildcard include/config/sched/smt.h) \ $(wildcard include/config/sched/mc.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/topology.h \ include/asm-generic/topology.h \ include/linux/mmdebug.h \ $(wildcard include/config/debug/virtual.h) \ include/linux/irqreturn.h \ include/linux/irqnr.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/irq.h \ arch/arm/mach-msm/include/mach/irqs.h \ $(wildcard include/config/arch/qsd8x50.h) \ $(wildcard include/config/arch/msm8x60.h) \ arch/arm/mach-msm/include/mach/irqs-8x50.h \ arch/arm/mach-msm/include/mach/sirc.h \ $(wildcard include/config/msm/soc/rev/a.h) \ arch/arm/mach-msm/include/mach/msm_iomap.h \ arch/arm/mach-msm/include/mach/msm_iomap-8x50.h \ $(wildcard include/config/mach/es209ra.h) \ $(wildcard include/config/msm/debug/uart.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/irq_regs.h \ include/asm-generic/irq_regs.h \ include/linux/percpu.h \ $(wildcard include/config/have/legacy/per/cpu/area.h) \ $(wildcard include/config/need/per/cpu/embed/first/chunk.h) \ $(wildcard include/config/need/per/cpu/page/first/chunk.h) \ $(wildcard include/config/debug/kmemleak.h) \ $(wildcard include/config/have/setup/per/cpu/area.h) \ include/linux/slab.h \ $(wildcard include/config/slab/debug.h) \ $(wildcard include/config/debug/objects.h) \ $(wildcard include/config/slub.h) \ $(wildcard include/config/slob.h) \ $(wildcard include/config/debug/slab.h) \ include/linux/slob_def.h \ include/linux/pfn.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/percpu.h \ include/asm-generic/percpu.h \ include/linux/percpu-defs.h \ $(wildcard include/config/debug/force/weak/per/cpu.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/hw_irq.h \ include/linux/sched.h \ $(wildcard include/config/sched/debug.h) \ $(wildcard include/config/no/hz.h) \ $(wildcard include/config/detect/softlockup.h) \ $(wildcard include/config/detect/hung/task.h) \ $(wildcard include/config/core/dump/default/elf/headers.h) \ $(wildcard include/config/bsd/process/acct.h) \ $(wildcard include/config/taskstats.h) \ $(wildcard include/config/audit.h) \ $(wildcard include/config/inotify/user.h) \ $(wildcard include/config/epoll.h) \ $(wildcard include/config/posix/mqueue.h) \ $(wildcard include/config/keys.h) \ $(wildcard include/config/user/sched.h) \ $(wildcard include/config/sysfs.h) \ $(wildcard include/config/perf/events.h) \ $(wildcard include/config/schedstats.h) \ $(wildcard include/config/task/delay/acct.h) \ $(wildcard include/config/fair/group/sched.h) \ $(wildcard include/config/rt/group/sched.h) \ $(wildcard include/config/blk/dev/io/trace.h) \ $(wildcard include/config/tree/preempt/rcu.h) \ $(wildcard include/config/cc/stackprotector.h) \ $(wildcard include/config/sysvipc.h) \ $(wildcard include/config/auditsyscall.h) \ $(wildcard include/config/rt/mutexes.h) \ $(wildcard include/config/task/xacct.h) \ $(wildcard include/config/cpusets.h) \ $(wildcard include/config/cgroups.h) \ $(wildcard include/config/futex.h) \ $(wildcard include/config/fault/injection.h) \ $(wildcard include/config/latencytop.h) \ $(wildcard include/config/function/graph/tracer.h) \ $(wildcard include/config/have/unstable/sched/clock.h) \ $(wildcard include/config/stack/growsup.h) \ $(wildcard include/config/debug/stack/usage.h) \ $(wildcard include/config/group/sched.h) \ $(wildcard include/config/mm/owner.h) \ include/linux/capability.h \ $(wildcard include/config/security/file/capabilities.h) \ include/linux/timex.h \ include/linux/time.h \ $(wildcard include/config/arch/uses/gettimeoffset.h) \ include/linux/math64.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/timex.h \ arch/arm/mach-msm/include/mach/timex.h \ include/linux/jiffies.h \ include/linux/rbtree.h \ include/linux/mm_types.h \ $(wildcard include/config/split/ptlock/cpus.h) \ $(wildcard include/config/want/page/debug/flags.h) \ $(wildcard include/config/aio.h) \ $(wildcard include/config/mmu/notifier.h) \ include/linux/auxvec.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/auxvec.h \ include/linux/prio_tree.h \ include/linux/completion.h \ include/linux/page-debug-flags.h \ $(wildcard include/config/page/poisoning.h) \ $(wildcard include/config/page/debug/something/else.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/mmu.h \ $(wildcard include/config/cpu/has/asid.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/cputime.h \ include/asm-generic/cputime.h \ include/linux/sem.h \ include/linux/ipc.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/ipcbuf.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/sembuf.h \ include/linux/rcupdate.h \ $(wildcard include/config/tree/rcu.h) \ include/linux/rcutree.h \ include/linux/signal.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/signal.h \ include/asm-generic/signal-defs.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/sigcontext.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/siginfo.h \ include/asm-generic/siginfo.h \ include/linux/path.h \ include/linux/pid.h \ include/linux/proportions.h \ include/linux/percpu_counter.h \ include/linux/seccomp.h \ $(wildcard include/config/seccomp.h) \ include/linux/rculist.h \ include/linux/rtmutex.h \ $(wildcard include/config/debug/rt/mutexes.h) \ include/linux/plist.h \ $(wildcard include/config/debug/pi/list.h) \ include/linux/resource.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/resource.h \ include/asm-generic/resource.h \ include/linux/timer.h \ $(wildcard include/config/timer/stats.h) \ $(wildcard include/config/debug/objects/timers.h) \ include/linux/ktime.h \ $(wildcard include/config/ktime/scalar.h) \ include/linux/debugobjects.h \ $(wildcard include/config/debug/objects/free.h) \ include/linux/hrtimer.h \ $(wildcard include/config/high/res/timers.h) \ include/linux/task_io_accounting.h \ $(wildcard include/config/task/io/accounting.h) \ include/linux/kobject.h \ include/linux/sysfs.h \ include/linux/kref.h \ include/linux/latencytop.h \ include/linux/cred.h \ $(wildcard include/config/debug/credentials.h) \ $(wildcard include/config/security.h) \ include/linux/key.h \ $(wildcard include/config/sysctl.h) \ include/linux/sysctl.h \ include/linux/selinux.h \ $(wildcard include/config/security/selinux.h) \ include/linux/aio.h \ include/linux/workqueue.h \ include/linux/aio_abi.h \ include/linux/uio.h \ include/linux/module.h \ $(wildcard include/config/modversions.h) \ $(wildcard include/config/unused/symbols.h) \ $(wildcard include/config/kallsyms.h) \ $(wildcard include/config/tracepoints.h) \ $(wildcard include/config/event/tracing.h) \ $(wildcard include/config/module/unload.h) \ $(wildcard include/config/constructors.h) \ include/linux/stat.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/stat.h \ include/linux/kmod.h \ include/linux/elf.h \ include/linux/elf-em.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/elf.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/user.h \ include/linux/moduleparam.h \ $(wildcard include/config/alpha.h) \ $(wildcard include/config/ia64.h) \ $(wildcard include/config/ppc64.h) \ include/linux/tracepoint.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/local.h \ include/asm-generic/local.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/module.h \ $(wildcard include/config/arm/unwind.h) \ include/trace/events/module.h \ include/trace/define_trace.h \ include/linux/random.h \ include/linux/ioctl.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/ioctl.h \ include/asm-generic/ioctl.h \ include/linux/interrupt.h \ $(wildcard include/config/pm/sleep.h) \ $(wildcard include/config/generic/irq/probe.h) \ $(wildcard include/config/debug/shirq.h) \ include/linux/hardirq.h \ $(wildcard include/config/virt/cpu/accounting.h) \ include/linux/smp_lock.h \ $(wildcard include/config/lock/kernel.h) \ include/linux/ftrace_irq.h \ $(wildcard include/config/ftrace/nmi/enter.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/hardirq.h \ include/linux/irq_cpustat.h \ include/linux/kernel_stat.h \ include/linux/hash.h \ include/linux/bootmem.h \ $(wildcard include/config/crash/dump.h) \ $(wildcard include/config/have/arch/bootmem/node.h) \ $(wildcard include/config/have/arch/alloc/remap.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/dma.h \ $(wildcard include/config/isa/dma/api.h) \ $(wildcard include/config/pci.h) \ include/trace/events/irq.h \ kernel/irq/internals.h \ include/linux/kallsyms.h \ kernel/irq/handle.o: $(deps_kernel/irq/handle.o) $(deps_kernel/irq/handle.o):
b8e5n/KTG-kernel_es209ra
kernel/irq/.handle.o.cmd
Batchfile
gpl-2.0
21,499
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, [email protected] Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ #include "fix_rigid.h" #include <mpi.h> #include <cmath> #include <cstdlib> #include <cstring> #include "math_extra.h" #include "atom.h" #include "atom_vec_ellipsoid.h" #include "atom_vec_line.h" #include "atom_vec_tri.h" #include "domain.h" #include "update.h" #include "respa.h" #include "modify.h" #include "group.h" #include "comm.h" #include "random_mars.h" #include "force.h" #include "input.h" #include "variable.h" #include "math_const.h" #include "memory.h" #include "error.h" #include "rigid_const.h" using namespace LAMMPS_NS; using namespace FixConst; using namespace MathConst; using namespace RigidConst; /* ---------------------------------------------------------------------- */ FixRigid::FixRigid(LAMMPS *lmp, int narg, char **arg) : Fix(lmp, narg, arg), step_respa(NULL), inpfile(NULL), nrigid(NULL), mol2body(NULL), body2mol(NULL), body(NULL), displace(NULL), masstotal(NULL), xcm(NULL), vcm(NULL), fcm(NULL), inertia(NULL), ex_space(NULL), ey_space(NULL), ez_space(NULL), angmom(NULL), omega(NULL), torque(NULL), quat(NULL), imagebody(NULL), fflag(NULL), tflag(NULL), langextra(NULL), sum(NULL), all(NULL), remapflag(NULL), xcmimage(NULL), eflags(NULL), orient(NULL), dorient(NULL), id_dilate(NULL), id_gravity(NULL), random(NULL), avec_ellipsoid(NULL), avec_line(NULL), avec_tri(NULL) { int i,ibody; scalar_flag = 1; extscalar = 0; time_integrate = 1; rigid_flag = 1; virial_flag = 1; thermo_virial = 1; create_attribute = 1; dof_flag = 1; enforce2d_flag = 1; MPI_Comm_rank(world,&me); MPI_Comm_size(world,&nprocs); // perform initial allocation of atom-based arrays // register with Atom class extended = orientflag = dorientflag = 0; body = NULL; xcmimage = NULL; displace = NULL; eflags = NULL; orient = NULL; dorient = NULL; grow_arrays(atom->nmax); atom->add_callback(0); // parse args for rigid body specification // set nbody and body[i] for each atom if (narg < 4) error->all(FLERR,"Illegal fix rigid command"); int iarg; mol2body = NULL; body2mol = NULL; // single rigid body // nbody = 1 // all atoms in fix group are part of body if (strcmp(arg[3],"single") == 0) { rstyle = SINGLE; iarg = 4; nbody = 1; int *mask = atom->mask; int nlocal = atom->nlocal; for (i = 0; i < nlocal; i++) { body[i] = -1; if (mask[i] & groupbit) body[i] = 0; } // each molecule in fix group is a rigid body // maxmol = largest molecule ID // ncount = # of atoms in each molecule (have to sum across procs) // nbody = # of non-zero ncount values // use nall as incremented ptr to set body[] values for each atom } else if (strcmp(arg[3],"molecule") == 0 || strcmp(arg[3],"custom") == 0) { rstyle = MOLECULE; tagint *molecule; int *mask = atom->mask; int nlocal = atom->nlocal; int custom_flag = strcmp(arg[3],"custom") == 0; if (custom_flag) { if (narg < 5) error->all(FLERR,"Illegal fix rigid command"); // determine whether atom-style variable or atom property is used if (strstr(arg[4],"i_") == arg[4]) { int is_double=0; int custom_index = atom->find_custom(arg[4]+2,is_double); if (custom_index == -1) error->all(FLERR,"Fix rigid custom requires " "previously defined property/atom"); else if (is_double) error->all(FLERR,"Fix rigid custom requires " "integer-valued property/atom"); int minval = INT_MAX; int *value = atom->ivector[custom_index]; for (i = 0; i < nlocal; i++) if (mask[i] & groupbit) minval = MIN(minval,value[i]); int vmin = minval; MPI_Allreduce(&vmin,&minval,1,MPI_INT,MPI_MIN,world); molecule = new tagint[nlocal]; for (i = 0; i < nlocal; i++) if (mask[i] & groupbit) molecule[i] = (tagint)(value[i] - minval + 1); else molecule[i] = 0; } else if (strstr(arg[4],"v_") == arg[4]) { int ivariable = input->variable->find(arg[4]+2); if (ivariable < 0) error->all(FLERR,"Variable name for fix rigid custom does not exist"); if (input->variable->atomstyle(ivariable) == 0) error->all(FLERR,"Fix rigid custom variable is no atom-style variable"); double *value = new double[nlocal]; input->variable->compute_atom(ivariable,0,value,1,0); int minval = INT_MAX; for (i = 0; i < nlocal; i++) if (mask[i] & groupbit) minval = MIN(minval,(int)value[i]); int vmin = minval; MPI_Allreduce(&vmin,&minval,1,MPI_INT,MPI_MIN,world); molecule = new tagint[nlocal]; for (i = 0; i < nlocal; i++) if (mask[i] & groupbit) molecule[i] = (tagint)((tagint)value[i] - minval + 1); delete[] value; } else error->all(FLERR,"Unsupported fix rigid custom property"); } else { if (atom->molecule_flag == 0) error->all(FLERR,"Fix rigid molecule requires atom attribute molecule"); molecule = atom->molecule; } iarg = 4 + custom_flag; tagint maxmol_tag = -1; for (i = 0; i < nlocal; i++) if (mask[i] & groupbit) maxmol_tag = MAX(maxmol_tag,molecule[i]); tagint itmp; MPI_Allreduce(&maxmol_tag,&itmp,1,MPI_LMP_TAGINT,MPI_MAX,world); if (itmp+1 > MAXSMALLINT) error->all(FLERR,"Too many molecules for fix rigid"); maxmol = (int) itmp; int *ncount; memory->create(ncount,maxmol+1,"rigid:ncount"); for (i = 0; i <= maxmol; i++) ncount[i] = 0; for (i = 0; i < nlocal; i++) if (mask[i] & groupbit) ncount[molecule[i]]++; memory->create(mol2body,maxmol+1,"rigid:mol2body"); MPI_Allreduce(ncount,mol2body,maxmol+1,MPI_INT,MPI_SUM,world); nbody = 0; for (i = 0; i <= maxmol; i++) if (mol2body[i]) mol2body[i] = nbody++; else mol2body[i] = -1; memory->create(body2mol,nbody,"rigid:body2mol"); nbody = 0; for (i = 0; i <= maxmol; i++) if (mol2body[i] >= 0) body2mol[nbody++] = i; for (i = 0; i < nlocal; i++) { body[i] = -1; if (mask[i] & groupbit) body[i] = mol2body[molecule[i]]; } memory->destroy(ncount); if (custom_flag) delete [] molecule; // each listed group is a rigid body // check if all listed groups exist // an atom must belong to fix group and listed group to be in rigid body // error if atom belongs to more than 1 rigid body } else if (strcmp(arg[3],"group") == 0) { if (narg < 5) error->all(FLERR,"Illegal fix rigid command"); rstyle = GROUP; nbody = force->inumeric(FLERR,arg[4]); if (nbody <= 0) error->all(FLERR,"Illegal fix rigid command"); if (narg < 5+nbody) error->all(FLERR,"Illegal fix rigid command"); iarg = 5+nbody; int *igroups = new int[nbody]; for (ibody = 0; ibody < nbody; ibody++) { igroups[ibody] = group->find(arg[5+ibody]); if (igroups[ibody] == -1) error->all(FLERR,"Could not find fix rigid group ID"); } int *mask = atom->mask; int nlocal = atom->nlocal; int flag = 0; for (i = 0; i < nlocal; i++) { body[i] = -1; if (mask[i] & groupbit) for (ibody = 0; ibody < nbody; ibody++) if (mask[i] & group->bitmask[igroups[ibody]]) { if (body[i] >= 0) flag = 1; body[i] = ibody; } } int flagall; MPI_Allreduce(&flag,&flagall,1,MPI_INT,MPI_SUM,world); if (flagall) error->all(FLERR,"One or more atoms belong to multiple rigid bodies"); delete [] igroups; } else error->all(FLERR,"Illegal fix rigid command"); // error check on nbody if (nbody == 0) error->all(FLERR,"No rigid bodies defined"); // create all nbody-length arrays memory->create(nrigid,nbody,"rigid:nrigid"); memory->create(masstotal,nbody,"rigid:masstotal"); memory->create(xcm,nbody,3,"rigid:xcm"); memory->create(vcm,nbody,3,"rigid:vcm"); memory->create(fcm,nbody,3,"rigid:fcm"); memory->create(inertia,nbody,3,"rigid:inertia"); memory->create(ex_space,nbody,3,"rigid:ex_space"); memory->create(ey_space,nbody,3,"rigid:ey_space"); memory->create(ez_space,nbody,3,"rigid:ez_space"); memory->create(angmom,nbody,3,"rigid:angmom"); memory->create(omega,nbody,3,"rigid:omega"); memory->create(torque,nbody,3,"rigid:torque"); memory->create(quat,nbody,4,"rigid:quat"); memory->create(imagebody,nbody,"rigid:imagebody"); memory->create(fflag,nbody,3,"rigid:fflag"); memory->create(tflag,nbody,3,"rigid:tflag"); memory->create(langextra,nbody,6,"rigid:langextra"); memory->create(sum,nbody,6,"rigid:sum"); memory->create(all,nbody,6,"rigid:all"); memory->create(remapflag,nbody,4,"rigid:remapflag"); // initialize force/torque flags to default = 1.0 // for 2d: fz, tx, ty = 0.0 array_flag = 1; size_array_rows = nbody; size_array_cols = 15; global_freq = 1; extarray = 0; for (i = 0; i < nbody; i++) { fflag[i][0] = fflag[i][1] = fflag[i][2] = 1.0; tflag[i][0] = tflag[i][1] = tflag[i][2] = 1.0; if (domain->dimension == 2) fflag[i][2] = tflag[i][0] = tflag[i][1] = 0.0; } // number of linear rigid bodies is counted later nlinear = 0; // parse optional args int seed; langflag = 0; reinitflag = 1; tstat_flag = 0; pstat_flag = 0; allremap = 1; t_chain = 10; t_iter = 1; t_order = 3; p_chain = 10; inpfile = NULL; id_gravity = NULL; id_dilate = NULL; pcouple = NONE; pstyle = ANISO; dimension = domain->dimension; for (int i = 0; i < 3; i++) { p_start[i] = p_stop[i] = p_period[i] = 0.0; p_flag[i] = 0; } while (iarg < narg) { if (strcmp(arg[iarg],"force") == 0) { if (iarg+5 > narg) error->all(FLERR,"Illegal fix rigid command"); int mlo,mhi; force->bounds(FLERR,arg[iarg+1],nbody,mlo,mhi); double xflag,yflag,zflag; if (strcmp(arg[iarg+2],"off") == 0) xflag = 0.0; else if (strcmp(arg[iarg+2],"on") == 0) xflag = 1.0; else error->all(FLERR,"Illegal fix rigid command"); if (strcmp(arg[iarg+3],"off") == 0) yflag = 0.0; else if (strcmp(arg[iarg+3],"on") == 0) yflag = 1.0; else error->all(FLERR,"Illegal fix rigid command"); if (strcmp(arg[iarg+4],"off") == 0) zflag = 0.0; else if (strcmp(arg[iarg+4],"on") == 0) zflag = 1.0; else error->all(FLERR,"Illegal fix rigid command"); if (domain->dimension == 2 && zflag == 1.0) error->all(FLERR,"Fix rigid z force cannot be on for 2d simulation"); int count = 0; for (int m = mlo; m <= mhi; m++) { fflag[m-1][0] = xflag; fflag[m-1][1] = yflag; fflag[m-1][2] = zflag; count++; } if (count == 0) error->all(FLERR,"Illegal fix rigid command"); iarg += 5; } else if (strcmp(arg[iarg],"torque") == 0) { if (iarg+5 > narg) error->all(FLERR,"Illegal fix rigid command"); int mlo,mhi; force->bounds(FLERR,arg[iarg+1],nbody,mlo,mhi); double xflag,yflag,zflag; if (strcmp(arg[iarg+2],"off") == 0) xflag = 0.0; else if (strcmp(arg[iarg+2],"on") == 0) xflag = 1.0; else error->all(FLERR,"Illegal fix rigid command"); if (strcmp(arg[iarg+3],"off") == 0) yflag = 0.0; else if (strcmp(arg[iarg+3],"on") == 0) yflag = 1.0; else error->all(FLERR,"Illegal fix rigid command"); if (strcmp(arg[iarg+4],"off") == 0) zflag = 0.0; else if (strcmp(arg[iarg+4],"on") == 0) zflag = 1.0; else error->all(FLERR,"Illegal fix rigid command"); if (domain->dimension == 2 && (xflag == 1.0 || yflag == 1.0)) error->all(FLERR,"Fix rigid xy torque cannot be on for 2d simulation"); int count = 0; for (int m = mlo; m <= mhi; m++) { tflag[m-1][0] = xflag; tflag[m-1][1] = yflag; tflag[m-1][2] = zflag; count++; } if (count == 0) error->all(FLERR,"Illegal fix rigid command"); iarg += 5; } else if (strcmp(arg[iarg],"langevin") == 0) { if (iarg+5 > narg) error->all(FLERR,"Illegal fix rigid command"); if (strcmp(style,"rigid") != 0 && strcmp(style,"rigid/nve") != 0 && strcmp(style,"rigid/omp") != 0 && strcmp(style,"rigid/nve/omp") != 0) error->all(FLERR,"Illegal fix rigid command"); langflag = 1; t_start = force->numeric(FLERR,arg[iarg+1]); t_stop = force->numeric(FLERR,arg[iarg+2]); t_period = force->numeric(FLERR,arg[iarg+3]); seed = force->inumeric(FLERR,arg[iarg+4]); if (t_period <= 0.0) error->all(FLERR,"Fix rigid langevin period must be > 0.0"); if (seed <= 0) error->all(FLERR,"Illegal fix rigid command"); iarg += 5; } else if (strcmp(arg[iarg],"temp") == 0) { if (iarg+4 > narg) error->all(FLERR,"Illegal fix rigid command"); if (strcmp(style,"rigid/nvt") != 0 && strcmp(style,"rigid/npt") != 0 && strcmp(style,"rigid/nvt/omp") != 0 && strcmp(style,"rigid/npt/omp") != 0) error->all(FLERR,"Illegal fix rigid command"); tstat_flag = 1; t_start = force->numeric(FLERR,arg[iarg+1]); t_stop = force->numeric(FLERR,arg[iarg+2]); t_period = force->numeric(FLERR,arg[iarg+3]); iarg += 4; } else if (strcmp(arg[iarg],"iso") == 0) { if (iarg+4 > narg) error->all(FLERR,"Illegal fix rigid command"); if (strcmp(style,"rigid/npt") != 0 && strcmp(style,"rigid/nph") != 0 && strcmp(style,"rigid/npt/omp") != 0 && strcmp(style,"rigid/nph/omp") != 0) error->all(FLERR,"Illegal fix rigid command"); pcouple = XYZ; p_start[0] = p_start[1] = p_start[2] = force->numeric(FLERR,arg[iarg+1]); p_stop[0] = p_stop[1] = p_stop[2] = force->numeric(FLERR,arg[iarg+2]); p_period[0] = p_period[1] = p_period[2] = force->numeric(FLERR,arg[iarg+3]); p_flag[0] = p_flag[1] = p_flag[2] = 1; if (dimension == 2) { p_start[2] = p_stop[2] = p_period[2] = 0.0; p_flag[2] = 0; } iarg += 4; } else if (strcmp(arg[iarg],"aniso") == 0) { if (iarg+4 > narg) error->all(FLERR,"Illegal fix rigid command"); if (strcmp(style,"rigid/npt") != 0 && strcmp(style,"rigid/nph") != 0 && strcmp(style,"rigid/npt/omp") != 0 && strcmp(style,"rigid/nph/omp") != 0) error->all(FLERR,"Illegal fix rigid command"); p_start[0] = p_start[1] = p_start[2] = force->numeric(FLERR,arg[iarg+1]); p_stop[0] = p_stop[1] = p_stop[2] = force->numeric(FLERR,arg[iarg+2]); p_period[0] = p_period[1] = p_period[2] = force->numeric(FLERR,arg[iarg+3]); p_flag[0] = p_flag[1] = p_flag[2] = 1; if (dimension == 2) { p_start[2] = p_stop[2] = p_period[2] = 0.0; p_flag[2] = 0; } iarg += 4; } else if (strcmp(arg[iarg],"x") == 0) { if (iarg+4 > narg) error->all(FLERR,"Illegal fix rigid command"); if (strcmp(style,"rigid/npt") != 0 && strcmp(style,"rigid/nph") != 0 && strcmp(style,"rigid/npt/omp") != 0 && strcmp(style,"rigid/nph/omp") != 0) error->all(FLERR,"Illegal fix rigid command"); p_start[0] = force->numeric(FLERR,arg[iarg+1]); p_stop[0] = force->numeric(FLERR,arg[iarg+2]); p_period[0] = force->numeric(FLERR,arg[iarg+3]); p_flag[0] = 1; iarg += 4; } else if (strcmp(arg[iarg],"y") == 0) { if (iarg+4 > narg) error->all(FLERR,"Illegal fix rigid command"); if (strcmp(style,"rigid/npt") != 0 && strcmp(style,"rigid/nph") != 0 && strcmp(style,"rigid/npt/omp") != 0 && strcmp(style,"rigid/nph/omp") != 0) error->all(FLERR,"Illegal fix rigid command"); p_start[1] = force->numeric(FLERR,arg[iarg+1]); p_stop[1] = force->numeric(FLERR,arg[iarg+2]); p_period[1] = force->numeric(FLERR,arg[iarg+3]); p_flag[1] = 1; iarg += 4; } else if (strcmp(arg[iarg],"z") == 0) { if (iarg+4 > narg) error->all(FLERR,"Illegal fix rigid command"); if (strcmp(style,"rigid/npt") != 0 && strcmp(style,"rigid/nph") != 0 && strcmp(style,"rigid/npt/omp") != 0 && strcmp(style,"rigid/nph/omp") != 0) error->all(FLERR,"Illegal fix rigid command"); p_start[2] = force->numeric(FLERR,arg[iarg+1]); p_stop[2] = force->numeric(FLERR,arg[iarg+2]); p_period[2] = force->numeric(FLERR,arg[iarg+3]); p_flag[2] = 1; iarg += 4; } else if (strcmp(arg[iarg],"couple") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal fix rigid command"); if (strcmp(arg[iarg+1],"xyz") == 0) pcouple = XYZ; else if (strcmp(arg[iarg+1],"xy") == 0) pcouple = XY; else if (strcmp(arg[iarg+1],"yz") == 0) pcouple = YZ; else if (strcmp(arg[iarg+1],"xz") == 0) pcouple = XZ; else if (strcmp(arg[iarg+1],"none") == 0) pcouple = NONE; else error->all(FLERR,"Illegal fix rigid command"); iarg += 2; } else if (strcmp(arg[iarg],"dilate") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal fix rigid npt/nph command"); if (strcmp(arg[iarg+1],"all") == 0) allremap = 1; else { allremap = 0; delete [] id_dilate; int n = strlen(arg[iarg+1]) + 1; id_dilate = new char[n]; strcpy(id_dilate,arg[iarg+1]); int idilate = group->find(id_dilate); if (idilate == -1) error->all(FLERR, "Fix rigid npt/nph dilate group ID does not exist"); } iarg += 2; } else if (strcmp(arg[iarg],"tparam") == 0) { if (iarg+4 > narg) error->all(FLERR,"Illegal fix rigid command"); if (strcmp(style,"rigid/nvt") != 0 && strcmp(style,"rigid/npt") != 0 && strcmp(style,"rigid/nvt/omp") != 0 && strcmp(style,"rigid/npt/omp") != 0) error->all(FLERR,"Illegal fix rigid command"); t_chain = force->inumeric(FLERR,arg[iarg+1]); t_iter = force->inumeric(FLERR,arg[iarg+2]); t_order = force->inumeric(FLERR,arg[iarg+3]); iarg += 4; } else if (strcmp(arg[iarg],"pchain") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal fix rigid command"); if (strcmp(style,"rigid/npt") != 0 && strcmp(style,"rigid/nph") != 0 && strcmp(style,"rigid/npt/omp") != 0 && strcmp(style,"rigid/nph/omp") != 0) error->all(FLERR,"Illegal fix rigid command"); p_chain = force->inumeric(FLERR,arg[iarg+1]); iarg += 2; } else if (strcmp(arg[iarg],"infile") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal fix rigid command"); delete [] inpfile; int n = strlen(arg[iarg+1]) + 1; inpfile = new char[n]; strcpy(inpfile,arg[iarg+1]); restart_file = 1; reinitflag = 0; iarg += 2; } else if (strcmp(arg[iarg],"reinit") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal fix rigid command"); if (strcmp("yes",arg[iarg+1]) == 0) reinitflag = 1; else if (strcmp("no",arg[iarg+1]) == 0) reinitflag = 0; else error->all(FLERR,"Illegal fix rigid command"); iarg += 2; } else if (strcmp(arg[iarg],"gravity") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal fix rigid command"); delete [] id_gravity; int n = strlen(arg[iarg+1]) + 1; id_gravity = new char[n]; strcpy(id_gravity,arg[iarg+1]); iarg += 2; } else error->all(FLERR,"Illegal fix rigid command"); } // set pstat_flag pstat_flag = 0; for (int i = 0; i < 3; i++) if (p_flag[i]) pstat_flag = 1; if (pcouple == XYZ || (dimension == 2 && pcouple == XY)) pstyle = ISO; else pstyle = ANISO; // initialize Marsaglia RNG with processor-unique seed if (langflag) random = new RanMars(lmp,seed + me); else random = NULL; // initialize vector output quantities in case accessed before run for (i = 0; i < nbody; i++) { xcm[i][0] = xcm[i][1] = xcm[i][2] = 0.0; vcm[i][0] = vcm[i][1] = vcm[i][2] = 0.0; fcm[i][0] = fcm[i][1] = fcm[i][2] = 0.0; torque[i][0] = torque[i][1] = torque[i][2] = 0.0; } // nrigid[n] = # of atoms in Nth rigid body // error if one or zero atoms int *ncount = new int[nbody]; for (ibody = 0; ibody < nbody; ibody++) ncount[ibody] = 0; int nlocal = atom->nlocal; for (i = 0; i < nlocal; i++) if (body[i] >= 0) ncount[body[i]]++; MPI_Allreduce(ncount,nrigid,nbody,MPI_INT,MPI_SUM,world); delete [] ncount; for (ibody = 0; ibody < nbody; ibody++) if (nrigid[ibody] <= 1) error->all(FLERR,"One or zero atoms in rigid body"); // wait to setup bodies until first init() using current atom properties setupflag = 0; // compute per body forces and torques at final_integrate() by default earlyflag = 0; // print statistics int nsum = 0; for (ibody = 0; ibody < nbody; ibody++) nsum += nrigid[ibody]; if (me == 0) { if (screen) fprintf(screen,"%d rigid bodies with %d atoms\n",nbody,nsum); if (logfile) fprintf(logfile,"%d rigid bodies with %d atoms\n",nbody,nsum); } } /* ---------------------------------------------------------------------- */ FixRigid::~FixRigid() { // unregister callbacks to this fix from Atom class atom->delete_callback(id,0); delete random; delete [] inpfile; delete [] id_dilate; delete [] id_gravity; memory->destroy(mol2body); memory->destroy(body2mol); // delete locally stored per-atom arrays memory->destroy(body); memory->destroy(xcmimage); memory->destroy(displace); memory->destroy(eflags); memory->destroy(orient); memory->destroy(dorient); // delete nbody-length arrays memory->destroy(nrigid); memory->destroy(masstotal); memory->destroy(xcm); memory->destroy(vcm); memory->destroy(fcm); memory->destroy(inertia); memory->destroy(ex_space); memory->destroy(ey_space); memory->destroy(ez_space); memory->destroy(angmom); memory->destroy(omega); memory->destroy(torque); memory->destroy(quat); memory->destroy(imagebody); memory->destroy(fflag); memory->destroy(tflag); memory->destroy(langextra); memory->destroy(sum); memory->destroy(all); memory->destroy(remapflag); } /* ---------------------------------------------------------------------- */ int FixRigid::setmask() { int mask = 0; mask |= INITIAL_INTEGRATE; mask |= FINAL_INTEGRATE; if (langflag) mask |= POST_FORCE; mask |= PRE_NEIGHBOR; mask |= INITIAL_INTEGRATE_RESPA; mask |= FINAL_INTEGRATE_RESPA; return mask; } /* ---------------------------------------------------------------------- */ void FixRigid::init() { int i,ibody; triclinic = domain->triclinic; // atom style pointers to particles that store extra info avec_ellipsoid = (AtomVecEllipsoid *) atom->style_match("ellipsoid"); avec_line = (AtomVecLine *) atom->style_match("line"); avec_tri = (AtomVecTri *) atom->style_match("tri"); // warn if more than one rigid fix // if earlyflag, warn if any post-force fixes come after a rigid fix int count = 0; for (i = 0; i < modify->nfix; i++) if (modify->fix[i]->rigid_flag) count++; if (count > 1 && me == 0) error->warning(FLERR,"More than one fix rigid"); if (earlyflag) { int rflag = 0; for (i = 0; i < modify->nfix; i++) { if (modify->fix[i]->rigid_flag) rflag = 1; if (rflag && (modify->fmask[i] & POST_FORCE) && !modify->fix[i]->rigid_flag) { char str[128]; snprintf(str,128,"Fix %s alters forces after fix rigid", modify->fix[i]->id); error->warning(FLERR,str); } } } // warn if body properties are read from inpfile // and the gravity keyword is not set and a gravity fix exists // this could mean body particles are overlapped // and gravity is not applied correctly if (inpfile && !id_gravity) { for (i = 0; i < modify->nfix; i++) { if (strcmp(modify->fix[i]->style,"gravity") == 0) { if (comm->me == 0) error->warning(FLERR,"Gravity may not be correctly applied " "to rigid bodies if they consist of " "overlapped particles"); break; } } } // error if npt,nph fix comes before rigid fix for (i = 0; i < modify->nfix; i++) { if (strcmp(modify->fix[i]->style,"npt") == 0) break; if (strcmp(modify->fix[i]->style,"nph") == 0) break; } if (i < modify->nfix) { for (int j = i; j < modify->nfix; j++) if (strcmp(modify->fix[j]->style,"rigid") == 0) error->all(FLERR,"Rigid fix must come before NPT/NPH fix"); } // add gravity forces based on gravity vector from fix if (id_gravity) { int ifix = modify->find_fix(id_gravity); if (ifix < 0) error->all(FLERR,"Fix rigid cannot find fix gravity ID"); if (strcmp(modify->fix[ifix]->style,"gravity") != 0) error->all(FLERR,"Fix rigid gravity fix is invalid"); int tmp; gvec = (double *) modify->fix[ifix]->extract("gvec",tmp); } // timestep info dtv = update->dt; dtf = 0.5 * update->dt * force->ftm2v; dtq = 0.5 * update->dt; if (strstr(update->integrate_style,"respa")) step_respa = ((Respa *) update->integrate)->step; // setup rigid bodies, using current atom info. if reinitflag is not set, // do the initialization only once, b/c properties may not be re-computable // especially if overlapping particles. // do not do dynamic init if read body properties from inpfile. // this is b/c the inpfile defines the static and dynamic properties and may // not be computable if contain overlapping particles. // setup_bodies_static() reads inpfile itself if (reinitflag || !setupflag) { setup_bodies_static(); if (!inpfile) setup_bodies_dynamic(); setupflag = 1; } // temperature scale factor double ndof = 0.0; for (ibody = 0; ibody < nbody; ibody++) { ndof += fflag[ibody][0] + fflag[ibody][1] + fflag[ibody][2]; ndof += tflag[ibody][0] + tflag[ibody][1] + tflag[ibody][2]; } ndof -= nlinear; if (ndof > 0.0) tfactor = force->mvv2e / (ndof * force->boltz); else tfactor = 0.0; } /* ---------------------------------------------------------------------- invoke pre_neighbor() to insure body xcmimage flags are reset needed if Verlet::setup::pbc() has remapped/migrated atoms for 2nd run ------------------------------------------------------------------------- */ void FixRigid::setup_pre_neighbor() { pre_neighbor(); } /* ---------------------------------------------------------------------- compute initial fcm and torque on bodies, also initial virial reset all particle velocities to be consistent with vcm and omega ------------------------------------------------------------------------- */ void FixRigid::setup(int vflag) { int i,n,ibody; // fcm = force on center-of-mass of each rigid body double **f = atom->f; int nlocal = atom->nlocal; for (ibody = 0; ibody < nbody; ibody++) for (i = 0; i < 6; i++) sum[ibody][i] = 0.0; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; sum[ibody][0] += f[i][0]; sum[ibody][1] += f[i][1]; sum[ibody][2] += f[i][2]; } MPI_Allreduce(sum[0],all[0],6*nbody,MPI_DOUBLE,MPI_SUM,world); for (ibody = 0; ibody < nbody; ibody++) { fcm[ibody][0] = all[ibody][0]; fcm[ibody][1] = all[ibody][1]; fcm[ibody][2] = all[ibody][2]; } // torque = torque on each rigid body double **x = atom->x; double dx,dy,dz; double unwrap[3]; for (ibody = 0; ibody < nbody; ibody++) for (i = 0; i < 6; i++) sum[ibody][i] = 0.0; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; domain->unmap(x[i],xcmimage[i],unwrap); dx = unwrap[0] - xcm[ibody][0]; dy = unwrap[1] - xcm[ibody][1]; dz = unwrap[2] - xcm[ibody][2]; sum[ibody][0] += dy * f[i][2] - dz * f[i][1]; sum[ibody][1] += dz * f[i][0] - dx * f[i][2]; sum[ibody][2] += dx * f[i][1] - dy * f[i][0]; } // extended particles add their torque to torque of body if (extended) { double **torque_one = atom->torque; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; if (eflags[i] & TORQUE) { sum[ibody][0] += torque_one[i][0]; sum[ibody][1] += torque_one[i][1]; sum[ibody][2] += torque_one[i][2]; } } } MPI_Allreduce(sum[0],all[0],6*nbody,MPI_DOUBLE,MPI_SUM,world); for (ibody = 0; ibody < nbody; ibody++) { torque[ibody][0] = all[ibody][0]; torque[ibody][1] = all[ibody][1]; torque[ibody][2] = all[ibody][2]; } // zero langextra in case Langevin thermostat not used // no point to calling post_force() here since langextra // is only added to fcm/torque in final_integrate() for (ibody = 0; ibody < nbody; ibody++) for (i = 0; i < 6; i++) langextra[ibody][i] = 0.0; // virial setup before call to set_v if (vflag) v_setup(vflag); else evflag = 0; // set velocities from angmom & omega for (ibody = 0; ibody < nbody; ibody++) MathExtra::angmom_to_omega(angmom[ibody],ex_space[ibody],ey_space[ibody], ez_space[ibody],inertia[ibody],omega[ibody]); set_v(); // guesstimate virial as 2x the set_v contribution if (vflag_global) for (n = 0; n < 6; n++) virial[n] *= 2.0; if (vflag_atom) { for (i = 0; i < nlocal; i++) for (n = 0; n < 6; n++) vatom[i][n] *= 2.0; } } /* ---------------------------------------------------------------------- */ void FixRigid::initial_integrate(int vflag) { double dtfm; for (int ibody = 0; ibody < nbody; ibody++) { // update vcm by 1/2 step dtfm = dtf / masstotal[ibody]; vcm[ibody][0] += dtfm * fcm[ibody][0] * fflag[ibody][0]; vcm[ibody][1] += dtfm * fcm[ibody][1] * fflag[ibody][1]; vcm[ibody][2] += dtfm * fcm[ibody][2] * fflag[ibody][2]; // update xcm by full step xcm[ibody][0] += dtv * vcm[ibody][0]; xcm[ibody][1] += dtv * vcm[ibody][1]; xcm[ibody][2] += dtv * vcm[ibody][2]; // update angular momentum by 1/2 step angmom[ibody][0] += dtf * torque[ibody][0] * tflag[ibody][0]; angmom[ibody][1] += dtf * torque[ibody][1] * tflag[ibody][1]; angmom[ibody][2] += dtf * torque[ibody][2] * tflag[ibody][2]; // compute omega at 1/2 step from angmom at 1/2 step and current q // update quaternion a full step via Richardson iteration // returns new normalized quaternion, also updated omega at 1/2 step // update ex,ey,ez to reflect new quaternion MathExtra::angmom_to_omega(angmom[ibody],ex_space[ibody],ey_space[ibody], ez_space[ibody],inertia[ibody],omega[ibody]); MathExtra::richardson(quat[ibody],angmom[ibody],omega[ibody], inertia[ibody],dtq); MathExtra::q_to_exyz(quat[ibody], ex_space[ibody],ey_space[ibody],ez_space[ibody]); } // virial setup before call to set_xv if (vflag) v_setup(vflag); else evflag = 0; // set coords/orient and velocity/rotation of atoms in rigid bodies // from quarternion and omega set_xv(); } /* ---------------------------------------------------------------------- apply Langevin thermostat to all 6 DOF of rigid bodies computed by proc 0, broadcast to other procs unlike fix langevin, this stores extra force in extra arrays, which are added in when final_integrate() calculates a new fcm/torque ------------------------------------------------------------------------- */ void FixRigid::apply_langevin_thermostat() { if (me == 0) { double gamma1,gamma2; double delta = update->ntimestep - update->beginstep; if (delta != 0.0) delta /= update->endstep - update->beginstep; t_target = t_start + delta * (t_stop-t_start); double tsqrt = sqrt(t_target); double boltz = force->boltz; double dt = update->dt; double mvv2e = force->mvv2e; double ftm2v = force->ftm2v; for (int i = 0; i < nbody; i++) { gamma1 = -masstotal[i] / t_period / ftm2v; gamma2 = sqrt(masstotal[i]) * tsqrt * sqrt(24.0*boltz/t_period/dt/mvv2e) / ftm2v; langextra[i][0] = gamma1*vcm[i][0] + gamma2*(random->uniform()-0.5); langextra[i][1] = gamma1*vcm[i][1] + gamma2*(random->uniform()-0.5); langextra[i][2] = gamma1*vcm[i][2] + gamma2*(random->uniform()-0.5); gamma1 = -1.0 / t_period / ftm2v; gamma2 = tsqrt * sqrt(24.0*boltz/t_period/dt/mvv2e) / ftm2v; langextra[i][3] = inertia[i][0]*gamma1*omega[i][0] + sqrt(inertia[i][0])*gamma2*(random->uniform()-0.5); langextra[i][4] = inertia[i][1]*gamma1*omega[i][1] + sqrt(inertia[i][1])*gamma2*(random->uniform()-0.5); langextra[i][5] = inertia[i][2]*gamma1*omega[i][2] + sqrt(inertia[i][2])*gamma2*(random->uniform()-0.5); } } MPI_Bcast(&langextra[0][0],6*nbody,MPI_DOUBLE,0,world); } /* ---------------------------------------------------------------------- called from FixEnforce2d post_force() for 2d problems zero all body values that should be zero for 2d model ------------------------------------------------------------------------- */ void FixRigid::enforce2d() { for (int ibody = 0; ibody < nbody; ibody++) { xcm[ibody][2] = 0.0; vcm[ibody][2] = 0.0; fcm[ibody][2] = 0.0; torque[ibody][0] = 0.0; torque[ibody][1] = 0.0; angmom[ibody][0] = 0.0; angmom[ibody][1] = 0.0; omega[ibody][0] = 0.0; omega[ibody][1] = 0.0; if (langflag && langextra) { langextra[ibody][2] = 0.0; langextra[ibody][3] = 0.0; langextra[ibody][4] = 0.0; } } } /* ---------------------------------------------------------------------- */ void FixRigid::compute_forces_and_torques() { int i,ibody; // sum over atoms to get force and torque on rigid body double **x = atom->x; double **f = atom->f; int nlocal = atom->nlocal; double dx,dy,dz; double unwrap[3]; for (ibody = 0; ibody < nbody; ibody++) for (i = 0; i < 6; i++) sum[ibody][i] = 0.0; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; sum[ibody][0] += f[i][0]; sum[ibody][1] += f[i][1]; sum[ibody][2] += f[i][2]; domain->unmap(x[i],xcmimage[i],unwrap); dx = unwrap[0] - xcm[ibody][0]; dy = unwrap[1] - xcm[ibody][1]; dz = unwrap[2] - xcm[ibody][2]; sum[ibody][3] += dy*f[i][2] - dz*f[i][1]; sum[ibody][4] += dz*f[i][0] - dx*f[i][2]; sum[ibody][5] += dx*f[i][1] - dy*f[i][0]; } // extended particles add their torque to torque of body if (extended) { double **torque_one = atom->torque; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; if (eflags[i] & TORQUE) { sum[ibody][3] += torque_one[i][0]; sum[ibody][4] += torque_one[i][1]; sum[ibody][5] += torque_one[i][2]; } } } MPI_Allreduce(sum[0],all[0],6*nbody,MPI_DOUBLE,MPI_SUM,world); // include Langevin thermostat forces for (ibody = 0; ibody < nbody; ibody++) { fcm[ibody][0] = all[ibody][0] + langextra[ibody][0]; fcm[ibody][1] = all[ibody][1] + langextra[ibody][1]; fcm[ibody][2] = all[ibody][2] + langextra[ibody][2]; torque[ibody][0] = all[ibody][3] + langextra[ibody][3]; torque[ibody][1] = all[ibody][4] + langextra[ibody][4]; torque[ibody][2] = all[ibody][5] + langextra[ibody][5]; } // add gravity force to COM of each body if (id_gravity) { for (ibody = 0; ibody < nbody; ibody++) { fcm[ibody][0] += gvec[0]*masstotal[ibody]; fcm[ibody][1] += gvec[1]*masstotal[ibody]; fcm[ibody][2] += gvec[2]*masstotal[ibody]; } } } /* ---------------------------------------------------------------------- */ void FixRigid::post_force(int /*vflag*/) { if (langflag) apply_langevin_thermostat(); if (earlyflag) compute_forces_and_torques(); } /* ---------------------------------------------------------------------- */ void FixRigid::final_integrate() { int ibody; double dtfm; if (!earlyflag) compute_forces_and_torques(); // update vcm and angmom // fflag,tflag = 0 for some dimensions in 2d for (ibody = 0; ibody < nbody; ibody++) { // update vcm by 1/2 step dtfm = dtf / masstotal[ibody]; vcm[ibody][0] += dtfm * fcm[ibody][0] * fflag[ibody][0]; vcm[ibody][1] += dtfm * fcm[ibody][1] * fflag[ibody][1]; vcm[ibody][2] += dtfm * fcm[ibody][2] * fflag[ibody][2]; // update angular momentum by 1/2 step angmom[ibody][0] += dtf * torque[ibody][0] * tflag[ibody][0]; angmom[ibody][1] += dtf * torque[ibody][1] * tflag[ibody][1]; angmom[ibody][2] += dtf * torque[ibody][2] * tflag[ibody][2]; MathExtra::angmom_to_omega(angmom[ibody],ex_space[ibody],ey_space[ibody], ez_space[ibody],inertia[ibody],omega[ibody]); } // set velocity/rotation of atoms in rigid bodies // virial is already setup from initial_integrate set_v(); } /* ---------------------------------------------------------------------- */ void FixRigid::initial_integrate_respa(int vflag, int ilevel, int /*iloop*/) { dtv = step_respa[ilevel]; dtf = 0.5 * step_respa[ilevel] * force->ftm2v; dtq = 0.5 * step_respa[ilevel]; if (ilevel == 0) initial_integrate(vflag); else final_integrate(); } /* ---------------------------------------------------------------------- */ void FixRigid::final_integrate_respa(int ilevel, int /*iloop*/) { dtf = 0.5 * step_respa[ilevel] * force->ftm2v; final_integrate(); } /* ---------------------------------------------------------------------- remap xcm of each rigid body back into periodic simulation box done during pre_neighbor so will be after call to pbc() and after fix_deform::pre_exchange() may have flipped box use domain->remap() in case xcm is far away from box due to first-time definition of rigid body in setup_bodies_static() or due to box flip also adjust imagebody = rigid body image flags, due to xcm remap also reset body xcmimage flags of all atoms in bodies xcmimage flags are relative to xcm so that body can be unwrapped if don't do this, would need xcm to move with true image flags then a body could end up very far away from box set_xv() will then compute huge displacements every step to reset coords of all body atoms to be back inside the box, ditto for triclinic box flip, which causes numeric problems ------------------------------------------------------------------------- */ void FixRigid::pre_neighbor() { for (int ibody = 0; ibody < nbody; ibody++) domain->remap(xcm[ibody],imagebody[ibody]); image_shift(); } /* ---------------------------------------------------------------------- reset body xcmimage flags of atoms in bodies xcmimage flags are relative to xcm so that body can be unwrapped xcmimage = true image flag - imagebody flag ------------------------------------------------------------------------- */ void FixRigid::image_shift() { int ibody; imageint tdim,bdim,xdim[3]; imageint *image = atom->image; int nlocal = atom->nlocal; for (int i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; tdim = image[i] & IMGMASK; bdim = imagebody[ibody] & IMGMASK; xdim[0] = IMGMAX + tdim - bdim; tdim = (image[i] >> IMGBITS) & IMGMASK; bdim = (imagebody[ibody] >> IMGBITS) & IMGMASK; xdim[1] = IMGMAX + tdim - bdim; tdim = image[i] >> IMG2BITS; bdim = imagebody[ibody] >> IMG2BITS; xdim[2] = IMGMAX + tdim - bdim; xcmimage[i] = (xdim[2] << IMG2BITS) | (xdim[1] << IMGBITS) | xdim[0]; } } /* ---------------------------------------------------------------------- count # of DOF removed by rigid bodies for atoms in igroup return total count of DOF ------------------------------------------------------------------------- */ int FixRigid::dof(int tgroup) { // cannot count DOF correctly unless setup_bodies_static() has been called if (!setupflag) { if (comm->me == 0) error->warning(FLERR,"Cannot count rigid body degrees-of-freedom " "before bodies are initialized"); return 0; } int tgroupbit = group->bitmask[tgroup]; // nall = # of point particles in each rigid body // mall = # of finite-size particles in each rigid body // particles must also be in temperature group int *mask = atom->mask; int nlocal = atom->nlocal; int *ncount = new int[nbody]; int *mcount = new int[nbody]; for (int ibody = 0; ibody < nbody; ibody++) ncount[ibody] = mcount[ibody] = 0; for (int i = 0; i < nlocal; i++) if (body[i] >= 0 && mask[i] & tgroupbit) { // do not count point particles or point dipoles as extended particles // a spheroid dipole will be counted as extended if (extended && (eflags[i] & ~(POINT | DIPOLE))) mcount[body[i]]++; else ncount[body[i]]++; } int *nall = new int[nbody]; int *mall = new int[nbody]; MPI_Allreduce(ncount,nall,nbody,MPI_INT,MPI_SUM,world); MPI_Allreduce(mcount,mall,nbody,MPI_INT,MPI_SUM,world); // warn if nall+mall != nrigid for any body included in temperature group int flag = 0; for (int ibody = 0; ibody < nbody; ibody++) { if (nall[ibody]+mall[ibody] > 0 && nall[ibody]+mall[ibody] != nrigid[ibody]) flag = 1; } if (flag && me == 0) error->warning(FLERR,"Computing temperature of portions of rigid bodies"); // remove appropriate DOFs for each rigid body wholly in temperature group // N = # of point particles in body // M = # of finite-size particles in body // 3d body has 3N + 6M dof to start with // 2d body has 2N + 3M dof to start with // 3d point-particle body with all non-zero I should have 6 dof, remove 3N-6 // 3d point-particle body (linear) with a 0 I should have 5 dof, remove 3N-5 // 2d point-particle body should have 3 dof, remove 2N-3 // 3d body with any finite-size M should have 6 dof, remove (3N+6M) - 6 // 2d body with any finite-size M should have 3 dof, remove (2N+3M) - 3 int n = 0; nlinear = 0; if (domain->dimension == 3) { for (int ibody = 0; ibody < nbody; ibody++) if (nall[ibody]+mall[ibody] == nrigid[ibody]) { n += 3*nall[ibody] + 6*mall[ibody] - 6; if (inertia[ibody][0] == 0.0 || inertia[ibody][1] == 0.0 || inertia[ibody][2] == 0.0) { n++; nlinear++; } } } else if (domain->dimension == 2) { for (int ibody = 0; ibody < nbody; ibody++) if (nall[ibody]+mall[ibody] == nrigid[ibody]) n += 2*nall[ibody] + 3*mall[ibody] - 3; } delete [] ncount; delete [] mcount; delete [] nall; delete [] mall; return n; } /* ---------------------------------------------------------------------- adjust xcm of each rigid body due to box deformation called by various fixes that change box size/shape flag = 0/1 means map from box to lamda coords or vice versa ------------------------------------------------------------------------- */ void FixRigid::deform(int flag) { if (flag == 0) for (int ibody = 0; ibody < nbody; ibody++) domain->x2lamda(xcm[ibody],xcm[ibody]); else for (int ibody = 0; ibody < nbody; ibody++) domain->lamda2x(xcm[ibody],xcm[ibody]); } /* ---------------------------------------------------------------------- set space-frame coords and velocity of each atom in each rigid body set orientation and rotation of extended particles x = Q displace + Xcm, mapped back to periodic box v = Vcm + (W cross (x - Xcm)) ------------------------------------------------------------------------- */ void FixRigid::set_xv() { int ibody; int xbox,ybox,zbox; double x0,x1,x2,v0,v1,v2,fc0,fc1,fc2,massone; double xy,xz,yz; double ione[3],exone[3],eyone[3],ezone[3],vr[6],p[3][3]; double **x = atom->x; double **v = atom->v; double **f = atom->f; double *rmass = atom->rmass; double *mass = atom->mass; int *type = atom->type; int nlocal = atom->nlocal; double xprd = domain->xprd; double yprd = domain->yprd; double zprd = domain->zprd; if (triclinic) { xy = domain->xy; xz = domain->xz; yz = domain->yz; } // set x and v of each atom for (int i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; xbox = (xcmimage[i] & IMGMASK) - IMGMAX; ybox = (xcmimage[i] >> IMGBITS & IMGMASK) - IMGMAX; zbox = (xcmimage[i] >> IMG2BITS) - IMGMAX; // save old positions and velocities for virial if (evflag) { if (triclinic == 0) { x0 = x[i][0] + xbox*xprd; x1 = x[i][1] + ybox*yprd; x2 = x[i][2] + zbox*zprd; } else { x0 = x[i][0] + xbox*xprd + ybox*xy + zbox*xz; x1 = x[i][1] + ybox*yprd + zbox*yz; x2 = x[i][2] + zbox*zprd; } v0 = v[i][0]; v1 = v[i][1]; v2 = v[i][2]; } // x = displacement from center-of-mass, based on body orientation // v = vcm + omega around center-of-mass MathExtra::matvec(ex_space[ibody],ey_space[ibody], ez_space[ibody],displace[i],x[i]); v[i][0] = omega[ibody][1]*x[i][2] - omega[ibody][2]*x[i][1] + vcm[ibody][0]; v[i][1] = omega[ibody][2]*x[i][0] - omega[ibody][0]*x[i][2] + vcm[ibody][1]; v[i][2] = omega[ibody][0]*x[i][1] - omega[ibody][1]*x[i][0] + vcm[ibody][2]; // add center of mass to displacement // map back into periodic box via xbox,ybox,zbox // for triclinic, add in box tilt factors as well if (triclinic == 0) { x[i][0] += xcm[ibody][0] - xbox*xprd; x[i][1] += xcm[ibody][1] - ybox*yprd; x[i][2] += xcm[ibody][2] - zbox*zprd; } else { x[i][0] += xcm[ibody][0] - xbox*xprd - ybox*xy - zbox*xz; x[i][1] += xcm[ibody][1] - ybox*yprd - zbox*yz; x[i][2] += xcm[ibody][2] - zbox*zprd; } // virial = unwrapped coords dotted into body constraint force // body constraint force = implied force due to v change minus f external // assume f does not include forces internal to body // 1/2 factor b/c final_integrate contributes other half // assume per-atom contribution is due to constraint force on that atom if (evflag) { if (rmass) massone = rmass[i]; else massone = mass[type[i]]; fc0 = massone*(v[i][0] - v0)/dtf - f[i][0]; fc1 = massone*(v[i][1] - v1)/dtf - f[i][1]; fc2 = massone*(v[i][2] - v2)/dtf - f[i][2]; vr[0] = 0.5*x0*fc0; vr[1] = 0.5*x1*fc1; vr[2] = 0.5*x2*fc2; vr[3] = 0.5*x0*fc1; vr[4] = 0.5*x0*fc2; vr[5] = 0.5*x1*fc2; v_tally(1,&i,1.0,vr); } } // set orientation, omega, angmom of each extended particle if (extended) { double theta_body,theta; double *shape,*quatatom,*inertiaatom; AtomVecEllipsoid::Bonus *ebonus; if (avec_ellipsoid) ebonus = avec_ellipsoid->bonus; AtomVecLine::Bonus *lbonus; if (avec_line) lbonus = avec_line->bonus; AtomVecTri::Bonus *tbonus; if (avec_tri) tbonus = avec_tri->bonus; double **omega_one = atom->omega; double **angmom_one = atom->angmom; double **mu = atom->mu; int *ellipsoid = atom->ellipsoid; int *line = atom->line; int *tri = atom->tri; for (int i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; if (eflags[i] & SPHERE) { omega_one[i][0] = omega[ibody][0]; omega_one[i][1] = omega[ibody][1]; omega_one[i][2] = omega[ibody][2]; } else if (eflags[i] & ELLIPSOID) { shape = ebonus[ellipsoid[i]].shape; quatatom = ebonus[ellipsoid[i]].quat; MathExtra::quatquat(quat[ibody],orient[i],quatatom); MathExtra::qnormalize(quatatom); ione[0] = EINERTIA*rmass[i] * (shape[1]*shape[1] + shape[2]*shape[2]); ione[1] = EINERTIA*rmass[i] * (shape[0]*shape[0] + shape[2]*shape[2]); ione[2] = EINERTIA*rmass[i] * (shape[0]*shape[0] + shape[1]*shape[1]); MathExtra::q_to_exyz(quatatom,exone,eyone,ezone); MathExtra::omega_to_angmom(omega[ibody],exone,eyone,ezone,ione, angmom_one[i]); } else if (eflags[i] & LINE) { if (quat[ibody][3] >= 0.0) theta_body = 2.0*acos(quat[ibody][0]); else theta_body = -2.0*acos(quat[ibody][0]); theta = orient[i][0] + theta_body; while (theta <= -MY_PI) theta += MY_2PI; while (theta > MY_PI) theta -= MY_2PI; lbonus[line[i]].theta = theta; omega_one[i][0] = omega[ibody][0]; omega_one[i][1] = omega[ibody][1]; omega_one[i][2] = omega[ibody][2]; } else if (eflags[i] & TRIANGLE) { inertiaatom = tbonus[tri[i]].inertia; quatatom = tbonus[tri[i]].quat; MathExtra::quatquat(quat[ibody],orient[i],quatatom); MathExtra::qnormalize(quatatom); MathExtra::q_to_exyz(quatatom,exone,eyone,ezone); MathExtra::omega_to_angmom(omega[ibody],exone,eyone,ezone, inertiaatom,angmom_one[i]); } if (eflags[i] & DIPOLE) { MathExtra::quat_to_mat(quat[ibody],p); MathExtra::matvec(p,dorient[i],mu[i]); MathExtra::snormalize3(mu[i][3],mu[i],mu[i]); } } } } /* ---------------------------------------------------------------------- set space-frame velocity of each atom in a rigid body set omega and angmom of extended particles v = Vcm + (W cross (x - Xcm)) ------------------------------------------------------------------------- */ void FixRigid::set_v() { int xbox,ybox,zbox; double x0,x1,x2,v0,v1,v2,fc0,fc1,fc2,massone; double xy,xz,yz; double ione[3],exone[3],eyone[3],ezone[3],delta[3],vr[6]; double **x = atom->x; double **v = atom->v; double **f = atom->f; double *rmass = atom->rmass; double *mass = atom->mass; int *type = atom->type; int nlocal = atom->nlocal; double xprd = domain->xprd; double yprd = domain->yprd; double zprd = domain->zprd; if (triclinic) { xy = domain->xy; xz = domain->xz; yz = domain->yz; } // set v of each atom for (int i = 0; i < nlocal; i++) { if (body[i] < 0) continue; const int ibody = body[i]; MathExtra::matvec(ex_space[ibody],ey_space[ibody], ez_space[ibody],displace[i],delta); // save old velocities for virial if (evflag) { v0 = v[i][0]; v1 = v[i][1]; v2 = v[i][2]; } v[i][0] = omega[ibody][1]*delta[2] - omega[ibody][2]*delta[1] + vcm[ibody][0]; v[i][1] = omega[ibody][2]*delta[0] - omega[ibody][0]*delta[2] + vcm[ibody][1]; v[i][2] = omega[ibody][0]*delta[1] - omega[ibody][1]*delta[0] + vcm[ibody][2]; // virial = unwrapped coords dotted into body constraint force // body constraint force = implied force due to v change minus f external // assume f does not include forces internal to body // 1/2 factor b/c initial_integrate contributes other half // assume per-atom contribution is due to constraint force on that atom if (evflag) { if (rmass) massone = rmass[i]; else massone = mass[type[i]]; fc0 = massone*(v[i][0] - v0)/dtf - f[i][0]; fc1 = massone*(v[i][1] - v1)/dtf - f[i][1]; fc2 = massone*(v[i][2] - v2)/dtf - f[i][2]; xbox = (xcmimage[i] & IMGMASK) - IMGMAX; ybox = (xcmimage[i] >> IMGBITS & IMGMASK) - IMGMAX; zbox = (xcmimage[i] >> IMG2BITS) - IMGMAX; if (triclinic == 0) { x0 = x[i][0] + xbox*xprd; x1 = x[i][1] + ybox*yprd; x2 = x[i][2] + zbox*zprd; } else { x0 = x[i][0] + xbox*xprd + ybox*xy + zbox*xz; x1 = x[i][1] + ybox*yprd + zbox*yz; x2 = x[i][2] + zbox*zprd; } vr[0] = 0.5*x0*fc0; vr[1] = 0.5*x1*fc1; vr[2] = 0.5*x2*fc2; vr[3] = 0.5*x0*fc1; vr[4] = 0.5*x0*fc2; vr[5] = 0.5*x1*fc2; v_tally(1,&i,1.0,vr); } } // set omega, angmom of each extended particle if (extended) { double *shape,*quatatom,*inertiaatom; AtomVecEllipsoid::Bonus *ebonus; if (avec_ellipsoid) ebonus = avec_ellipsoid->bonus; AtomVecTri::Bonus *tbonus; if (avec_tri) tbonus = avec_tri->bonus; double **omega_one = atom->omega; double **angmom_one = atom->angmom; int *ellipsoid = atom->ellipsoid; int *tri = atom->tri; for (int i = 0; i < nlocal; i++) { if (body[i] < 0) continue; const int ibody = body[i]; if (eflags[i] & SPHERE) { omega_one[i][0] = omega[ibody][0]; omega_one[i][1] = omega[ibody][1]; omega_one[i][2] = omega[ibody][2]; } else if (eflags[i] & ELLIPSOID) { shape = ebonus[ellipsoid[i]].shape; quatatom = ebonus[ellipsoid[i]].quat; ione[0] = EINERTIA*rmass[i] * (shape[1]*shape[1] + shape[2]*shape[2]); ione[1] = EINERTIA*rmass[i] * (shape[0]*shape[0] + shape[2]*shape[2]); ione[2] = EINERTIA*rmass[i] * (shape[0]*shape[0] + shape[1]*shape[1]); MathExtra::q_to_exyz(quatatom,exone,eyone,ezone); MathExtra::omega_to_angmom(omega[ibody],exone,eyone,ezone,ione, angmom_one[i]); } else if (eflags[i] & LINE) { omega_one[i][0] = omega[ibody][0]; omega_one[i][1] = omega[ibody][1]; omega_one[i][2] = omega[ibody][2]; } else if (eflags[i] & TRIANGLE) { inertiaatom = tbonus[tri[i]].inertia; quatatom = tbonus[tri[i]].quat; MathExtra::q_to_exyz(quatatom,exone,eyone,ezone); MathExtra::omega_to_angmom(omega[ibody],exone,eyone,ezone, inertiaatom,angmom_one[i]); } } } } /* ---------------------------------------------------------------------- one-time initialization of static rigid body attributes sets extended flags, masstotal, center-of-mass sets Cartesian and diagonalized inertia tensor sets body image flags may read some properties from inpfile ------------------------------------------------------------------------- */ void FixRigid::setup_bodies_static() { int i,ibody; // extended = 1 if any particle in a rigid body is finite size // or has a dipole moment extended = orientflag = dorientflag = 0; AtomVecEllipsoid::Bonus *ebonus; if (avec_ellipsoid) ebonus = avec_ellipsoid->bonus; AtomVecLine::Bonus *lbonus; if (avec_line) lbonus = avec_line->bonus; AtomVecTri::Bonus *tbonus; if (avec_tri) tbonus = avec_tri->bonus; double **mu = atom->mu; double *radius = atom->radius; double *rmass = atom->rmass; double *mass = atom->mass; int *ellipsoid = atom->ellipsoid; int *line = atom->line; int *tri = atom->tri; int *type = atom->type; int nlocal = atom->nlocal; if (atom->radius_flag || atom->ellipsoid_flag || atom->line_flag || atom->tri_flag || atom->mu_flag) { int flag = 0; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; if (radius && radius[i] > 0.0) flag = 1; if (ellipsoid && ellipsoid[i] >= 0) flag = 1; if (line && line[i] >= 0) flag = 1; if (tri && tri[i] >= 0) flag = 1; if (mu && mu[i][3] > 0.0) flag = 1; } MPI_Allreduce(&flag,&extended,1,MPI_INT,MPI_MAX,world); } // grow extended arrays and set extended flags for each particle // orientflag = 4 if any particle stores ellipsoid or tri orientation // orientflag = 1 if any particle stores line orientation // dorientflag = 1 if any particle stores dipole orientation if (extended) { if (atom->ellipsoid_flag) orientflag = 4; if (atom->line_flag) orientflag = 1; if (atom->tri_flag) orientflag = 4; if (atom->mu_flag) dorientflag = 1; grow_arrays(atom->nmax); for (i = 0; i < nlocal; i++) { eflags[i] = 0; if (body[i] < 0) continue; // set to POINT or SPHERE or ELLIPSOID or LINE if (radius && radius[i] > 0.0) { eflags[i] |= SPHERE; eflags[i] |= OMEGA; eflags[i] |= TORQUE; } else if (ellipsoid && ellipsoid[i] >= 0) { eflags[i] |= ELLIPSOID; eflags[i] |= ANGMOM; eflags[i] |= TORQUE; } else if (line && line[i] >= 0) { eflags[i] |= LINE; eflags[i] |= OMEGA; eflags[i] |= TORQUE; } else if (tri && tri[i] >= 0) { eflags[i] |= TRIANGLE; eflags[i] |= ANGMOM; eflags[i] |= TORQUE; } else eflags[i] |= POINT; // set DIPOLE if atom->mu and mu[3] > 0.0 if (atom->mu_flag && mu[i][3] > 0.0) eflags[i] |= DIPOLE; } } // set body xcmimage flags = true image flags imageint *image = atom->image; for (i = 0; i < nlocal; i++) if (body[i] >= 0) xcmimage[i] = image[i]; else xcmimage[i] = 0; // compute masstotal & center-of-mass of each rigid body // error if image flag is not 0 in a non-periodic dim double **x = atom->x; int *periodicity = domain->periodicity; double xprd = domain->xprd; double yprd = domain->yprd; double zprd = domain->zprd; double xy = domain->xy; double xz = domain->xz; double yz = domain->yz; for (ibody = 0; ibody < nbody; ibody++) for (i = 0; i < 6; i++) sum[ibody][i] = 0.0; int xbox,ybox,zbox; double massone,xunwrap,yunwrap,zunwrap; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; xbox = (xcmimage[i] & IMGMASK) - IMGMAX; ybox = (xcmimage[i] >> IMGBITS & IMGMASK) - IMGMAX; zbox = (xcmimage[i] >> IMG2BITS) - IMGMAX; if (rmass) massone = rmass[i]; else massone = mass[type[i]]; if ((xbox && !periodicity[0]) || (ybox && !periodicity[1]) || (zbox && !periodicity[2])) error->one(FLERR,"Fix rigid atom has non-zero image flag " "in a non-periodic dimension"); if (triclinic == 0) { xunwrap = x[i][0] + xbox*xprd; yunwrap = x[i][1] + ybox*yprd; zunwrap = x[i][2] + zbox*zprd; } else { xunwrap = x[i][0] + xbox*xprd + ybox*xy + zbox*xz; yunwrap = x[i][1] + ybox*yprd + zbox*yz; zunwrap = x[i][2] + zbox*zprd; } sum[ibody][0] += xunwrap * massone; sum[ibody][1] += yunwrap * massone; sum[ibody][2] += zunwrap * massone; sum[ibody][3] += massone; } MPI_Allreduce(sum[0],all[0],6*nbody,MPI_DOUBLE,MPI_SUM,world); for (ibody = 0; ibody < nbody; ibody++) { masstotal[ibody] = all[ibody][3]; xcm[ibody][0] = all[ibody][0]/masstotal[ibody]; xcm[ibody][1] = all[ibody][1]/masstotal[ibody]; xcm[ibody][2] = all[ibody][2]/masstotal[ibody]; } // set vcm, angmom = 0.0 in case inpfile is used // and doesn't overwrite all body's values // since setup_bodies_dynamic() will not be called for (ibody = 0; ibody < nbody; ibody++) { vcm[ibody][0] = vcm[ibody][1] = vcm[ibody][2] = 0.0; angmom[ibody][0] = angmom[ibody][1] = angmom[ibody][2] = 0.0; } // set rigid body image flags to default values for (ibody = 0; ibody < nbody; ibody++) imagebody[ibody] = ((imageint) IMGMAX << IMG2BITS) | ((imageint) IMGMAX << IMGBITS) | IMGMAX; // overwrite masstotal, center-of-mass, image flags with file values // inbody[i] = 0/1 if Ith rigid body is initialized by file int *inbody; if (inpfile) { memory->create(inbody,nbody,"rigid:inbody"); for (ibody = 0; ibody < nbody; ibody++) inbody[ibody] = 0; readfile(0,masstotal,xcm,vcm,angmom,imagebody,inbody); } // remap the xcm of each body back into simulation box // and reset body and atom xcmimage flags via pre_neighbor() pre_neighbor(); // compute 6 moments of inertia of each body in Cartesian reference frame // dx,dy,dz = coords relative to center-of-mass // symmetric 3x3 inertia tensor stored in Voigt notation as 6-vector double dx,dy,dz; for (ibody = 0; ibody < nbody; ibody++) for (i = 0; i < 6; i++) sum[ibody][i] = 0.0; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; xbox = (xcmimage[i] & IMGMASK) - IMGMAX; ybox = (xcmimage[i] >> IMGBITS & IMGMASK) - IMGMAX; zbox = (xcmimage[i] >> IMG2BITS) - IMGMAX; if (triclinic == 0) { xunwrap = x[i][0] + xbox*xprd; yunwrap = x[i][1] + ybox*yprd; zunwrap = x[i][2] + zbox*zprd; } else { xunwrap = x[i][0] + xbox*xprd + ybox*xy + zbox*xz; yunwrap = x[i][1] + ybox*yprd + zbox*yz; zunwrap = x[i][2] + zbox*zprd; } dx = xunwrap - xcm[ibody][0]; dy = yunwrap - xcm[ibody][1]; dz = zunwrap - xcm[ibody][2]; if (rmass) massone = rmass[i]; else massone = mass[type[i]]; sum[ibody][0] += massone * (dy*dy + dz*dz); sum[ibody][1] += massone * (dx*dx + dz*dz); sum[ibody][2] += massone * (dx*dx + dy*dy); sum[ibody][3] -= massone * dy*dz; sum[ibody][4] -= massone * dx*dz; sum[ibody][5] -= massone * dx*dy; } // extended particles may contribute extra terms to moments of inertia if (extended) { double ivec[6]; double *shape,*quatatom,*inertiaatom; double length,theta; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; if (rmass) massone = rmass[i]; else massone = mass[type[i]]; if (eflags[i] & SPHERE) { sum[ibody][0] += SINERTIA*massone * radius[i]*radius[i]; sum[ibody][1] += SINERTIA*massone * radius[i]*radius[i]; sum[ibody][2] += SINERTIA*massone * radius[i]*radius[i]; } else if (eflags[i] & ELLIPSOID) { shape = ebonus[ellipsoid[i]].shape; quatatom = ebonus[ellipsoid[i]].quat; MathExtra::inertia_ellipsoid(shape,quatatom,massone,ivec); sum[ibody][0] += ivec[0]; sum[ibody][1] += ivec[1]; sum[ibody][2] += ivec[2]; sum[ibody][3] += ivec[3]; sum[ibody][4] += ivec[4]; sum[ibody][5] += ivec[5]; } else if (eflags[i] & LINE) { length = lbonus[line[i]].length; theta = lbonus[line[i]].theta; MathExtra::inertia_line(length,theta,massone,ivec); sum[ibody][0] += ivec[0]; sum[ibody][1] += ivec[1]; sum[ibody][2] += ivec[2]; sum[ibody][3] += ivec[3]; sum[ibody][4] += ivec[4]; sum[ibody][5] += ivec[5]; } else if (eflags[i] & TRIANGLE) { inertiaatom = tbonus[tri[i]].inertia; quatatom = tbonus[tri[i]].quat; MathExtra::inertia_triangle(inertiaatom,quatatom,massone,ivec); sum[ibody][0] += ivec[0]; sum[ibody][1] += ivec[1]; sum[ibody][2] += ivec[2]; sum[ibody][3] += ivec[3]; sum[ibody][4] += ivec[4]; sum[ibody][5] += ivec[5]; } } } MPI_Allreduce(sum[0],all[0],6*nbody,MPI_DOUBLE,MPI_SUM,world); // overwrite Cartesian inertia tensor with file values if (inpfile) readfile(1,NULL,all,NULL,NULL,NULL,inbody); // diagonalize inertia tensor for each body via Jacobi rotations // inertia = 3 eigenvalues = principal moments of inertia // evectors and exzy_space = 3 evectors = principal axes of rigid body int ierror; double cross[3]; double tensor[3][3],evectors[3][3]; for (ibody = 0; ibody < nbody; ibody++) { tensor[0][0] = all[ibody][0]; tensor[1][1] = all[ibody][1]; tensor[2][2] = all[ibody][2]; tensor[1][2] = tensor[2][1] = all[ibody][3]; tensor[0][2] = tensor[2][0] = all[ibody][4]; tensor[0][1] = tensor[1][0] = all[ibody][5]; ierror = MathExtra::jacobi(tensor,inertia[ibody],evectors); if (ierror) error->all(FLERR, "Insufficient Jacobi rotations for rigid body"); ex_space[ibody][0] = evectors[0][0]; ex_space[ibody][1] = evectors[1][0]; ex_space[ibody][2] = evectors[2][0]; ey_space[ibody][0] = evectors[0][1]; ey_space[ibody][1] = evectors[1][1]; ey_space[ibody][2] = evectors[2][1]; ez_space[ibody][0] = evectors[0][2]; ez_space[ibody][1] = evectors[1][2]; ez_space[ibody][2] = evectors[2][2]; // if any principal moment < scaled EPSILON, set to 0.0 double max; max = MAX(inertia[ibody][0],inertia[ibody][1]); max = MAX(max,inertia[ibody][2]); if (inertia[ibody][0] < EPSILON*max) inertia[ibody][0] = 0.0; if (inertia[ibody][1] < EPSILON*max) inertia[ibody][1] = 0.0; if (inertia[ibody][2] < EPSILON*max) inertia[ibody][2] = 0.0; // enforce 3 evectors as a right-handed coordinate system // flip 3rd vector if needed MathExtra::cross3(ex_space[ibody],ey_space[ibody],cross); if (MathExtra::dot3(cross,ez_space[ibody]) < 0.0) MathExtra::negate3(ez_space[ibody]); // create initial quaternion MathExtra::exyz_to_q(ex_space[ibody],ey_space[ibody],ez_space[ibody], quat[ibody]); } // displace = initial atom coords in basis of principal axes // set displace = 0.0 for atoms not in any rigid body // for extended particles, set their orientation wrt to rigid body double qc[4],delta[3]; double *quatatom; double theta_body; for (i = 0; i < nlocal; i++) { if (body[i] < 0) { displace[i][0] = displace[i][1] = displace[i][2] = 0.0; continue; } ibody = body[i]; xbox = (xcmimage[i] & IMGMASK) - IMGMAX; ybox = (xcmimage[i] >> IMGBITS & IMGMASK) - IMGMAX; zbox = (xcmimage[i] >> IMG2BITS) - IMGMAX; if (triclinic == 0) { xunwrap = x[i][0] + xbox*xprd; yunwrap = x[i][1] + ybox*yprd; zunwrap = x[i][2] + zbox*zprd; } else { xunwrap = x[i][0] + xbox*xprd + ybox*xy + zbox*xz; yunwrap = x[i][1] + ybox*yprd + zbox*yz; zunwrap = x[i][2] + zbox*zprd; } delta[0] = xunwrap - xcm[ibody][0]; delta[1] = yunwrap - xcm[ibody][1]; delta[2] = zunwrap - xcm[ibody][2]; MathExtra::transpose_matvec(ex_space[ibody],ey_space[ibody], ez_space[ibody],delta,displace[i]); if (extended) { if (eflags[i] & ELLIPSOID) { quatatom = ebonus[ellipsoid[i]].quat; MathExtra::qconjugate(quat[ibody],qc); MathExtra::quatquat(qc,quatatom,orient[i]); MathExtra::qnormalize(orient[i]); } else if (eflags[i] & LINE) { if (quat[ibody][3] >= 0.0) theta_body = 2.0*acos(quat[ibody][0]); else theta_body = -2.0*acos(quat[ibody][0]); orient[i][0] = lbonus[line[i]].theta - theta_body; while (orient[i][0] <= -MY_PI) orient[i][0] += MY_2PI; while (orient[i][0] > MY_PI) orient[i][0] -= MY_2PI; if (orientflag == 4) orient[i][1] = orient[i][2] = orient[i][3] = 0.0; } else if (eflags[i] & TRIANGLE) { quatatom = tbonus[tri[i]].quat; MathExtra::qconjugate(quat[ibody],qc); MathExtra::quatquat(qc,quatatom,orient[i]); MathExtra::qnormalize(orient[i]); } else if (orientflag == 4) { orient[i][0] = orient[i][1] = orient[i][2] = orient[i][3] = 0.0; } else if (orientflag == 1) orient[i][0] = 0.0; if (eflags[i] & DIPOLE) { MathExtra::transpose_matvec(ex_space[ibody],ey_space[ibody], ez_space[ibody],mu[i],dorient[i]); MathExtra::snormalize3(mu[i][3],dorient[i],dorient[i]); } else if (dorientflag) dorient[i][0] = dorient[i][1] = dorient[i][2] = 0.0; } } // test for valid principal moments & axes // recompute moments of inertia around new axes // 3 diagonal moments should equal principal moments // 3 off-diagonal moments should be 0.0 // extended particles may contribute extra terms to moments of inertia for (ibody = 0; ibody < nbody; ibody++) for (i = 0; i < 6; i++) sum[ibody][i] = 0.0; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; if (rmass) massone = rmass[i]; else massone = mass[type[i]]; sum[ibody][0] += massone * (displace[i][1]*displace[i][1] + displace[i][2]*displace[i][2]); sum[ibody][1] += massone * (displace[i][0]*displace[i][0] + displace[i][2]*displace[i][2]); sum[ibody][2] += massone * (displace[i][0]*displace[i][0] + displace[i][1]*displace[i][1]); sum[ibody][3] -= massone * displace[i][1]*displace[i][2]; sum[ibody][4] -= massone * displace[i][0]*displace[i][2]; sum[ibody][5] -= massone * displace[i][0]*displace[i][1]; } if (extended) { double ivec[6]; double *shape,*inertiaatom; double length; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; if (rmass) massone = rmass[i]; else massone = mass[type[i]]; if (eflags[i] & SPHERE) { sum[ibody][0] += SINERTIA*massone * radius[i]*radius[i]; sum[ibody][1] += SINERTIA*massone * radius[i]*radius[i]; sum[ibody][2] += SINERTIA*massone * radius[i]*radius[i]; } else if (eflags[i] & ELLIPSOID) { shape = ebonus[ellipsoid[i]].shape; MathExtra::inertia_ellipsoid(shape,orient[i],massone,ivec); sum[ibody][0] += ivec[0]; sum[ibody][1] += ivec[1]; sum[ibody][2] += ivec[2]; sum[ibody][3] += ivec[3]; sum[ibody][4] += ivec[4]; sum[ibody][5] += ivec[5]; } else if (eflags[i] & LINE) { length = lbonus[line[i]].length; MathExtra::inertia_line(length,orient[i][0],massone,ivec); sum[ibody][0] += ivec[0]; sum[ibody][1] += ivec[1]; sum[ibody][2] += ivec[2]; sum[ibody][3] += ivec[3]; sum[ibody][4] += ivec[4]; sum[ibody][5] += ivec[5]; } else if (eflags[i] & TRIANGLE) { inertiaatom = tbonus[tri[i]].inertia; MathExtra::inertia_triangle(inertiaatom,orient[i],massone,ivec); sum[ibody][0] += ivec[0]; sum[ibody][1] += ivec[1]; sum[ibody][2] += ivec[2]; sum[ibody][3] += ivec[3]; sum[ibody][4] += ivec[4]; sum[ibody][5] += ivec[5]; } } } MPI_Allreduce(sum[0],all[0],6*nbody,MPI_DOUBLE,MPI_SUM,world); // error check that re-computed moments of inertia match diagonalized ones // do not do test for bodies with params read from inpfile double norm; for (ibody = 0; ibody < nbody; ibody++) { if (inpfile && inbody[ibody]) continue; if (inertia[ibody][0] == 0.0) { if (fabs(all[ibody][0]) > TOLERANCE) error->all(FLERR,"Fix rigid: Bad principal moments"); } else { if (fabs((all[ibody][0]-inertia[ibody][0])/inertia[ibody][0]) > TOLERANCE) error->all(FLERR,"Fix rigid: Bad principal moments"); } if (inertia[ibody][1] == 0.0) { if (fabs(all[ibody][1]) > TOLERANCE) error->all(FLERR,"Fix rigid: Bad principal moments"); } else { if (fabs((all[ibody][1]-inertia[ibody][1])/inertia[ibody][1]) > TOLERANCE) error->all(FLERR,"Fix rigid: Bad principal moments"); } if (inertia[ibody][2] == 0.0) { if (fabs(all[ibody][2]) > TOLERANCE) error->all(FLERR,"Fix rigid: Bad principal moments"); } else { if (fabs((all[ibody][2]-inertia[ibody][2])/inertia[ibody][2]) > TOLERANCE) error->all(FLERR,"Fix rigid: Bad principal moments"); } norm = (inertia[ibody][0] + inertia[ibody][1] + inertia[ibody][2]) / 3.0; if (fabs(all[ibody][3]/norm) > TOLERANCE || fabs(all[ibody][4]/norm) > TOLERANCE || fabs(all[ibody][5]/norm) > TOLERANCE) error->all(FLERR,"Fix rigid: Bad principal moments"); } if (inpfile) memory->destroy(inbody); } /* ---------------------------------------------------------------------- one-time initialization of dynamic rigid body attributes set vcm and angmom, computed explicitly from constituent particles not done if body properites read from file, e.g. for overlapping particles ------------------------------------------------------------------------- */ void FixRigid::setup_bodies_dynamic() { int i,ibody; double massone,radone; // vcm = velocity of center-of-mass of each rigid body // angmom = angular momentum of each rigid body double **x = atom->x; double **v = atom->v; double *rmass = atom->rmass; double *mass = atom->mass; int *type = atom->type; int nlocal = atom->nlocal; double dx,dy,dz; double unwrap[3]; for (ibody = 0; ibody < nbody; ibody++) for (i = 0; i < 6; i++) sum[ibody][i] = 0.0; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; if (rmass) massone = rmass[i]; else massone = mass[type[i]]; sum[ibody][0] += v[i][0] * massone; sum[ibody][1] += v[i][1] * massone; sum[ibody][2] += v[i][2] * massone; domain->unmap(x[i],xcmimage[i],unwrap); dx = unwrap[0] - xcm[ibody][0]; dy = unwrap[1] - xcm[ibody][1]; dz = unwrap[2] - xcm[ibody][2]; sum[ibody][3] += dy * massone*v[i][2] - dz * massone*v[i][1]; sum[ibody][4] += dz * massone*v[i][0] - dx * massone*v[i][2]; sum[ibody][5] += dx * massone*v[i][1] - dy * massone*v[i][0]; } // extended particles add their rotation to angmom of body if (extended) { AtomVecLine::Bonus *lbonus; if (avec_line) lbonus = avec_line->bonus; double **omega_one = atom->omega; double **angmom_one = atom->angmom; double *radius = atom->radius; int *line = atom->line; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; if (eflags[i] & OMEGA) { if (eflags[i] & SPHERE) { radone = radius[i]; sum[ibody][3] += SINERTIA*rmass[i] * radone*radone * omega_one[i][0]; sum[ibody][4] += SINERTIA*rmass[i] * radone*radone * omega_one[i][1]; sum[ibody][5] += SINERTIA*rmass[i] * radone*radone * omega_one[i][2]; } else if (eflags[i] & LINE) { radone = lbonus[line[i]].length; sum[ibody][5] += LINERTIA*rmass[i] * radone*radone * omega_one[i][2]; } } if (eflags[i] & ANGMOM) { sum[ibody][3] += angmom_one[i][0]; sum[ibody][4] += angmom_one[i][1]; sum[ibody][5] += angmom_one[i][2]; } } } MPI_Allreduce(sum[0],all[0],6*nbody,MPI_DOUBLE,MPI_SUM,world); // normalize velocity of COM for (ibody = 0; ibody < nbody; ibody++) { vcm[ibody][0] = all[ibody][0]/masstotal[ibody]; vcm[ibody][1] = all[ibody][1]/masstotal[ibody]; vcm[ibody][2] = all[ibody][2]/masstotal[ibody]; angmom[ibody][0] = all[ibody][3]; angmom[ibody][1] = all[ibody][4]; angmom[ibody][2] = all[ibody][5]; } } /* ---------------------------------------------------------------------- read per rigid body info from user-provided file which = 0 to read everthing except 6 moments of inertia which = 1 to read 6 moments of inertia flag inbody = 0 for bodies whose info is read from file nlines = # of lines of rigid body info one line = rigid-ID mass xcm ycm zcm ixx iyy izz ixy ixz iyz vxcm vycm vzcm lx ly lz ix iy iz ------------------------------------------------------------------------- */ void FixRigid::readfile(int which, double *vec, double **array1, double **array2, double **array3, imageint *ivec, int *inbody) { int j,nchunk,id,eofflag,xbox,ybox,zbox; int nlines; FILE *fp; char *eof,*start,*next,*buf; char line[MAXLINE]; if (me == 0) { fp = fopen(inpfile,"r"); if (fp == NULL) { char str[128]; snprintf(str,128,"Cannot open fix rigid inpfile %s",inpfile); error->one(FLERR,str); } while (1) { eof = fgets(line,MAXLINE,fp); if (eof == NULL) error->one(FLERR,"Unexpected end of fix rigid file"); start = &line[strspn(line," \t\n\v\f\r")]; if (*start != '\0' && *start != '#') break; } sscanf(line,"%d",&nlines); } MPI_Bcast(&nlines,1,MPI_INT,0,world); if (nlines == 0) error->all(FLERR,"Fix rigid file has no lines"); char *buffer = new char[CHUNK*MAXLINE]; char **values = new char*[ATTRIBUTE_PERBODY]; int nread = 0; while (nread < nlines) { nchunk = MIN(nlines-nread,CHUNK); eofflag = comm->read_lines_from_file(fp,nchunk,MAXLINE,buffer); if (eofflag) error->all(FLERR,"Unexpected end of fix rigid file"); buf = buffer; next = strchr(buf,'\n'); *next = '\0'; int nwords = atom->count_words(buf); *next = '\n'; if (nwords != ATTRIBUTE_PERBODY) error->all(FLERR,"Incorrect rigid body format in fix rigid file"); // loop over lines of rigid body attributes // tokenize the line into values // id = rigid body ID // use ID as-is for SINGLE, as mol-ID for MOLECULE, as-is for GROUP // for which = 0, store all but inertia in vecs and arrays // for which = 1, store inertia tensor array, invert 3,4,5 values to Voigt for (int i = 0; i < nchunk; i++) { next = strchr(buf,'\n'); values[0] = strtok(buf," \t\n\r\f"); for (j = 1; j < nwords; j++) values[j] = strtok(NULL," \t\n\r\f"); id = atoi(values[0]); if (rstyle == MOLECULE) { if (id <= 0 || id > maxmol) error->all(FLERR,"Invalid rigid body ID in fix rigid file"); id = mol2body[id]; } else id--; if (id < 0 || id >= nbody) error->all(FLERR,"Invalid rigid body ID in fix rigid file"); inbody[id] = 1; if (which == 0) { vec[id] = atof(values[1]); array1[id][0] = atof(values[2]); array1[id][1] = atof(values[3]); array1[id][2] = atof(values[4]); array2[id][0] = atof(values[11]); array2[id][1] = atof(values[12]); array2[id][2] = atof(values[13]); array3[id][0] = atof(values[14]); array3[id][1] = atof(values[15]); array3[id][2] = atof(values[16]); xbox = atoi(values[17]); ybox = atoi(values[18]); zbox = atoi(values[19]); ivec[id] = ((imageint) (xbox + IMGMAX) & IMGMASK) | (((imageint) (ybox + IMGMAX) & IMGMASK) << IMGBITS) | (((imageint) (zbox + IMGMAX) & IMGMASK) << IMG2BITS); } else { array1[id][0] = atof(values[5]); array1[id][1] = atof(values[6]); array1[id][2] = atof(values[7]); array1[id][3] = atof(values[10]); array1[id][4] = atof(values[9]); array1[id][5] = atof(values[8]); } buf = next + 1; } nread += nchunk; } if (me == 0) fclose(fp); delete [] buffer; delete [] values; } /* ---------------------------------------------------------------------- write out restart info for mass, COM, inertia tensor, image flags to file identical format to inpfile option, so info can be read in when restarting only proc 0 writes list of global bodies to file ------------------------------------------------------------------------- */ void FixRigid::write_restart_file(char *file) { if (me) return; char outfile[128]; snprintf(outfile,128,"%s.rigid",file); FILE *fp = fopen(outfile,"w"); if (fp == NULL) { char str[192]; snprintf(str,192,"Cannot open fix rigid restart file %s",outfile); error->one(FLERR,str); } fprintf(fp,"# fix rigid mass, COM, inertia tensor info for " "%d bodies on timestep " BIGINT_FORMAT "\n\n", nbody,update->ntimestep); fprintf(fp,"%d\n",nbody); // compute I tensor against xyz axes from diagonalized I and current quat // Ispace = P Idiag P_transpose // P is stored column-wise in exyz_space int xbox,ybox,zbox; double p[3][3],pdiag[3][3],ispace[3][3]; int id; for (int i = 0; i < nbody; i++) { if (rstyle == SINGLE || rstyle == GROUP) id = i; else id = body2mol[i]; MathExtra::col2mat(ex_space[i],ey_space[i],ez_space[i],p); MathExtra::times3_diag(p,inertia[i],pdiag); MathExtra::times3_transpose(pdiag,p,ispace); xbox = (imagebody[i] & IMGMASK) - IMGMAX; ybox = (imagebody[i] >> IMGBITS & IMGMASK) - IMGMAX; zbox = (imagebody[i] >> IMG2BITS) - IMGMAX; fprintf(fp,"%d %-1.16e %-1.16e %-1.16e %-1.16e " "%-1.16e %-1.16e %-1.16e %-1.16e %-1.16e %-1.16e " "%-1.16e %-1.16e %-1.16e %-1.16e %-1.16e %-1.16e " "%d %d %d\n", id,masstotal[i],xcm[i][0],xcm[i][1],xcm[i][2], ispace[0][0],ispace[1][1],ispace[2][2], ispace[0][1],ispace[0][2],ispace[1][2], vcm[i][0],vcm[i][1],vcm[i][2], angmom[i][0],angmom[i][1],angmom[i][2], xbox,ybox,zbox); } fclose(fp); } /* ---------------------------------------------------------------------- memory usage of local atom-based arrays ------------------------------------------------------------------------- */ double FixRigid::memory_usage() { int nmax = atom->nmax; double bytes = nmax * sizeof(int); bytes += nmax * sizeof(imageint); bytes += nmax*3 * sizeof(double); bytes += maxvatom*6 * sizeof(double); // vatom if (extended) { bytes += nmax * sizeof(int); if (orientflag) bytes = nmax*orientflag * sizeof(double); if (dorientflag) bytes = nmax*3 * sizeof(double); } return bytes; } /* ---------------------------------------------------------------------- allocate local atom-based arrays ------------------------------------------------------------------------- */ void FixRigid::grow_arrays(int nmax) { memory->grow(body,nmax,"rigid:body"); memory->grow(xcmimage,nmax,"rigid:xcmimage"); memory->grow(displace,nmax,3,"rigid:displace"); if (extended) { memory->grow(eflags,nmax,"rigid:eflags"); if (orientflag) memory->grow(orient,nmax,orientflag,"rigid:orient"); if (dorientflag) memory->grow(dorient,nmax,3,"rigid:dorient"); } // check for regrow of vatom // must be done whether per-atom virial is accumulated on this step or not // b/c this is only time grow_array() may be called // need to regrow b/c vatom is calculated before and after atom migration if (nmax > maxvatom) { maxvatom = atom->nmax; memory->grow(vatom,maxvatom,6,"fix:vatom"); } } /* ---------------------------------------------------------------------- copy values within local atom-based arrays ------------------------------------------------------------------------- */ void FixRigid::copy_arrays(int i, int j, int /*delflag*/) { body[j] = body[i]; xcmimage[j] = xcmimage[i]; displace[j][0] = displace[i][0]; displace[j][1] = displace[i][1]; displace[j][2] = displace[i][2]; if (extended) { eflags[j] = eflags[i]; for (int k = 0; k < orientflag; k++) orient[j][k] = orient[i][k]; if (dorientflag) { dorient[j][0] = dorient[i][0]; dorient[j][1] = dorient[i][1]; dorient[j][2] = dorient[i][2]; } } // must also copy vatom if per-atom virial calculated on this timestep // since vatom is calculated before and after atom migration if (vflag_atom) for (int k = 0; k < 6; k++) vatom[j][k] = vatom[i][k]; } /* ---------------------------------------------------------------------- initialize one atom's array values, called when atom is created ------------------------------------------------------------------------- */ void FixRigid::set_arrays(int i) { body[i] = -1; xcmimage[i] = 0; displace[i][0] = 0.0; displace[i][1] = 0.0; displace[i][2] = 0.0; // must also zero vatom if per-atom virial calculated on this timestep // since vatom is calculated before and after atom migration if (vflag_atom) for (int k = 0; k < 6; k++) vatom[i][k] = 0.0; } /* ---------------------------------------------------------------------- pack values in local atom-based arrays for exchange with another proc ------------------------------------------------------------------------- */ int FixRigid::pack_exchange(int i, double *buf) { buf[0] = ubuf(body[i]).d; buf[1] = ubuf(xcmimage[i]).d; buf[2] = displace[i][0]; buf[3] = displace[i][1]; buf[4] = displace[i][2]; if (!extended) return 5; int m = 5; buf[m++] = eflags[i]; for (int j = 0; j < orientflag; j++) buf[m++] = orient[i][j]; if (dorientflag) { buf[m++] = dorient[i][0]; buf[m++] = dorient[i][1]; buf[m++] = dorient[i][2]; } // must also pack vatom if per-atom virial calculated on this timestep // since vatom is calculated before and after atom migration if (vflag_atom) for (int k = 0; k < 6; k++) buf[m++] = vatom[i][k]; return m; } /* ---------------------------------------------------------------------- unpack values in local atom-based arrays from exchange with another proc ------------------------------------------------------------------------- */ int FixRigid::unpack_exchange(int nlocal, double *buf) { body[nlocal] = (int) ubuf(buf[0]).i; xcmimage[nlocal] = (imageint) ubuf(buf[1]).i; displace[nlocal][0] = buf[2]; displace[nlocal][1] = buf[3]; displace[nlocal][2] = buf[4]; if (!extended) return 5; int m = 5; eflags[nlocal] = static_cast<int> (buf[m++]); for (int j = 0; j < orientflag; j++) orient[nlocal][j] = buf[m++]; if (dorientflag) { dorient[nlocal][0] = buf[m++]; dorient[nlocal][1] = buf[m++]; dorient[nlocal][2] = buf[m++]; } // must also unpack vatom if per-atom virial calculated on this timestep // since vatom is calculated before and after atom migration if (vflag_atom) for (int k = 0; k < 6; k++) vatom[nlocal][k] = buf[m++]; return m; } /* ---------------------------------------------------------------------- */ void FixRigid::reset_dt() { dtv = update->dt; dtf = 0.5 * update->dt * force->ftm2v; dtq = 0.5 * update->dt; } /* ---------------------------------------------------------------------- zero linear momentum of each rigid body set Vcm to 0.0, then reset velocities of particles via set_v() ------------------------------------------------------------------------- */ void FixRigid::zero_momentum() { for (int ibody = 0; ibody < nbody; ibody++) vcm[ibody][0] = vcm[ibody][1] = vcm[ibody][2] = 0.0; evflag = 0; set_v(); } /* ---------------------------------------------------------------------- zero angular momentum of each rigid body set angmom/omega to 0.0, then reset velocities of particles via set_v() ------------------------------------------------------------------------- */ void FixRigid::zero_rotation() { for (int ibody = 0; ibody < nbody; ibody++) { angmom[ibody][0] = angmom[ibody][1] = angmom[ibody][2] = 0.0; omega[ibody][0] = omega[ibody][1] = omega[ibody][2] = 0.0; } evflag = 0; set_v(); } /* ---------------------------------------------------------------------- */ int FixRigid::modify_param(int narg, char **arg) { if (strcmp(arg[0],"bodyforces") == 0) { if (narg < 2) error->all(FLERR,"Illegal fix_modify command"); if (strcmp(arg[1],"early") == 0) earlyflag = 1; else if (strcmp(arg[1],"late") == 0) earlyflag = 0; else error->all(FLERR,"Illegal fix_modify command"); // reset fix mask // must do here and not in init, // since modify.cpp::init() uses fix masks before calling fix::init() for (int i = 0; i < modify->nfix; i++) if (strcmp(modify->fix[i]->id,id) == 0) { if (earlyflag) modify->fmask[i] |= POST_FORCE; else if (!langflag) modify->fmask[i] &= ~POST_FORCE; break; } return 2; } return 0; } /* ---------------------------------------------------------------------- return temperature of collection of rigid bodies non-active DOF are removed by fflag/tflag and in tfactor ------------------------------------------------------------------------- */ double FixRigid::compute_scalar() { double wbody[3],rot[3][3]; double t = 0.0; for (int i = 0; i < nbody; i++) { t += masstotal[i] * (fflag[i][0]*vcm[i][0]*vcm[i][0] + fflag[i][1]*vcm[i][1]*vcm[i][1] + fflag[i][2]*vcm[i][2]*vcm[i][2]); // wbody = angular velocity in body frame MathExtra::quat_to_mat(quat[i],rot); MathExtra::transpose_matvec(rot,angmom[i],wbody); if (inertia[i][0] == 0.0) wbody[0] = 0.0; else wbody[0] /= inertia[i][0]; if (inertia[i][1] == 0.0) wbody[1] = 0.0; else wbody[1] /= inertia[i][1]; if (inertia[i][2] == 0.0) wbody[2] = 0.0; else wbody[2] /= inertia[i][2]; t += tflag[i][0]*inertia[i][0]*wbody[0]*wbody[0] + tflag[i][1]*inertia[i][1]*wbody[1]*wbody[1] + tflag[i][2]*inertia[i][2]*wbody[2]*wbody[2]; } t *= tfactor; return t; } /* ---------------------------------------------------------------------- */ void *FixRigid::extract(const char *str, int &dim) { if (strcmp(str,"body") == 0) { dim = 1; return body; } if (strcmp(str,"masstotal") == 0) { dim = 1; return masstotal; } if (strcmp(str,"t_target") == 0) { dim = 0; return &t_target; } return NULL; } /* ---------------------------------------------------------------------- return translational KE for all rigid bodies KE = 1/2 M Vcm^2 ------------------------------------------------------------------------- */ double FixRigid::extract_ke() { double ke = 0.0; for (int i = 0; i < nbody; i++) ke += masstotal[i] * (vcm[i][0]*vcm[i][0] + vcm[i][1]*vcm[i][1] + vcm[i][2]*vcm[i][2]); return 0.5*ke; } /* ---------------------------------------------------------------------- return rotational KE for all rigid bodies Erotational = 1/2 I wbody^2 ------------------------------------------------------------------------- */ double FixRigid::extract_erotational() { double wbody[3],rot[3][3]; double erotate = 0.0; for (int i = 0; i < nbody; i++) { // wbody = angular velocity in body frame MathExtra::quat_to_mat(quat[i],rot); MathExtra::transpose_matvec(rot,angmom[i],wbody); if (inertia[i][0] == 0.0) wbody[0] = 0.0; else wbody[0] /= inertia[i][0]; if (inertia[i][1] == 0.0) wbody[1] = 0.0; else wbody[1] /= inertia[i][1]; if (inertia[i][2] == 0.0) wbody[2] = 0.0; else wbody[2] /= inertia[i][2]; erotate += inertia[i][0]*wbody[0]*wbody[0] + inertia[i][1]*wbody[1]*wbody[1] + inertia[i][2]*wbody[2]*wbody[2]; } return 0.5*erotate; } /* ---------------------------------------------------------------------- return attributes of a rigid body 15 values per body xcm = 0,1,2; vcm = 3,4,5; fcm = 6,7,8; torque = 9,10,11; image = 12,13,14 ------------------------------------------------------------------------- */ double FixRigid::compute_array(int i, int j) { if (j < 3) return xcm[i][j]; if (j < 6) return vcm[i][j-3]; if (j < 9) return fcm[i][j-6]; if (j < 12) return torque[i][j-9]; if (j == 12) return (imagebody[i] & IMGMASK) - IMGMAX; if (j == 13) return (imagebody[i] >> IMGBITS & IMGMASK) - IMGMAX; return (imagebody[i] >> IMG2BITS) - IMGMAX; }
pdebuyl/lammps
src/RIGID/fix_rigid.cpp
C++
gpl-2.0
91,201
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ResourceList.cs" company="Tygertec"> // Copyright © 2016 Ty Walls. // All rights reserved. // </copyright> // <summary> // Defines the ResourceList type. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace TW.Resfit.Core { using System.Collections.Generic; using System.Linq; using TW.Resfit.Framework; public class ResourceList : ListDecoratorBase<Resource> { public ResourceList() { } public ResourceList(IEnumerable<Resource> resources) : this() { this.Items.AddRange(resources); } /// <summary> /// Gets the underlying Items collection. /// It is just a proxy for the protected Items property. /// Its only purpose is to make the code read easier. /// </summary> public ICollection<Resource> Resources { get { return this.Items; } } public ResourceList Clone(ResourceFilter filter = null) { if (filter == null) { filter = ResourceFilter.NoFilter; } var clonedList = new ResourceList(); foreach (var resource in this.Where(resource => filter.IsMatch(resource))) { clonedList.Add(new Resource(resource)); } return clonedList; } public void Merge(ResourceList resourceListToAbsorb) { foreach (var resource in resourceListToAbsorb) { if (this.All(x => x.Key != resource.Key)) { this.Add(new Resource(resource)); } } } public ResourceList TransformSelfIntoNewList() { var newList = new ResourceList(); foreach (var resource in this) { var newResource = new Resource(resource); foreach (var transform in resource.Transforms) { newResource = transform.Transform(resource); } if (newResource != null) { newList.Add(newResource); } } return newList; } } }
tygerbytes/ResourceFitness
TW.Resfit.Core/ResourceList.cs
C#
gpl-2.0
2,524
package mnm.mcpackager.gui; import java.io.File; import javax.swing.filechooser.FileFilter; public class JarFilter extends FileFilter { @Override public boolean accept(File f) { if (f.isDirectory()) return true; return getExtension(f).equalsIgnoreCase("jar"); } @Override public String getDescription() { return "Jar Archives"; } private String getExtension(File f) { String ext = null; String s = f.getName(); int i = s.lastIndexOf('.'); if (i > 0 && i < s.length() - 1) ext = s.substring(i + 1).toLowerCase(); return ext; } }
killjoy1221/MCPatcher-Repackager
src/main/java/mnm/mcpackager/gui/JarFilter.java
Java
gpl-2.0
656
/*************************************************************************** * Copyright (C) 2008-2017 by Andrzej Rybczak * * [email protected] * * * * 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., * * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef NCMPCPP_MENU_H #define NCMPCPP_MENU_H #include <boost/iterator/transform_iterator.hpp> #include <boost/range/detail/any_iterator.hpp> #include <cassert> #include <functional> #include <iterator> #include <memory> #include <set> #include "curses/formatted_color.h" #include "curses/strbuffer.h" #include "curses/window.h" #include "utility/const.h" namespace NC { struct List { struct Properties { enum Type { None = 0, Selectable = (1 << 0), Selected = (1 << 1), Inactive = (1 << 2), Separator = (1 << 3) }; Properties(Type properties = Selectable) : m_properties(properties) { } void setSelectable(bool is_selectable) { if (is_selectable) m_properties |= Selectable; else m_properties &= ~(Selectable | Selected); } void setSelected(bool is_selected) { if (!isSelectable()) return; if (is_selected) m_properties |= Selected; else m_properties &= ~Selected; } void setInactive(bool is_inactive) { if (is_inactive) m_properties |= Inactive; else m_properties &= ~Inactive; } void setSeparator(bool is_separator) { if (is_separator) m_properties |= Separator; else m_properties &= ~Separator; } bool isSelectable() const { return m_properties & Selectable; } bool isSelected() const { return m_properties & Selected; } bool isInactive() const { return m_properties & Inactive; } bool isSeparator() const { return m_properties & Separator; } private: unsigned m_properties; }; template <typename ValueT> using PropertiesIterator = boost::range_detail::any_iterator< ValueT, boost::random_access_traversal_tag, ValueT &, std::ptrdiff_t >; typedef PropertiesIterator<Properties> Iterator; typedef PropertiesIterator<const Properties> ConstIterator; virtual ~List() { } virtual bool empty() const = 0; virtual size_t size() const = 0; virtual size_t choice() const = 0; virtual void highlight(size_t pos) = 0; virtual Iterator currentP() = 0; virtual ConstIterator currentP() const = 0; virtual Iterator beginP() = 0; virtual ConstIterator beginP() const = 0; virtual Iterator endP() = 0; virtual ConstIterator endP() const = 0; }; inline List::Properties::Type operator|(List::Properties::Type lhs, List::Properties::Type rhs) { return List::Properties::Type(unsigned(lhs) | unsigned(rhs)); } inline List::Properties::Type &operator|=(List::Properties::Type &lhs, List::Properties::Type rhs) { lhs = lhs | rhs; return lhs; } inline List::Properties::Type operator&(List::Properties::Type lhs, List::Properties::Type rhs) { return List::Properties::Type(unsigned(lhs) & unsigned(rhs)); } inline List::Properties::Type &operator&=(List::Properties::Type &lhs, List::Properties::Type rhs) { lhs = lhs & rhs; return lhs; } // for range-based for loop inline List::Iterator begin(List &list) { return list.beginP(); } inline List::ConstIterator begin(const List &list) { return list.beginP(); } inline List::Iterator end(List &list) { return list.endP(); } inline List::ConstIterator end(const List &list) { return list.endP(); } /// Generic menu capable of holding any std::vector compatible values. template <typename ItemT> struct Menu: Window, List { struct Item { friend struct Menu<ItemT>; typedef ItemT Type; Item() : m_impl(std::make_shared<std::tuple<ItemT, Properties>>()) { } template <typename ValueT, typename PropertiesT> Item(ValueT &&value_, PropertiesT properties_) : m_impl( std::make_shared<std::tuple<ItemT, List::Properties>>( std::forward<ValueT>(value_), std::forward<PropertiesT>(properties_))) { } ItemT &value() { return std::get<0>(*m_impl); } const ItemT &value() const { return std::get<0>(*m_impl); } Properties &properties() { return std::get<1>(*m_impl); } const Properties &properties() const { return std::get<1>(*m_impl); } // Forward methods to List::Properties. void setSelectable(bool is_selectable) { properties().setSelectable(is_selectable); } void setSelected (bool is_selected) { properties().setSelected(is_selected); } void setInactive (bool is_inactive) { properties().setInactive(is_inactive); } void setSeparator (bool is_separator) { properties().setSeparator(is_separator); } bool isSelectable() const { return properties().isSelectable(); } bool isSelected() const { return properties().isSelected(); } bool isInactive() const { return properties().isInactive(); } bool isSeparator() const { return properties().isSeparator(); } // Make a deep copy of Item. Item copy() const { return Item(value(), properties()); } private: template <Const const_> struct ExtractProperties { typedef ExtractProperties type; typedef typename std::conditional< const_ == Const::Yes, const Properties, Properties>::type Properties_; typedef typename std::conditional< const_ == Const::Yes, const Item, Item>::type Item_; Properties_ &operator()(Item_ &i) const { return i.properties(); } }; template <Const const_> struct ExtractValue { typedef ExtractValue type; typedef typename std::conditional< const_ == Const::Yes, const ItemT, ItemT>::type Value_; typedef typename std::conditional< const_ == Const::Yes, const Item, Item>::type Item_; Value_ &operator()(Item_ &i) const { return i.value(); } }; static Item mkSeparator() { Item item; item.setSelectable(false); item.setSeparator(true); return item; } std::shared_ptr<std::tuple<ItemT, Properties>> m_impl; }; typedef typename std::vector<Item>::iterator Iterator; typedef typename std::vector<Item>::const_iterator ConstIterator; typedef std::reverse_iterator<Iterator> ReverseIterator; typedef std::reverse_iterator<ConstIterator> ConstReverseIterator; typedef boost::transform_iterator< typename Item::template ExtractValue<Const::No>, Iterator> ValueIterator; typedef boost::transform_iterator< typename Item::template ExtractValue<Const::Yes>, ConstIterator> ConstValueIterator; typedef std::reverse_iterator<ValueIterator> ReverseValueIterator; typedef std::reverse_iterator<ConstValueIterator> ConstReverseValueIterator; typedef boost::transform_iterator< typename Item::template ExtractProperties<Const::No>, Iterator> PropertiesIterator; typedef boost::transform_iterator< typename Item::template ExtractProperties<Const::Yes>, ConstIterator> ConstPropertiesIterator; // For compliance with boost utilities. typedef Iterator iterator; typedef ConstIterator const_iterator; /// Function helper prototype used to display each option on the screen. /// If not set by setItemDisplayer(), menu won't display anything. /// @see setItemDisplayer() typedef std::function<void(Menu<ItemT> &)> ItemDisplayer; typedef std::function<bool(const Item &)> FilterPredicate; Menu(); Menu(size_t startx, size_t starty, size_t width, size_t height, const std::string &title, Color color, Border border); Menu(const Menu &rhs); Menu(Menu &&rhs); Menu &operator=(Menu rhs); /// Sets helper function that is responsible for displaying items /// @param ptr function pointer that matches the ItemDisplayer prototype template <typename ItemDisplayerT> void setItemDisplayer(ItemDisplayerT &&displayer); /// Resizes the list to given size (adequate to std::vector::resize()) /// @param size requested size void resizeList(size_t new_size); /// Adds a new option to list void addItem(ItemT item, Properties::Type properties = Properties::Selectable); /// Adds separator to list void addSeparator(); /// Inserts a new option to the list at given position void insertItem(size_t pos, ItemT item, Properties::Type properties = Properties::Selectable); /// Inserts separator to list at given position /// @param pos initial position of inserted separator void insertSeparator(size_t pos); /// Moves the highlighted position to the given line of window /// @param y Y position of menu window to be highlighted /// @return true if the position is reachable, false otherwise bool Goto(size_t y); /// Checks if list is empty /// @return true if list is empty, false otherwise virtual bool empty() const override { return m_items->empty(); } /// @return size of the list virtual size_t size() const override { return m_items->size(); } /// @return currently highlighted position virtual size_t choice() const override; /// Highlights given position /// @param pos position to be highlighted virtual void highlight(size_t position) override; /// Refreshes the menu window /// @see Window::refresh() virtual void refresh() override; /// Scrolls by given amount of lines /// @param where indicated where exactly one wants to go /// @see Window::scroll() virtual void scroll(Scroll where) override; /// Cleares all options, used filters etc. It doesn't reset highlighted position though. /// @see reset() virtual void clear() override; /// Sets highlighted position to 0 void reset(); /// Apply filter predicate to items in the menu and show the ones for which it /// returned true. template <typename PredicateT> void applyFilter(PredicateT &&pred); /// Reapply previously applied filter. void reapplyFilter(); /// Get current filter predicate. template <typename TargetT> const TargetT *filterPredicate() const; /// Clear results of applyFilter and show all items. void clearFilter(); /// @return true if menu is filtered. bool isFiltered() const { return m_items == &m_filtered_items; } /// Show all items. void showAllItems() { m_items = &m_all_items; } /// Show filtered items. void showFilteredItems() { m_items = &m_filtered_items; } /// Sets prefix, that is put before each selected item to indicate its selection /// Note that the passed variable is not deleted along with menu object. /// @param b pointer to buffer that contains the prefix void setSelectedPrefix(const Buffer &b) { m_selected_prefix = b; } /// Sets suffix, that is put after each selected item to indicate its selection /// Note that the passed variable is not deleted along with menu object. /// @param b pointer to buffer that contains the suffix void setSelectedSuffix(const Buffer &b) { m_selected_suffix = b; } void setHighlightPrefix(const Buffer &b) { m_highlight_prefix = b; } void setHighlightSuffix(const Buffer &b) { m_highlight_suffix = b; } const Buffer &highlightPrefix() const { return m_highlight_prefix; } const Buffer &highlightSuffix() const { return m_highlight_suffix; } /// @return state of highlighting bool isHighlighted() { return m_highlight_enabled; } /// Turns on/off highlighting /// @param state state of hihglighting void setHighlighting(bool state) { m_highlight_enabled = state; } /// Turns on/off cyclic scrolling /// @param state state of cyclic scrolling void cyclicScrolling(bool state) { m_cyclic_scroll_enabled = state; } /// Turns on/off centered cursor /// @param state state of centered cursor void centeredCursor(bool state) { m_autocenter_cursor = state; } /// @return currently drawn item. The result is defined only within /// drawing function that is called by refresh() /// @see refresh() ConstIterator drawn() const { return begin() + m_drawn_position; } /// @param pos requested position /// @return reference to item at given position /// @throw std::out_of_range if given position is out of range Menu<ItemT>::Item &at(size_t pos) { return m_items->at(pos); } /// @param pos requested position /// @return const reference to item at given position /// @throw std::out_of_range if given position is out of range const Menu<ItemT>::Item &at(size_t pos) const { return m_items->at(pos); } /// @param pos requested position /// @return const reference to item at given position const Menu<ItemT>::Item &operator[](size_t pos) const { return (*m_items)[pos]; } /// @param pos requested position /// @return const reference to item at given position Menu<ItemT>::Item &operator[](size_t pos) { return (*m_items)[pos]; } Iterator current() { return Iterator(m_items->begin() + m_highlight); } ConstIterator current() const { return ConstIterator(m_items->begin() + m_highlight); } ReverseIterator rcurrent() { if (empty()) return rend(); else return ReverseIterator(++current()); } ConstReverseIterator rcurrent() const { if (empty()) return rend(); else return ConstReverseIterator(++current()); } ValueIterator currentV() { return ValueIterator(m_items->begin() + m_highlight); } ConstValueIterator currentV() const { return ConstValueIterator(m_items->begin() + m_highlight); } ReverseValueIterator rcurrentV() { if (empty()) return rendV(); else return ReverseValueIterator(++currentV()); } ConstReverseValueIterator rcurrentV() const { if (empty()) return rendV(); else return ConstReverseValueIterator(++currentV()); } Iterator begin() { return Iterator(m_items->begin()); } ConstIterator begin() const { return ConstIterator(m_items->begin()); } Iterator end() { return Iterator(m_items->end()); } ConstIterator end() const { return ConstIterator(m_items->end()); } ReverseIterator rbegin() { return ReverseIterator(end()); } ConstReverseIterator rbegin() const { return ConstReverseIterator(end()); } ReverseIterator rend() { return ReverseIterator(begin()); } ConstReverseIterator rend() const { return ConstReverseIterator(begin()); } ValueIterator beginV() { return ValueIterator(begin()); } ConstValueIterator beginV() const { return ConstValueIterator(begin()); } ValueIterator endV() { return ValueIterator(end()); } ConstValueIterator endV() const { return ConstValueIterator(end()); } ReverseValueIterator rbeginV() { return ReverseValueIterator(endV()); } ConstReverseIterator rbeginV() const { return ConstReverseValueIterator(endV()); } ReverseValueIterator rendV() { return ReverseValueIterator(beginV()); } ConstReverseValueIterator rendV() const { return ConstReverseValueIterator(beginV()); } virtual List::Iterator currentP() override { return List::Iterator(PropertiesIterator(m_items->begin() + m_highlight)); } virtual List::ConstIterator currentP() const override { return List::ConstIterator(ConstPropertiesIterator(m_items->begin() + m_highlight)); } virtual List::Iterator beginP() override { return List::Iterator(PropertiesIterator(m_items->begin())); } virtual List::ConstIterator beginP() const override { return List::ConstIterator(ConstPropertiesIterator(m_items->begin())); } virtual List::Iterator endP() override { return List::Iterator(PropertiesIterator(m_items->end())); } virtual List::ConstIterator endP() const override { return List::ConstIterator(ConstPropertiesIterator(m_items->end())); } private: bool isHighlightable(size_t pos) { return !(*m_items)[pos].isSeparator() && !(*m_items)[pos].isInactive(); } ItemDisplayer m_item_displayer; FilterPredicate m_filter_predicate; std::vector<Item> *m_items; std::vector<Item> m_all_items; std::vector<Item> m_filtered_items; size_t m_beginning; size_t m_highlight; bool m_highlight_enabled; bool m_cyclic_scroll_enabled; bool m_autocenter_cursor; size_t m_drawn_position; Buffer m_highlight_prefix; Buffer m_highlight_suffix; Buffer m_selected_prefix; Buffer m_selected_suffix; }; } #endif // NCMPCPP_MENU_H
KoffeinFlummi/ncmpcpp-vim
src/curses/menu.h
C
gpl-2.0
16,896
<?php /** --------------------------------------------------------------------- * app/lib/core/BaseModel.php : * ---------------------------------------------------------------------- * CollectiveAccess * Open-source collections management software * ---------------------------------------------------------------------- * * Software by Whirl-i-Gig (http://www.whirl-i-gig.com) * Copyright 2000-2012 Whirl-i-Gig * * For more information visit http://www.CollectiveAccess.org * * This program is free software; you may redistribute it and/or modify it under * the terms of the provided license as published by Whirl-i-Gig * * CollectiveAccess is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTIES whatsoever, including any implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * This source code is free and modifiable under the terms of * GNU General Public License. (http://www.gnu.org/copyleft/gpl.html). See * the "license.txt" file for details, or visit the CollectiveAccess web site at * http://www.CollectiveAccess.org * * @package CollectiveAccess * @subpackage BaseModel * @license http://www.gnu.org/copyleft/gpl.html GNU Public License version 3 * * ---------------------------------------------------------------------- */ /** * */ # ------------------------------------------------------------------------------------ # --- Field type constants # ------------------------------------------------------------------------------------ define("FT_NUMBER",0); define("FT_TEXT", 1); define("FT_TIMESTAMP", 2); define("FT_DATETIME", 3); define("FT_HISTORIC_DATETIME", 4); define("FT_DATERANGE", 5); define("FT_HISTORIC_DATERANGE", 6); define("FT_BIT", 7); define("FT_FILE", 8); define("FT_MEDIA", 9); define("FT_PASSWORD", 10); define("FT_VARS", 11); define("FT_TIMECODE", 12); define("FT_DATE", 13); define("FT_HISTORIC_DATE", 14); define("FT_TIME", 15); define("FT_TIMERANGE", 16); # ------------------------------------------------------------------------------------ # --- Display type constants # ------------------------------------------------------------------------------------ define("DT_SELECT", 0); define("DT_LIST", 1); define("DT_LIST_MULTIPLE", 2); define("DT_CHECKBOXES", 3); define("DT_RADIO_BUTTONS", 4); define("DT_FIELD", 5); define("DT_HIDDEN", 6); define("DT_OMIT", 7); define("DT_TEXT", 8); define("DT_PASSWORD", 9); define("DT_COLORPICKER", 10); define("DT_TIMECODE", 12); define("DT_COUNTRY_LIST", 13); define("DT_STATEPROV_LIST", 14); # ------------------------------------------------------------------------------------ # --- Access mode constants # ------------------------------------------------------------------------------------ define("ACCESS_READ", 0); define("ACCESS_WRITE", 1); # ------------------------------------------------------------------------------------ # --- Text-markup constants # ------------------------------------------------------------------------------------ define("__CA_MT_HTML__", 0); define("__CA_MT_TEXT_ONLY__", 1); # ------------------------------------------------------------------------------------ # --- Hierarchy type constants # ------------------------------------------------------------------------------------ define("__CA_HIER_TYPE_SIMPLE_MONO__", 1); define("__CA_HIER_TYPE_MULTI_MONO__", 2); define("__CA_HIER_TYPE_ADHOC_MONO__", 3); define("__CA_HIER_TYPE_MULTI_POLY__", 4); # ---------------------------------------------------------------------- # --- Import classes # ---------------------------------------------------------------------- require_once(__CA_LIB_DIR__."/core/BaseObject.php"); require_once(__CA_LIB_DIR__."/core/Error.php"); require_once(__CA_LIB_DIR__."/core/Configuration.php"); require_once(__CA_LIB_DIR__."/core/Datamodel.php"); require_once(__CA_LIB_DIR__."/core/ApplicationChangeLog.php"); require_once(__CA_LIB_DIR__."/core/Parsers/TimeExpressionParser.php"); require_once(__CA_LIB_DIR__."/core/Parsers/TimecodeParser.php"); require_once(__CA_LIB_DIR__."/core/Db.php"); require_once(__CA_LIB_DIR__."/core/Media.php"); require_once(__CA_LIB_DIR__."/core/Media/MediaVolumes.php"); require_once(__CA_LIB_DIR__."/core/File.php"); require_once(__CA_LIB_DIR__."/core/File/FileVolumes.php"); require_once(__CA_LIB_DIR__."/core/Utils/Timer.php"); require_once(__CA_LIB_DIR__."/core/Utils/Unicode.php"); require_once(__CA_LIB_DIR__."/core/Search/SearchIndexer.php"); require_once(__CA_LIB_DIR__."/core/Db/Transaction.php"); require_once(__CA_LIB_DIR__."/core/Media/MediaProcessingSettings.php"); require_once(__CA_APP_DIR__."/helpers/utilityHelpers.php"); require_once(__CA_APP_DIR__."/helpers/gisHelpers.php"); require_once(__CA_LIB_DIR__."/ca/ApplicationPluginManager.php"); require_once(__CA_LIB_DIR__."/core/Parsers/htmlpurifier/HTMLPurifier.standalone.php"); /** * Base class for all database table classes. Implements database insert/update/delete * functionality and a whole lot more, including automatic generation of HTML form * widgets, layering of additional field types and data processing functionality * (media upload fields using the Media class; date/time and date range fields * with natural language input using the TimeExpressionParser class; serialized * variable stores using php serialize(), automatic management of hierarchies, etc.) * Each table in your database should have a class that extends BaseModel. */ class BaseModel extends BaseObject { # -------------------------------------------------------------------------------- # --- Properties # -------------------------------------------------------------------------------- /** * representation of the access mode of the current instance. * 0 (ACCESS_READ) means read-only, * 1 (ACCESS_WRITE) characterizes a BaseModel instance that is able to write to the database. * * @access private */ private $ACCESS_MODE; /** * local Db object for database access * * @access private */ private $o_db; /** * debug mode state * * @access private */ var $debug = 0; /** * @access private */ var $_FIELD_VALUES; /** * @access protected */ protected $_FIELD_VALUE_CHANGED; /** * @access private */ var $_FIELD_VALUES_OLD; /** * @access private */ private $_FILES; /** * @access private */ private $_SET_FILES; /** * @access private */ private $_FILES_CLEAR; /** * object-oriented access to media volume information * * @access private */ private $_MEDIA_VOLUMES; /** * object-oriented access to file volume information * * @access private */ private $_FILE_VOLUMES; /** * if true, DATETIME fields take Unix date/times, * not parseable date/time expressions * * @access private */ private $DIRECT_DATETIMES = 0; /** * local Configuration object representation * * @access protected */ protected $_CONFIG; /** * local Datamodel object representation * * @access protected */ protected $_DATAMODEL = null; /** * contains current Transaction object * * @access protected */ protected $_TRANSACTION = null; /** * The current locale. Used to determine which set of localized error messages to use. Default is US English ("en_us") * * @access private */ var $ops_locale = "en_us"; # /** * prepared change log statement (primary log entry) * * @access private */ private $opqs_change_log; /** * prepared change log statement (log subject entries) * * @access private */ private $opqs_change_log_subjects; /** * prepared statement to get change log * * @access private */ private $opqs_get_change_log; /** * prepared statement to get change log * * @access private */ private $opqs_get_change_log_subjects; # /** * array containing parsed version string from * * @access private */ private $opa_php_version; # # -------------------------------------------------------------------------------- # --- Error handling properties # -------------------------------------------------------------------------------- /** * Array of error objects * * @access public */ public $errors; /** * If true, on error error message is printed and execution halted * * @access private */ private $error_output; /** * List of fields that had conflicts with existing data during last update() * (ie. someone else had already saved to this field while the user of this instance was working) * * @access private */ private $field_conflicts; /** * Single instance of search indexer used by all models */ static public $search_indexer; /** * Single instance of HTML Purifier used by all models */ static public $html_purifier; /** * If set, all field values passed through BaseModel::set() are run through HTML Purifier before being stored */ private $opb_purify_input = false; /** * Array of model definitions, keyed on table name */ static $s_ca_models_definitions; /** * Constructor * In general you should not call this constructor directly. Any table in your database * should be represented by an extension of this class. * * @param int $pn_id primary key identifier of the table row represented by this object * if omitted, an empty object is created which can be used to create a new row in the database. * @return BaseModel */ public function __construct($pn_id=null) { $vs_table_name = $this->tableName(); if (!$this->FIELDS =& BaseModel::$s_ca_models_definitions[$vs_table_name]['FIELDS']) { die("Field definitions not found for {$vs_table_name}"); } $this->NAME_SINGULAR =& BaseModel::$s_ca_models_definitions[$vs_table_name]['NAME_SINGULAR']; $this->NAME_PLURAL =& BaseModel::$s_ca_models_definitions[$vs_table_name]['NAME_PLURAL']; $this->errors = array(); $this->error_output = 0; # don't halt on error $this->field_conflicts = array(); $this->_CONFIG = Configuration::load(); $this->_DATAMODEL = Datamodel::load(); $this->_FILES_CLEAR = array(); $this->_SET_FILES = array(); $this->_MEDIA_VOLUMES = MediaVolumes::load(); $this->_FILE_VOLUMES = FileVolumes::load(); $this->_FIELD_VALUE_CHANGED = array(); if ($vs_locale = $this->_CONFIG->get("locale")) { $this->ops_locale = $vs_locale; } $this->opo_app_plugin_manager = new ApplicationPluginManager(); $this->setMode(ACCESS_READ); if ($pn_id) { $this->load($pn_id);} } /** * Get Db object * If a transaction is pending, the Db object representation is taken from the Transaction object, * if not, a new connection is established, stored in a local property and returned. * * @return Db */ public function getDb() { if ($this->inTransaction()) { $this->o_db = $this->getTransaction()->getDb(); } else { if (!$this->o_db) { $this->o_db = new Db(); $this->o_db->dieOnError(false); } } return $this->o_db; } /** * Convenience method to return application configuration object. This is the same object * you'd get if you instantiated a Configuration() object without any parameters * * @return Configuration */ public function getAppConfig() { return $this->_CONFIG; } /** * Convenience method to return application datamodel object. This is the same object * you'd get if you instantiated a Datamodel() object * * @return Configuration */ public function getAppDatamodel() { return $this->_DATAMODEL; } /** * Get character set from configuration file. Defaults to * UTF8 if configuration parameter "character_set" is * not found. * * @return string the character set */ public function getCharacterSet() { if (!($vs_charset = $this->_CONFIG->get("character_set"))) { $vs_charset = "UTF-8"; } return $vs_charset; } # -------------------------------------------------------------------------------- # --- Transactions # -------------------------------------------------------------------------------- /** * Sets up local transaction property and refreshes local db property to * reflect the db connection of that transaction. After setting it, you * can perform common actions. * * @see BaseModel::getTransaction() * @see BaseModel::inTransaction() * @see BaseModel::removeTransaction() * * @param Transaction $transaction * @return bool success state */ public function setTransaction(&$transaction) { if (is_object($transaction)) { $this->_TRANSACTION = $transaction; $this->getDb(); // refresh $o_db property to reflect db connection of transaction return true; } else { return false; } } /** * Get transaction property. * * @see BaseModel::setTransaction() * @see BaseModel::inTransaction() * @see BaseModel::removeTransaction() * * @return Transaction */ public function getTransaction() { return isset($this->_TRANSACTION) ? $this->_TRANSACTION : null; } /** * Is there a pending transaction? * * @return bool */ public function inTransaction() { if (isset($this->_TRANSACTION)) { return ($this->_TRANSACTION) ? true : false; } return false; } /** * Remove transaction property. * * @param bool $ps_commit If true, the transaction is committed, if false, the transaction is rollback. * Defaults to true. * @return bool success state */ public function removeTransaction($ps_commit=true) { if ($this->inTransaction()) { if ($ps_commit) { $this->_TRANSACTION->commit(); } else { $this->_TRANSACTION->rollback(); } unset($this->_TRANSACTION); return true; } else { return false; } } # -------------------------------------------------------------------------------- /** * Sets whether BaseModel::set() input is run through HTML purifier or not * * @param bool $pb_purify If true, all input passed via BaseModel::set() is run through HTML Purifier prior to being stored. If false, input is stored as-is. If null or omitted, no change is made to current setting * @return bool Returns current purification settings. If you simply want to get the current setting call BaseModel::purify without any parameters. */ public function purify($pb_purify=null) { if (!is_null($pb_purify)) { $this->opb_purify_input = (bool)$pb_purify; } return $this->opb_purify_input; } # -------------------------------------------------------------------------------- # Set/get values # -------------------------------------------------------------------------------- /** * Get all field values of the current row that is represented by this BaseModel object. * * @see BaseModel::getChangedFieldValuesArray() * @return array associative array: field name => field value */ public function getFieldValuesArray() { return $this->_FIELD_VALUES; } /** * Set alls field values of the current row that is represented by this BaseModel object * by passing an associative array as follows: field name => field value * * @param array $pa_values associative array: field name => field value * @return void */ public function setFieldValuesArray($pa_values) { $this->_FIELD_VALUES = $pa_values; } /** * Get an associative array of the field values that changed since instantiation of * this BaseModel object. * * @return array associative array: field name => field value */ public function getChangedFieldValuesArray() { $va_fieldnames = array_keys($this->_FIELD_VALUES); $va_changed_field_values_array = array(); foreach($va_fieldnames as $vs_fieldname) { if($this->changed($vs_fieldname)) { $va_changed_field_values_array[$vs_fieldname] = $this->_FIELD_VALUES[$vs_fieldname]; } } return $va_changed_field_values_array; } /** * What was the original value of a field? * * @param string $ps_field field name * @return mixed original field value */ public function getOriginalValue($ps_field) { return $this->_FIELD_VALUES_OLD[$ps_field]; } /** * Check if the content of a field has changed. * * @param string $ps_field field name * @return bool */ public function changed($ps_field) { return isset($this->_FIELD_VALUE_CHANGED[$ps_field]) ? $this->_FIELD_VALUE_CHANGED[$ps_field] : null; } /** * Force field to be considered changed * * @param string $ps_field field name * @return bool Always true */ public function setAsChanged($ps_field) { $this->_FIELD_VALUE_CHANGED[$ps_field] = true; return true; } /** * Returns value of primary key * * @param bool $vb_quoted Set to true if you want the method to return the value in quotes. Default is false. * @return mixed value of primary key */ public function getPrimaryKey ($vb_quoted=false) { if (!isset($this->_FIELD_VALUES[$this->PRIMARY_KEY])) return null; $vm_pk = $this->_FIELD_VALUES[$this->PRIMARY_KEY]; if ($vb_quoted) { $vm_pk = $this->quote($this->PRIMARY_KEY, $vm_pk); } return $vm_pk; } /** * Get a field value of the table row that is represented by this object. * * @param string $ps_field field name * @param array $pa_options options array; can be omitted. * It should be an associative array of boolean (except one of the options) flags. In case that some of the options are not set, they are treated as 'false'. * Possible options (keys) are: * -BINARY: return field value as is * -FILTER_HTML_SPECIAL_CHARS: convert all applicable chars to their html entities * -DONT_PROCESS_GLOSSARY_TAGS: ? * -CONVERT_HTML_BREAKS: similar to nl2br() * -convertLineBreaks: same as CONVERT_HTML_BREAKS * -GET_DIRECT_DATE: return raw date value from database if $ps_field adresses a date field, otherwise the value will be parsed using the TimeExpressionParser::getText() method * -GET_DIRECT_TIME: return raw time value from database if $ps_field adresses a time field, otherwise the value will be parsed using the TimeExpressionParser::getText() method * -TIMECODE_FORMAT: set return format for fields representing time ranges possible (string) values: COLON_DELIMITED, HOURS_MINUTES_SECONDS, RAW; data will be passed through floatval() by default * -QUOTE: set return value into quotes * -URL_ENCODE: value will be passed through urlencode() * -ESCAPE_FOR_XML: convert <, >, &, ' and " characters for XML use * -DONT_STRIP_SLASHES: if set to true, return value will not be passed through stripslashes() * -template: formatting string to use for returned value; ^<fieldname> placeholder is used to represent field value in template * -returnAsArray: if true, fields that can return multiple values [currently only <table_name>.children.<field>] will return values in an indexed array; default is false * -returnAllLocales: * -delimiter: if set, value is used as delimiter when fields that can return multiple fields are returned as strings; default is a single space * -convertCodesToDisplayText: if set, id values refering to foreign keys are returned as preferred label text in the current locale * -returnURL: if set then url is returned for media, otherwise an HTML tag for display is returned * -dateFormat: format to return created or lastModified dates in. Valid values are iso8601 or text */ public function get($ps_field, $pa_options=null) { if (!$ps_field) return null; if (!is_array($pa_options)) { $pa_options = array();} $vb_return_as_array = (isset($pa_options['returnAsArray'])) ? (bool)$pa_options['returnAsArray'] : false; $vb_return_all_locales = (isset($pa_options['returnAllLocales'])) ? (bool)$pa_options['returnAllLocales'] : false; $vs_delimiter = (isset($pa_options['delimiter'])) ? $pa_options['delimiter'] : ' '; if ($vb_return_all_locales && !$vb_return_as_array) { $vb_return_as_array = true; } $vn_row_id = $this->getPrimaryKey(); if ($vb_return_as_array && $vb_return_as_array) { $vn_locale_id = ($this->hasField('locale_id')) ? $this->get('locale_id') : null; } $va_tmp = explode('.', $ps_field); if (sizeof($va_tmp) > 1) { if ($va_tmp[0] === $this->tableName()) { // // Return created on or last modified // if (in_array($va_tmp[1], array('created', 'lastModified'))) { if ($vb_return_as_array) { return ($va_tmp[1] == 'lastModified') ? $this->getLastChangeTimestamp() : $this->getCreationTimestamp(); } else { $va_data = ($va_tmp[1] == 'lastModified') ? $this->getLastChangeTimestamp() : $this->getCreationTimestamp(); $vs_subfield = (isset($va_tmp[2]) && isset($va_data[$va_tmp[2]])) ? $va_tmp[2] : 'timestamp'; $vm_val = $va_data[$vs_subfield]; if ($vs_subfield == 'timestamp') { $o_tep = new TimeExpressionParser(); $o_tep->setUnixTimestamps($vm_val, $vm_val); $vm_val = $o_tep->getText($pa_options); } return $vm_val; } } // // Generalized get // switch(sizeof($va_tmp)) { case 2: // support <table_name>.<field_name> syntax $ps_field = $va_tmp[1]; break; default: // > 2 elements // media field? $va_field_info = $this->getFieldInfo($va_tmp[1]); if (($va_field_info['FIELD_TYPE'] === FT_MEDIA) && (!isset($pa_options['returnAsArray'])) && !$pa_options['returnAsArray']) { $o_media_settings = new MediaProcessingSettings($va_tmp[0], $va_tmp[1]); $va_versions = $o_media_settings->getMediaTypeVersions('*'); $vs_version = $va_tmp[2]; if (!isset($va_versions[$vs_version])) { $vs_version = array_shift(array_keys($va_versions)); } if (isset($pa_options['returnURL']) && $pa_options['returnURL']) { return $this->getMediaUrl($va_tmp[1], $vs_version); } else { return $this->getMediaTag($va_tmp[1], $vs_version); } } if (($va_tmp[1] == 'parent') && ($this->isHierarchical()) && ($vn_parent_id = $this->get($this->getProperty('HIERARCHY_PARENT_ID_FLD')))) { $t_instance = $this->getAppDatamodel()->getInstanceByTableNum($this->tableNum(), true); if (!$t_instance->load($vn_parent_id)) { return ($vb_return_as_array) ? array() : null; } else { unset($va_tmp[1]); $va_tmp = array_values($va_tmp); if ($vb_return_as_array) { if ($vb_return_all_locales) { return array( $vn_row_id => array( // this row_id $vn_locale_id => array( // base model fields aren't translate-able $t_instance->get(join('.', $va_tmp)) ) ) ); } else { return array( $vn_row_id => $t_instance->get(join('.', $va_tmp)) ); } } else { return $t_instance->get(join('.', $va_tmp)); } } } else { if (($va_tmp[1] == 'children') && ($this->isHierarchical())) { unset($va_tmp[1]); // remove 'children' from field path $va_tmp = array_values($va_tmp); $vs_childless_path = join('.', $va_tmp); $va_data = array(); $va_children_ids = $this->getHierarchyChildren(null, array('idsOnly' => true)); $t_instance = $this->getAppDatamodel()->getInstanceByTableNum($this->tableNum()); foreach($va_children_ids as $vn_child_id) { if ($t_instance->load($vn_child_id)) { if ($vb_return_as_array) { $va_data[$vn_child_id] = array_shift($t_instance->get($vs_childless_path, array_merge($pa_options, array('returnAsArray' => $vb_return_as_array, 'returnAllLocales' => $vb_return_all_locales)))); } else { $va_data[$vn_child_id] = $t_instance->get($vs_childless_path, array_merge($pa_options, array('returnAsArray' => false, 'returnAllLocales' => false))); } } } if ($vb_return_as_array) { return $va_data; } else { return join($vs_delimiter, $va_data); } } } break; } } else { // can't pull fields from other tables! return $vb_return_as_array ? array() : null; } } if (isset($pa_options["BINARY"]) && $pa_options["BINARY"]) { return $this->_FIELD_VALUES[$ps_field]; } if (array_key_exists($ps_field,$this->FIELDS)) { $ps_field_type = $this->getFieldInfo($ps_field,"FIELD_TYPE"); if ($this->getFieldInfo($ps_field, 'IS_LIFESPAN')) { $pa_options['isLifespan'] = true; } switch ($ps_field_type) { case (FT_BIT): $vs_prop = isset($this->_FIELD_VALUES[$ps_field]) ? $this->_FIELD_VALUES[$ps_field] : ""; if (isset($pa_options['convertCodesToDisplayText']) && $pa_options['convertCodesToDisplayText']) { $vs_prop = (bool)$vs_prop ? _t('yes') : _t('no'); } return $vs_prop; break; case (FT_TEXT): case (FT_NUMBER): case (FT_PASSWORD): $vs_prop = isset($this->_FIELD_VALUES[$ps_field]) ? $this->_FIELD_VALUES[$ps_field] : null; if (isset($pa_options["FILTER_HTML_SPECIAL_CHARS"]) && ($pa_options["FILTER_HTML_SPECIAL_CHARS"])) { $vs_prop = htmlentities(html_entity_decode($vs_prop)); } // // Convert foreign keys and choice list values to display text is needed // if (isset($pa_options['convertCodesToDisplayText']) && $pa_options['convertCodesToDisplayText'] && ($vs_list_code = $this->getFieldInfo($ps_field,"LIST_CODE"))) { $t_list = new ca_lists(); $vs_prop = $t_list->getItemFromListForDisplayByItemID($vs_list_code, $vs_prop); } else { if (isset($pa_options['convertCodesToDisplayText']) && $pa_options['convertCodesToDisplayText'] && ($vs_list_code = $this->getFieldInfo($ps_field,"LIST"))) { $t_list = new ca_lists(); if (!($vs_tmp = $t_list->getItemFromListForDisplayByItemValue($vs_list_code, $vs_prop))) { if ($vs_tmp = $this->getChoiceListValue($ps_field, $vs_prop)) { $vs_prop = $vs_tmp; } } else { $vs_prop = $vs_tmp; } } else { if (isset($pa_options['convertCodesToDisplayText']) && $pa_options['convertCodesToDisplayText'] && ($ps_field === 'locale_id') && ((int)$vs_prop > 0)) { $t_locale = new ca_locales($vs_prop); $vs_prop = $t_locale->getName(); } else { if (isset($pa_options['convertCodesToDisplayText']) && $pa_options['convertCodesToDisplayText'] && (is_array($va_list = $this->getFieldInfo($ps_field,"BOUNDS_CHOICE_LIST")))) { foreach($va_list as $vs_option => $vs_value) { if ($vs_value == $vs_prop) { $vs_prop = $vs_option; break; } } } } } } if ( (isset($pa_options["CONVERT_HTML_BREAKS"]) && ($pa_options["CONVERT_HTML_BREAKS"])) || (isset($pa_options["convertLineBreaks"]) && ($pa_options["convertLineBreaks"])) ) { $vs_prop = caConvertLineBreaks($vs_prop); } break; case (FT_DATETIME): case (FT_TIMESTAMP): case (FT_HISTORIC_DATETIME): case (FT_HISTORIC_DATE): case (FT_DATE): if (isset($pa_options["GET_DIRECT_DATE"]) && $pa_options["GET_DIRECT_DATE"]) { $vs_prop = $this->_FIELD_VALUES[$ps_field]; } else { $o_tep = new TimeExpressionParser(); $vn_timestamp = isset($this->_FIELD_VALUES[$ps_field]) ? $this->_FIELD_VALUES[$ps_field] : 0; if (($ps_field_type == FT_HISTORIC_DATETIME) || ($ps_field_type == FT_HISTORIC_DATE)) { $o_tep->setHistoricTimestamps($vn_timestamp, $vn_timestamp); } else { $o_tep->setUnixTimestamps($vn_timestamp, $vn_timestamp); } if (($ps_field_type == FT_DATE) || ($ps_field_type == FT_HISTORIC_DATE)) { $vs_prop = $o_tep->getText(array_merge(array('timeOmit' => true), $pa_options)); } else { $vs_prop = $o_tep->getText($pa_options); } } break; case (FT_TIME): if (isset($pa_options["GET_DIRECT_TIME"]) && $pa_options["GET_DIRECT_TIME"]) { $vs_prop = $this->_FIELD_VALUES[$ps_field]; } else { $o_tep = new TimeExpressionParser(); $vn_timestamp = isset($this->_FIELD_VALUES[$ps_field]) ? $this->_FIELD_VALUES[$ps_field] : 0; $o_tep->setTimes($vn_timestamp, $vn_timestamp); $vs_prop = $o_tep->getText($pa_options); } break; case (FT_DATERANGE): case (FT_HISTORIC_DATERANGE): $vs_start_field_name = $this->getFieldInfo($ps_field,"START"); $vs_end_field_name = $this->getFieldInfo($ps_field,"END"); $vn_start_date = isset($this->_FIELD_VALUES[$vs_start_field_name]) ? $this->_FIELD_VALUES[$vs_start_field_name] : null; $vn_end_date = isset($this->_FIELD_VALUES[$vs_end_field_name]) ? $this->_FIELD_VALUES[$vs_end_field_name] : null; if (!isset($pa_options["GET_DIRECT_DATE"]) || !$pa_options["GET_DIRECT_DATE"]) { $o_tep = new TimeExpressionParser(); if ($ps_field_type == FT_HISTORIC_DATERANGE) { $o_tep->setHistoricTimestamps($vn_start_date, $vn_end_date); } else { $o_tep->setUnixTimestamps($vn_start_date, $vn_end_date); } $vs_prop = $o_tep->getText($pa_options); } else { $vs_prop = array($vn_start_date, $vn_end_date); } break; case (FT_TIMERANGE): $vs_start_field_name = $this->getFieldInfo($ps_field,"START"); $vs_end_field_name = $this->getFieldInfo($ps_field,"END"); $vn_start_date = isset($this->_FIELD_VALUES[$vs_start_field_name]) ? $this->_FIELD_VALUES[$vs_start_field_name] : null; $vn_end_date = isset($this->_FIELD_VALUES[$vs_end_field_name]) ? $this->_FIELD_VALUES[$vs_end_field_name] : null; if (!isset($pa_options["GET_DIRECT_TIME"]) || !$pa_options["GET_DIRECT_TIME"]) { $o_tep = new TimeExpressionParser(); $o_tep->setTimes($vn_start_date, $vn_end_date); $vs_prop = $o_tep->getText($pa_options); } else { $vs_prop = array($vn_start_date, $vn_end_date); } break; case (FT_TIMECODE): $o_tp = new TimecodeParser(); $o_tp->setParsedValueInSeconds($this->_FIELD_VALUES[$ps_field]); $vs_prop = $o_tp->getText(isset($pa_options["TIMECODE_FORMAT"]) ? $pa_options["TIMECODE_FORMAT"] : null); break; case (FT_MEDIA): case (FT_FILE): if (isset($pa_options["USE_MEDIA_FIELD_VALUES"]) && $pa_options["USE_MEDIA_FIELD_VALUES"]) { $vs_prop = $this->_FIELD_VALUES[$ps_field]; } else { $vs_prop = (isset($this->_SET_FILES[$ps_field]['tmp_name']) && $this->_SET_FILES[$ps_field]['tmp_name']) ? $this->_SET_FILES[$ps_field]['tmp_name'] : $this->_FIELD_VALUES[$ps_field]; } break; case (FT_VARS): $vs_prop = (isset($this->_FIELD_VALUES[$ps_field]) && $this->_FIELD_VALUES[$ps_field]) ? $this->_FIELD_VALUES[$ps_field] : null; break; } if (isset($pa_options["QUOTE"]) && $pa_options["QUOTE"]) $vs_prop = $this->quote($ps_field, $vs_prop); } else { $this->postError(710,_t("'%1' does not exist in this object", $ps_field),"BaseModel->get()"); return $vb_return_as_array ? array() : null; } if (isset($pa_options["URL_ENCODE"]) && $pa_options["URL_ENCODE"]) { $vs_prop = urlEncode($vs_prop); } if (isset($pa_options["ESCAPE_FOR_XML"]) && $pa_options["ESCAPE_FOR_XML"]) { $vs_prop = escapeForXML($vs_prop); } if (!(isset($pa_options["DONT_STRIP_SLASHES"]) && $pa_options["DONT_STRIP_SLASHES"])) { if (is_string($vs_prop)) { $vs_prop = stripSlashes($vs_prop); } } if ((isset($pa_options["template"]) && $pa_options["template"])) { $vs_template_with_substitution = str_replace("^".$ps_field, $vs_prop, $pa_options["template"]); $vs_prop = str_replace("^".$this->tableName().".".$ps_field, $vs_prop, $vs_template_with_substitution); } if ($vb_return_as_array) { if ($vb_return_all_locales) { return array( $vn_row_id => array( // this row_id $vn_locale_id => array($vs_prop) ) ); } else { return array( $vn_row_id => $vs_prop ); } } else { return $vs_prop; } } /** * Set field value(s) for the table row represented by this object * * @param string|array string $pa_fields representation of a field name * or array of string representations of field names * @param mixed $pm_value value to set the given field(s) to * @param array $pa_options associative array of options * possible options (keys): * when dealing with date/time fields: * - SET_DIRECT_DATE * - SET_DIRECT_TIME * - SET_DIRECT_TIMES * * for media/files fields: * - original_filename : (note that it is lower case) optional parameter which enables you to pass the original filename of a file, in addition to the representation in the temporary, global _FILES array; * * for text fields: * - purify : if set then text input is run through HTML Purifier before being set */ public function set($pa_fields, $pm_value="", $pa_options=null) { $this->errors = array(); if (!is_array($pa_fields)) { $pa_fields = array($pa_fields => $pm_value); } foreach($pa_fields as $vs_field => $vm_value) { if (array_key_exists($vs_field, $this->FIELDS)) { $pa_fields_type = $this->getFieldInfo($vs_field,"FIELD_TYPE"); $pb_need_reload = false; if (!$this->verifyFieldValue($vs_field, $vm_value, $pb_need_reload)) { return false; } if ($pb_need_reload) { return true; } // was set to default if ($vs_field == $this->primaryKey()) { $vm_value = preg_replace("/[\"']/", "", $vm_value); } // what markup is supported for text fields? $vs_markup_type = $this->getFieldInfo($vs_field, "MARKUP_TYPE"); // if markup is non-HTML then strip out HTML special chars for safety if (!($vs_markup_type == __CA_MT_HTML__)) { $vm_value = htmlspecialchars($vm_value, ENT_QUOTES, 'UTF-8'); } $vs_cur_value = isset($this->_FIELD_VALUES[$vs_field]) ? $this->_FIELD_VALUES[$vs_field] : null; switch ($pa_fields_type) { case (FT_NUMBER): if ($vs_cur_value != $vm_value) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; } if (($vm_value !== "") || ($this->getFieldInfo($vs_field, "IS_NULL") && ($vm_value == ""))) { if ($vm_value) { $vm_orig_value = $vm_value; $vm_value = preg_replace("/[^\d-.]+/", "", $vm_value); # strip non-numeric characters if (!preg_match("/^[\-]{0,1}[\d.]+$/", $vm_value)) { $this->postError(1100,_t("'%1' for %2 is not numeric", $vm_orig_value, $vs_field),"BaseModel->set()"); return ""; } } $this->_FIELD_VALUES[$vs_field] = $vm_value; } break; case (FT_BIT): if ($vs_cur_value != $vm_value) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; } $this->_FIELD_VALUES[$vs_field] = ($vm_value ? 1 : 0); break; case (FT_DATETIME): case (FT_HISTORIC_DATETIME): case (FT_DATE): case (FT_HISTORIC_DATE): if (($this->DIRECT_DATETIMES) || ($pa_options["SET_DIRECT_DATE"])) { $this->_FIELD_VALUES[$vs_field] = $vm_value; } else { if (!$vm_value && $this->FIELDS[$vs_field]["IS_NULL"]) { if ($vs_cur_value) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; } $this->_FIELD_VALUES[$vs_field] = null; } else { $o_tep= new TimeExpressionParser(); if (($pa_fields_type == FT_DATE) || ($pa_fields_type == FT_HISTORIC_DATE)) { $va_timestamps = $o_tep->parseDate($vm_value); } else { $va_timestamps = $o_tep->parseDatetime($vm_value); } if (!$va_timestamps) { $this->postError(1805, $o_tep->getParseErrorMessage(), 'BaseModel->set()'); return false; } if (($pa_fields_type == FT_HISTORIC_DATETIME) || ($pa_fields_type == FT_HISTORIC_DATE)) { if($vs_cur_value != $va_timestamps["start"]) { $this->_FIELD_VALUES[$vs_field] = $va_timestamps["start"]; $this->_FIELD_VALUE_CHANGED[$vs_field] = true; } } else { $va_timestamps = $o_tep->getUnixTimestamps(); if ($va_timestamps[0] == -1) { $this->postError(1830, $o_tep->getParseErrorMessage(), 'BaseModel->set()'); return false; } if ($vs_cur_value != $va_timestamps["start"]) { $this->_FIELD_VALUES[$vs_field] = $va_timestamps["start"]; $this->_FIELD_VALUE_CHANGED[$vs_field] = true; } } } } break; case (FT_TIME): if (($this->DIRECT_TIMES) || ($pa_options["SET_DIRECT_TIME"])) { $this->_FIELD_VALUES[$vs_field] = $vm_value; } else { if (!$vm_value && $this->FIELDS[$vs_field]["IS_NULL"]) { if ($vs_cur_value) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; } $this->_FIELD_VALUES[$vs_field] = null; } else { $o_tep= new TimeExpressionParser(); if (!$o_tep->parseTime($vm_value)) { $this->postError(1805, $o_tep->getParseErrorMessage(), 'BaseModel->set()'); return false; } $va_times = $o_tep->getTimes(); if ($vs_cur_value != $va_times['start']) { $this->_FIELD_VALUES[$vs_field] = $va_times['start']; $this->_FIELD_VALUE_CHANGED[$vs_field] = true; } } } break; case (FT_TIMESTAMP): # can't set timestamp break; case (FT_DATERANGE): case (FT_HISTORIC_DATERANGE): $vs_start_field_name = $this->getFieldInfo($vs_field,"START"); $vs_end_field_name = $this->getFieldInfo($vs_field,"END"); $vn_start_date = isset($this->_FIELD_VALUES[$vs_start_field_name]) ? $this->_FIELD_VALUES[$vs_start_field_name] : null; $vn_end_date = isset($this->_FIELD_VALUES[$vs_end_field_name]) ? $this->_FIELD_VALUES[$vs_end_field_name] : null; if (($this->DIRECT_DATETIMES) || ($pa_options["SET_DIRECT_DATE"])) { if (is_array($vm_value) && (sizeof($vm_value) == 2) && ($vm_value[0] <= $vm_value[1])) { if ($vn_start_date != $vm_value[0]) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; $this->_FIELD_VALUES[$vs_start_field_name] = $vm_value[0]; } if ($vn_end_date != $vm_value[1]) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; $this->_FIELD_VALUES[$vs_end_field_name] = $vm_value[1]; } } else { $this->postError(1100,_t("Invalid direct date values"),"BaseModel->set()"); } } else { if (!$vm_value && $this->FIELDS[$vs_field]["IS_NULL"]) { if ($vn_start_date || $vn_end_date) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; } $this->_FIELD_VALUES[$vs_start_field_name] = null; $this->_FIELD_VALUES[$vs_end_field_name] = null; } else { $o_tep = new TimeExpressionParser(); if (!$o_tep->parseDatetime($vm_value)) { $this->postError(1805, $o_tep->getParseErrorMessage(), 'BaseModel->set()'); return false; } if ($pa_fields_type == FT_HISTORIC_DATERANGE) { $va_timestamps = $o_tep->getHistoricTimestamps(); } else { $va_timestamps = $o_tep->getUnixTimestamps(); if ($va_timestamps[0] == -1) { $this->postError(1830, $o_tep->getParseErrorMessage(), 'BaseModel->set()'); return false; } } if ($vn_start_date != $va_timestamps["start"]) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; $this->_FIELD_VALUES[$vs_start_field_name] = $va_timestamps["start"]; } if ($vn_end_date != $va_timestamps["end"]) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; $this->_FIELD_VALUES[$vs_end_field_name] = $va_timestamps["end"]; } } } break; case (FT_TIMERANGE): $vs_start_field_name = $this->getFieldInfo($vs_field,"START"); $vs_end_field_name = $this->getFieldInfo($vs_field,"END"); if (($this->DIRECT_TIMES) || ($pa_options["SET_DIRECT_TIMES"])) { if (is_array($vm_value) && (sizeof($vm_value) == 2) && ($vm_value[0] <= $vm_value[1])) { if ($this->_FIELD_VALUES[$vs_start_field_name] != $vm_value[0]) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; $this->_FIELD_VALUES[$vs_start_field_name] = $vm_value[0]; } if ($this->_FIELD_VALUES[$vs_end_field_name] != $vm_value[1]) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; $this->_FIELD_VALUES[$vs_end_field_name] = $vm_value[1]; } } else { $this->postError(1100,_t("Invalid direct time values"),"BaseModel->set()"); } } else { if (!$vm_value && $this->FIELDS[$vs_field]["IS_NULL"]) { if ($this->_FIELD_VALUES[$vs_start_field_name] || $this->_FIELD_VALUES[$vs_end_field_name]) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; } $this->_FIELD_VALUES[$vs_start_field_name] = null; $this->_FIELD_VALUES[$vs_end_field_name] = null; } else { $o_tep = new TimeExpressionParser(); if (!$o_tep->parseTime($vm_value)) { $this->postError(1805, $o_tep->getParseErrorMessage(), 'BaseModel->set()'); return false; } $va_timestamps = $o_tep->getTimes(); if ($this->_FIELD_VALUES[$vs_start_field_name] != $va_timestamps["start"]) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; $this->_FIELD_VALUES[$vs_start_field_name] = $va_timestamps["start"]; } if ($this->_FIELD_VALUES[$vs_end_field_name] != $va_timestamps["end"]) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; $this->_FIELD_VALUES[$vs_end_field_name] = $va_timestamps["end"]; } } } break; case (FT_TIMECODE): $o_tp = new TimecodeParser(); if ($o_tp->parse($vm_value)) { if ($o_tp->getParsedValueInSeconds() != $vs_cur_value) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; $this->_FIELD_VALUES[$vs_field] = $o_tp->getParsedValueInSeconds(); } } break; case (FT_TEXT): if (is_string($vm_value)) { $vm_value = stripSlashes($vm_value); } if ((isset($pa_options['purify']) && ($pa_options['purify'])) || ((bool)$this->opb_purify_input) || ($this->getFieldInfo($vs_field, "PURIFY")) || ((bool)$this->getAppConfig()->get('useHTMLPurifier'))) { if (!BaseModel::$html_purifier) { BaseModel::$html_purifier = new HTMLPurifier(); } $vm_value = BaseModel::$html_purifier->purify((string)$vm_value); } if ($this->getFieldInfo($vs_field, "DISPLAY_TYPE") == DT_LIST_MULTIPLE) { if (is_array($vm_value)) { if (!($vs_list_multiple_delimiter = $this->getFieldInfo($vs_field, 'LIST_MULTIPLE_DELIMITER'))) { $vs_list_multiple_delimiter = ';'; } $vs_string_value = join($vs_list_multiple_delimiter, $vm_value); $vs_string_value = str_replace("\0", '', $vs_string_value); if ($vs_cur_value != $vs_string_value) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; } $this->_FIELD_VALUES[$vs_field] = $vs_string_value; } } else { $vm_value = str_replace("\0", '', $vm_value); if ($this->getFieldInfo($vs_field, "ENTITY_ENCODE_INPUT")) { $vs_value_entity_encoded = htmlentities(html_entity_decode($vm_value)); if ($vs_cur_value != $vs_value_entity_encoded) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; } $this->_FIELD_VALUES[$vs_field] = $vs_value_entity_encoded; } else { if ($this->getFieldInfo($vs_field, "URL_ENCODE_INPUT")) { $vs_value_url_encoded = urlencode($vm_value); if ($vs_cur_value != $vs_value_url_encoded) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; } $this->_FIELD_VALUES[$vs_field] = $vs_value_url_encoded; } else { if ($vs_cur_value != $vm_value) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; } $this->_FIELD_VALUES[$vs_field] = $vm_value; } } } break; case (FT_PASSWORD): if (!$vm_value) { // store blank passwords as blank, not MD5 of blank $this->_FIELD_VALUES[$vs_field] = $vs_crypt_pw = ""; } else { if ($this->_CONFIG->get("use_old_style_passwords")) { $vs_crypt_pw = crypt($vm_value,substr($vm_value,0,2)); } else { $vs_crypt_pw = md5($vm_value); } if (($vs_cur_value != $vm_value) && ($vs_cur_value != $vs_crypt_pw)) { $this->_FIELD_VALUES[$vs_field] = $vs_crypt_pw; } if ($vs_cur_value != $vs_crypt_pw) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; } } break; case (FT_VARS): if (md5(print_r($vs_cur_value, true)) != md5(print_r($vm_value, true))) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; } $this->_FIELD_VALUES[$vs_field] = $vm_value; break; case (FT_MEDIA): case (FT_FILE): $vb_allow_fetching_of_urls = (bool)$this->_CONFIG->get('allow_fetching_of_media_from_remote_urls'); # if there's a tmp_name is the global _FILES array # then we'll process it in insert()/update()... $this->_SET_FILES[$vs_field]['options'] = $pa_options; if (caGetOSFamily() == OS_WIN32) { // fix for paths using backslashes on Windows failing in processing $vm_value = str_replace('\\', '/', $vm_value); } $va_matches = null; if (is_string($vm_value) && (file_exists($vm_value) || ($vb_allow_fetching_of_urls && isURL($vm_value)))) { $this->_SET_FILES[$vs_field]['original_filename'] = $pa_options["original_filename"]; $this->_SET_FILES[$vs_field]['tmp_name'] = $vm_value; $this->_FIELD_VALUE_CHANGED[$vs_field] = true; } else { # only return error when file name is not 'none' # 'none' is PHP's stupid way of telling you there # isn't a file... if (($vm_value != "none") && ($vm_value)) { //$this->postError(1500,_t("%1 does not exist", $vm_value),"BaseModel->set()"); } return false; } break; default: die("Invalid field type in BaseModel->set()"); break; } } else { $this->postError(710,_t("%1' does not exist in this object", $vs_field),"BaseModel->set()"); return false; } } return true; } # ------------------------------------------------------------------ /** * */ public function getValuesForExport($pa_options=null) { $va_fields = $this->getFields(); $va_data = array(); $t_list = new ca_lists(); // get field values foreach($va_fields as $vs_field) { $vs_value = $this->get($this->tableName().'.'.$vs_field); // Convert list item_id's to idnos for export if ($vs_list_code = $this->getFieldInfo($vs_field, 'LIST_CODE')) { $va_item = $t_list->getItemFromListByItemID($vs_list_code, $vs_value); $vs_value = $va_item['idno']; } $va_data[$vs_field] = $vs_value; } return $va_data; } # -------------------------------------------------------------------------------- # BaseModel info # -------------------------------------------------------------------------------- /** * Returns an array containing the field names of the table. * * @return array field names */ public function getFields() { return array_keys($this->FIELDS); } /** * Returns an array containing the field names of the table as keys and their info as values. * * @return array field names */ public function getFieldsArray() { return $this->FIELDS; } /** * Returns name of primary key * * @return string the primary key of the table */ public function primaryKey() { return $this->PRIMARY_KEY; } /** * Returns name of the table * * @return string the name of the table */ public function tableName() { return $this->TABLE; } /** * Returns number of the table as defined in datamodel.conf configuration file * * @return int table number */ public function tableNum() { return $this->_DATAMODEL->getTableNum($this->TABLE); } /** * Returns number of the given field. Field numbering is defined implicitly by the order. * * @param string $ps_field field name * @return int field number */ public function fieldNum($ps_field) { return $this->_DATAMODEL->getFieldNum($this->TABLE, $ps_field); } /** * Returns name of the given field number. * * @param number $pn_num field number * @return string field name */ public function fieldName($pn_num) { $va_fields = $this->getFields(); return isset($va_fields[$pn_num]) ? $va_fields[$pn_num] : null; } /** * Returns name field used for arbitrary ordering of records (returns "" if none defined) * * @return string field name, "" if none defined */ public function rankField() { return $this->RANK; } /** * Returns table property * * @return mixed the property */ public function getProperty($property) { if (isset($this->{$property})) { return $this->{$property}; } return null; } /** * Returns a string with the values taken from fields which are defined in global property LIST_FIELDS * taking into account the global property LIST_DELIMITER. Each extension of BaseModel can define those properties. * * @return string */ public function getListFieldText() { if (is_array($va_list_fields = $this->getProperty('LIST_FIELDS'))) { $vs_delimiter = $this->getProperty('LIST_DELIMITER'); if ($vs_delimiter == null) { $vs_delimiter = ' '; } $va_tmp = array(); foreach($va_list_fields as $vs_field) { $va_tmp[] = $this->get($vs_field); } return join($vs_delimiter, $va_tmp); } return ''; } # -------------------------------------------------------------------------------- # Access mode # -------------------------------------------------------------------------------- /** * Returns the current access mode. * * @param bool $pb_return_name If set to true, return string representations of the modes * (i.e. 'read' or 'write'). If set to false (it is by default), returns ACCESS_READ or ACCESS_WRITE. * * @return int|string access mode representation */ public function getMode($pb_return_name=false) { if ($pb_return_name) { switch($this->ACCESS_MODE) { case ACCESS_READ: return 'read'; break; case ACCESS_WRITE: return 'write'; break; default: return '???'; break; } } return $this->ACCESS_MODE; } /** * Set current access mode. * * @param int $pn_mode access mode representation, either ACCESS_READ or ACCESS_WRITE * @return bool either returns the access mode or false on error */ public function setMode($pn_mode) { if (in_array($pn_mode, array(ACCESS_READ, ACCESS_WRITE))) { return $this->ACCESS_MODE = $pn_mode; } $this->postError(700,_t("Mode:%1 is not supported by this object", $pn_mode),"BaseModel->setMode()"); return false; } # -------------------------------------------------------------------------------- # --- Content methods (just your standard Create, Return, Update, Delete methods) # -------------------------------------------------------------------------------- /** * Generic method to load content properties of object with database fields. * After dealing with one row in the database using an extension of BaseModel * you can use this method to make the same object represent another row, instead * of destructing the old and constructing a new one. * * @param mixed $pm_id primary key value of the record to load (assuming we have no composed primary key) * @return bool success state */ public function load ($pm_id=null) { $this->clear(); if ($pm_id == null) { //$this->postError(750,_t("Can't load record; key is blank"), "BaseModel->load()"); return false; } $o_db = $this->getDb(); if (!is_array($pm_id)) { if ($this->_getFieldTypeType($this->primaryKey()) == 1) { $pm_id = $this->quote($pm_id); } else { $pm_id = intval($pm_id); } $vs_sql = "SELECT * FROM ".$this->tableName()." WHERE ".$this->primaryKey()." = ".$pm_id; } else { $va_sql_wheres = array(); foreach ($pm_id as $vs_field => $vm_value) { # support case where fieldname is in format table.fieldname if (preg_match("/([\w_]+)\.([\w_]+)/", $vs_field, $va_matches)) { if ($va_matches[1] != $this->tableName()) { if ($this->_DATAMODEL->tableExists($va_matches[1])) { $this->postError(715,_t("BaseModel '%1' cannot be accessed with this class", $matches[1]), "BaseModel->load()"); return false; } else { $this->postError(715, _t("BaseModel '%1' does not exist", $matches[1]), "BaseModel->load()"); return false; } } $vs_field = $matches[2]; # get field name alone } if (!$this->hasField($vs_field)) { $this->postError(716,_t("Field '%1' does not exist", $vs_field), "BaseModel->load()"); return false; } if ($this->_getFieldTypeType($vs_field) == 0) { if (!is_numeric($vm_value) && !is_null($vm_value)) { $vm_value = intval($vm_value); } } else { $vm_value = $this->quote($vs_field, is_null($vm_value) ? '' : $vm_value); } if (is_null($vm_value)) { $va_sql_wheres[] = "($vs_field IS NULL)"; } else { if ($vm_value === '') { continue; } $va_sql_wheres[] = "($vs_field = $vm_value)"; } } $vs_sql = "SELECT * FROM ".$this->tableName()." WHERE ".join(" AND ", $va_sql_wheres); } $qr_res = $o_db->query($vs_sql); if ($o_db->numErrors()) { $this->postError(250, _t('Basemodel::load SQL had an error: %1; SQL was %2', join("; ", $o_db->getErrors()), $vs_sql), 'BaseModel->load'); return false; } if ($qr_res->nextRow()) { foreach($this->FIELDS as $vs_field => $va_attr) { $vs_cur_value = isset($this->_FIELD_VALUES[$vs_field]) ? $this->_FIELD_VALUES[$vs_field] : null; $va_row =& $qr_res->getRow(); switch($va_attr["FIELD_TYPE"]) { case FT_DATERANGE: case FT_HISTORIC_DATERANGE: case FT_TIMERANGE: $vs_start_field_name = $va_attr["START"]; $vs_end_field_name = $va_attr["END"]; $this->_FIELD_VALUES[$vs_start_field_name] = $va_row[$vs_start_field_name]; $this->_FIELD_VALUES[$vs_end_field_name] = $va_row[$vs_end_field_name]; break; case FT_TIMESTAMP: $this->_FIELD_VALUES[$vs_field] = $va_row[$vs_field]; break; case FT_VARS: case FT_FILE: case FT_MEDIA: if (!$vs_cur_value) { $this->_FIELD_VALUES[$vs_field] = caUnserializeForDatabase($va_row[$vs_field]); } break; default: $this->_FIELD_VALUES[$vs_field] = $va_row[$vs_field]; break; } } $this->_FIELD_VALUES_OLD = $this->_FIELD_VALUES; $this->_FILES_CLEAR = array(); return true; } else { if (!is_array($pm_id)) { $this->postError(750,_t("Invalid %1 '%2'", $this->primaryKey(), $pm_id), "BaseModel->load()"); } else { $va_field_list = array(); foreach ($pm_id as $vs_field => $vm_value) { $va_field_list[] = "$vs_field => $vm_value"; } $this->postError(750,_t("No record with %1", join(", ", $va_field_list)), "BaseModel->load()"); } return false; } } /** * */ private function _calcHierarchicalIndexing($pa_parent_info) { $vs_hier_left_fld = $this->getProperty('HIERARCHY_LEFT_INDEX_FLD'); $vs_hier_right_fld = $this->getProperty('HIERARCHY_RIGHT_INDEX_FLD'); $vs_hier_id_fld = $this->getProperty('HIERARCHY_ID_FLD'); $vs_parent_fld = $this->getProperty('HIERARCHY_PARENT_ID_FLD'); $o_db = $this->getDb(); $qr_up = $o_db->query(" SELECT MAX({$vs_hier_right_fld}) maxChildRight FROM ".$this->tableName()." WHERE ({$vs_hier_left_fld} > ?) AND ({$vs_hier_right_fld} < ?) AND (".$this->primaryKey()." <> ?)". ($vs_hier_id_fld ? " AND ({$vs_hier_id_fld} = ".intval($pa_parent_info[$vs_hier_id_fld]).")" : '')." ", $pa_parent_info[$vs_hier_left_fld], $pa_parent_info[$vs_hier_right_fld], $pa_parent_info[$this->primaryKey()]); if ($qr_up->nextRow()) { if (!($vn_gap_start = $qr_up->get('maxChildRight'))) { $vn_gap_start = $pa_parent_info[$vs_hier_left_fld]; } $vn_gap_end = $pa_parent_info[$vs_hier_right_fld]; $vn_gap_size = ($vn_gap_end - $vn_gap_start); if ($vn_gap_size < 0.00001) { // rebuild hierarchical index if the current gap is not large enough to fit current record $this->rebuildHierarchicalIndex($this->get($vs_hier_id_fld)); $pa_parent_info = $this->_getHierarchyParent($pa_parent_info[$this->primaryKey()]); return $this->_calcHierarchicalIndexing($pa_parent_info); } if (($vn_scale = strlen(floor($vn_gap_size/10000))) < 1) { $vn_scale = 1; } $vn_interval_start = $vn_gap_start + ($vn_gap_size/(pow(10, $vn_scale))); $vn_interval_end = $vn_interval_start + ($vn_gap_size/(pow(10, $vn_scale))); //print "--------------------------\n"; //print "GAP START={$vn_gap_start} END={$vn_gap_end} SIZE={$vn_gap_size} SCALE={$vn_scale} INC=".($vn_gap_size/(pow(10, $vn_scale)))."\n"; //print "INT START={$vn_interval_start} INT END={$vn_interval_end}\n"; //print "--------------------------\n"; return array('left' => $vn_interval_start, 'right' => $vn_interval_end); } return null; } /** * */ private function _getHierarchyParent($pn_parent_id) { $o_db = $this->getDb(); $qr_get_parent = $o_db->query(" SELECT * FROM ".$this->tableName()." WHERE ".$this->primaryKey()." = ? ", intval($pn_parent_id)); if($qr_get_parent->nextRow()) { return $qr_get_parent->getRow(); } return null; } /** * Internal-use-only function for getting child record ids in a hierarchy. Unlike the public getHierarchyChildren() method * which uses nested set hierarchical indexing to fetch all children in a single pass (and also can return more than just the id's * of the children), _getHierarchyChildren() recursively traverses the hierarchy using parent_id field values. This makes it useful for * getting children in situations when the hierarchical indexing may not be valid, such as when moving items between hierarchies. * * @access private * @param array $pa_ids List of ids to get children for * @return array ids of all children of specified ids. List includes the original specified ids. */ private function _getHierarchyChildren($pa_ids) { if(!is_array($pa_ids)) { return null; } if (!sizeof($pa_ids)) { return null; } if (!($vs_parent_id_fld = $this->getProperty('HIERARCHY_PARENT_ID_FLD'))) { return null; } foreach($pa_ids as $vn_i => $vn_v) { $pa_ids[$vn_i] = (int)$vn_v; } $o_db = $this->getDb(); $qr_get_children = $o_db->query(" SELECT ".$this->primaryKey()." FROM ".$this->tableName()." WHERE {$vs_parent_id_fld} IN (?) ", array($pa_ids)); $va_child_ids = $qr_get_children->getAllFieldValues($this->primaryKey()); if (($va_child_ids && is_array($va_child_ids) && sizeof($va_child_ids) > 0)) { $va_child_ids = array_merge($va_child_ids, $this->_getHierarchyChildren($va_child_ids)); } if (!is_array($va_child_ids)) { $va_child_ids = array(); } $va_child_ids = array_merge($pa_ids, $va_child_ids); return array_unique($va_child_ids, SORT_STRING); } /** * Use this method to insert new record using supplied values * (assuming that you've constructed your BaseModel object as empty record) * @param $pa_options array optional associative array of options. Supported options include: * dont_do_search_indexing = if set to true then no search indexing on the inserted record is performed * @return int primary key of the new record, false on error */ public function insert ($pa_options=null) { if (!is_array($pa_options)) { $pa_options = array(); } $vb_we_set_transaction = false; $this->clearErrors(); if ($this->getMode() == ACCESS_WRITE) { if (!$this->inTransaction()) { $this->setTransaction(new Transaction($this->getDb())); $vb_we_set_transaction = true; } $o_db = $this->getDb(); $vs_fields = ""; $vs_values = ""; $va_media_fields = array(); $va_file_fields = array(); // // Set any auto-set hierarchical fields (eg. HIERARCHY_LEFT_INDEX_FLD and HIERARCHY_RIGHT_INDEX_FLD indexing for all and HIERARCHY_ID_FLD for ad-hoc hierarchies) here // $vn_hier_left_index_value = $vn_hier_right_index_value = 0; if ($vb_is_hierarchical = $this->isHierarchical()) { $vn_parent_id = $this->get($this->getProperty('HIERARCHY_PARENT_ID_FLD')); $va_parent_info = $this->_getHierarchyParent($vn_parent_id); switch($this->getHierarchyType()) { case __CA_HIER_TYPE_SIMPLE_MONO__: // you only need to set parent_id for this type of hierarchy if (!$vn_parent_id) { if ($vn_parent_id = $this->getHierarchyRootID(null)) { $this->set($this->getProperty('HIERARCHY_PARENT_ID_FLD'), $vn_parent_id); $va_parent_info = $this->_getHierarchyParent($vn_parent_id); } } break; case __CA_HIER_TYPE_MULTI_MONO__: // you need to set parent_id (otherwise it defaults to the hierarchy root); you only need to set hierarchy_id if you're creating a root if (!($vn_hierarchy_id = $this->get($this->getProperty('HIERARCHY_ID_FLD')))) { $this->set($this->getProperty('HIERARCHY_ID_FLD'), $va_parent_info[$this->getProperty('HIERARCHY_ID_FLD')]); } if (!$vn_parent_id) { if ($vn_parent_id = $this->getHierarchyRootID($vn_hierarchy_id)) { $this->set($this->getProperty('HIERARCHY_PARENT_ID_FLD'), $vn_parent_id); $va_parent_info = $this->_getHierarchyParent($vn_parent_id); } } break; case __CA_HIER_TYPE_ADHOC_MONO__: // you need to set parent_id for this hierarchy; you never need to set hierarchy_id if (!($vn_hierarchy_id = $this->get($this->getProperty('HIERARCHY_ID_FLD')))) { if ($va_parent_info) { // set hierarchy to that of parent $this->set($this->getProperty('HIERARCHY_ID_FLD'), $va_parent_info[$this->getProperty('HIERARCHY_ID_FLD')]); } // if there's no parent then this is a root in which case HIERARCHY_ID_FLD should be set to the primary // key of the row, which we'll know once we insert it (so we must set it after insert) } break; case __CA_HIER_TYPE_MULTI_POLY__: // TODO: implement break; default: die("Invalid hierarchy type: ".$this->getHierarchyType()); break; } if ($va_parent_info) { $va_hier_indexing = $this->_calcHierarchicalIndexing($va_parent_info); } else { $va_hier_indexing = array('left' => 1, 'right' => pow(2,32)); } $this->set($this->getProperty('HIERARCHY_LEFT_INDEX_FLD'), $va_hier_indexing['left']); $this->set($this->getProperty('HIERARCHY_RIGHT_INDEX_FLD'), $va_hier_indexing['right']); } $va_many_to_one_relations = $this->_DATAMODEL->getManyToOneRelations($this->tableName()); foreach($this->FIELDS as $vs_field => $va_attr) { $vs_field_type = $va_attr["FIELD_TYPE"]; # field type $vs_field_value = $this->get($vs_field, array("TIMECODE_FORMAT" => "RAW")); if (isset($va_attr['DONT_PROCESS_DURING_INSERT_UPDATE']) && (bool)$va_attr['DONT_PROCESS_DURING_INSERT_UPDATE']) { continue; } # --- check bounds (value, length and choice lists) $pb_need_reload = false; if (!$this->verifyFieldValue($vs_field, $vs_field_value, $pb_need_reload)) { # verifyFieldValue() posts errors so we don't have to do anything here # No query will be run if there are errors so we don't have to worry about invalid # values being written into the database. By not immediately bailing on an error we # can return a list of *all* input errors to the caller; this is perfect listing all form input errors in # a form-based user interface } if ($pb_need_reload) { $vs_field_value = $this->get($vs_field, array("TIMECODE_FORMAT" => "RAW")); // reload value since verifyFieldValue() may force the value to a default } # --- TODO: This is MySQL dependent # --- primary key has no place in an INSERT statement if it is identity if ($vs_field == $this->primaryKey()) { if (isset($va_attr["IDENTITY"]) && $va_attr["IDENTITY"]) { if (!defined('__CA_ALLOW_SETTING_OF_PRIMARY_KEYS__') || !$vs_field_value) { continue; } } } # --- check ->one relations if (isset($va_many_to_one_relations[$vs_field]) && $va_many_to_one_relations[$vs_field]) { # Nothing to verify if key is null if (!( (isset($va_attr["IS_NULL"]) && $va_attr["IS_NULL"]) && ( ($vs_field_value == "") || ($vs_field_value === null) ) )) { if ($t_many_table = $this->_DATAMODEL->getTableInstance($va_many_to_one_relations[$vs_field]["one_table"])) { if ($this->inTransaction()) { $t_many_table->setTransaction($this->getTransaction()); } $t_many_table->load($this->get($va_many_to_one_relations[$vs_field]["many_table_field"])); } if ($t_many_table->numErrors()) { $this->postError(750,_t("%1 record with $vs_field = %2 does not exist", $t_many_table->tableName(), $this->get($vs_field)),"BaseModel->insert()"); } } } if (isset($va_attr["IS_NULL"]) && $va_attr["IS_NULL"] && ($vs_field_value == null)) { $vs_field_value_is_null = true; } else { $vs_field_value_is_null = false; } if ($vs_field_value_is_null) { if (($vs_field_type == FT_DATERANGE) || ($vs_field_type == FT_HISTORIC_DATERANGE) || ($vs_field_type == FT_TIMERANGE)) { $start_field_name = $va_attr["START"]; $end_field_name = $va_attr["END"]; $vs_fields .= "$start_field_name, $end_field_name,"; $vs_values .= "NULL, NULL,"; } else { $vs_fields .= "$vs_field,"; $vs_values .= "NULL,"; } } else { switch($vs_field_type) { # ----------------------------- case (FT_DATETIME): # date/time case (FT_HISTORIC_DATETIME): case (FT_DATE): case (FT_HISTORIC_DATE): $vs_fields .= "$vs_field,"; $v = isset($this->_FIELD_VALUES[$vs_field]) ? $this->_FIELD_VALUES[$vs_field] : null; if ($v == '') { $this->postError(1805, _t("Date is undefined but field %1 does not support NULL values", $vs_field),"BaseModel->insert()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } if (!is_numeric($v)) { $this->postError(1100, _t("Date is invalid for %1", $vs_field),"BaseModel->insert()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } $vs_values .= $v.","; # output as is break; # ----------------------------- case (FT_TIME): $vs_fields .= $vs_field.","; $v = isset($this->_FIELD_VALUES[$vs_field]) ? $this->_FIELD_VALUES[$vs_field] : null; if ($v == "") { $this->postError(1805, _t("Time is undefined but field %1 does not support NULL values", $vs_field),"BaseModel->insert()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } if (!is_numeric($v)) { $this->postError(1100, _t("Time is invalid for ", $vs_field),"BaseModel->insert()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } $vs_values .= $v.","; # output as is break; # ----------------------------- case (FT_TIMESTAMP): # insert on stamp $vs_fields .= $vs_field.","; $vs_values .= time().","; break; # ----------------------------- case (FT_DATERANGE): case (FT_HISTORIC_DATERANGE): $start_field_name = $va_attr["START"]; $end_field_name = $va_attr["END"]; if (($this->_FIELD_VALUES[$start_field_name] == "") || ($this->_FIELD_VALUES[$end_field_name] == "")) { $this->postError(1805, _t("Daterange is undefined but field does not support NULL values"),"BaseModel->insert()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } if (!is_numeric($this->_FIELD_VALUES[$start_field_name])) { $this->postError(1100, _t("Starting date is invalid"),"BaseModel->insert()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } if (!is_numeric($this->_FIELD_VALUES[$end_field_name])) { $this->postError(1100,_t("Ending date is invalid"),"BaseModel->insert()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } $vs_fields .= "$start_field_name, $end_field_name,"; $vs_values .= $this->_FIELD_VALUES[$start_field_name].", ".$this->_FIELD_VALUES[$end_field_name].","; break; # ----------------------------- case (FT_TIMERANGE): $start_field_name = $va_attr["START"]; $end_field_name = $va_attr["END"]; if (($this->_FIELD_VALUES[$start_field_name] == "") || ($this->_FIELD_VALUES[$end_field_name] == "")) { $this->postError(1805,_t("Time range is undefined but field does not support NULL values"),"BaseModel->insert()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } if (!is_numeric($this->_FIELD_VALUES[$start_field_name])) { $this->postError(1100,_t("Starting time is invalid"),"BaseModel->insert()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } if (!is_numeric($this->_FIELD_VALUES[$end_field_name])) { $this->postError(1100,_t("Ending time is invalid"),"BaseModel->insert()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } $vs_fields .= "$start_field_name, $end_field_name,"; $vs_values .= $this->_FIELD_VALUES[$start_field_name].", ".$this->_FIELD_VALUES[$end_field_name].","; break; # ----------------------------- case (FT_NUMBER): case (FT_BIT): if (!$vb_is_hierarchical) { if ((isset($this->RANK)) && ($vs_field == $this->RANK) && (!$this->get($this->RANK))) { $qr_fmax = $o_db->query("SELECT MAX(".$this->RANK.") m FROM ".$this->TABLE); $qr_fmax->nextRow(); $vs_field_value = $qr_fmax->get("m")+1; $this->set($vs_field, $vs_field_value); } } $vs_fields .= "$vs_field,"; $v = $vs_field_value; if (!trim($v)) { $v = 0; } if (!is_numeric($v)) { $this->postError(1100,_t("Number is invalid for %1 [%2]", $vs_field, $v),"BaseModel->insert()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } $vs_values .= $v.","; break; # ----------------------------- case (FT_TIMECODE): $vs_fields .= $vs_field.","; $v = $vs_field_value; if (!trim($v)) { $v = 0; } if (!is_numeric($v)) { $this->postError(1100, _t("Timecode is invalid"),"BaseModel->insert()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } $vs_values .= $v.","; break; # ----------------------------- case (FT_MEDIA): $vs_fields .= $vs_field.","; $vs_values .= "'',"; $va_media_fields[] = $vs_field; break; # ----------------------------- case (FT_FILE): $vs_fields .= $vs_field.","; $vs_values .= "'',"; $va_file_fields[] = $vs_field; break; # ----------------------------- case (FT_TEXT): case (FT_PASSWORD): $vs_fields .= $vs_field.","; $vs_value = $this->quote($this->get($vs_field)); $vs_values .= $vs_value.","; break; # ----------------------------- case (FT_VARS): $vs_fields .= $vs_field.","; $vs_values .= $this->quote(caSerializeForDatabase($this->get($vs_field), (isset($va_attr['COMPRESS']) && $va_attr['COMPRESS']) ? true : false)).","; break; # ----------------------------- default: # Should never be executed die("$vs_field not caught in insert()"); # ----------------------------- } } } if ($this->numErrors() == 0) { $vs_fields = substr($vs_fields,0,strlen($vs_fields)-1); # remove trailing comma $vs_values = substr($vs_values,0,strlen($vs_values)-1); # remove trailing comma $vs_sql = "INSERT INTO ".$this->TABLE." ($vs_fields) VALUES ($vs_values)"; if ($this->debug) echo $vs_sql; $o_db->query($vs_sql); if ($o_db->numErrors() == 0) { if ($this->getFieldInfo($this->primaryKey(), "IDENTITY")) { $this->_FIELD_VALUES[$this->primaryKey()] = $o_db->getLastInsertID(); } if ((sizeof($va_media_fields) > 0) || (sizeof($va_file_fields) > 0) || ($this->getHierarchyType() == __CA_HIER_TYPE_ADHOC_MONO__)) { $vs_sql = ""; if (sizeof($va_media_fields) > 0) { foreach($va_media_fields as $f) { if($vs_msql = $this->_processMedia($f, array('delete_old_media' => false))) { $vs_sql .= $vs_msql; } } } if (sizeof($va_file_fields) > 0) { foreach($va_file_fields as $f) { if($vs_msql = $this->_processFiles($f)) { $vs_sql .= $vs_msql; } } } if($this->getHierarchyType() == __CA_HIER_TYPE_ADHOC_MONO__) { // Ad-hoc hierarchy if (!$this->get($this->getProperty('HIERARCHY_ID_FLD'))) { $vs_sql .= $this->getProperty('HIERARCHY_ID_FLD').' = '.$this->getPrimaryKey().' '; } } if ($this->numErrors() == 0) { $vs_sql = substr($vs_sql, 0, strlen($vs_sql) - 1); if ($vs_sql) { $o_db->query("UPDATE ".$this->tableName()." SET ".$vs_sql." WHERE ".$this->primaryKey()." = ?", $this->getPrimaryKey(1)); } } else { # media and/or file error $o_db->query("DELETE FROM ".$this->tableName()." WHERE ".$this->primaryKey()." = ?", $this->getPrimaryKey(1)); $this->_FIELD_VALUES[$this->primaryKey()] = ""; if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } } $this->_FILES_CLEAR = array(); $this->logChange("I"); # # update search index # $vn_id = $this->getPrimaryKey(); if ((!isset($pa_options['dont_do_search_indexing']) || (!$pa_options['dont_do_search_indexing'])) && !defined('__CA_DONT_DO_SEARCH_INDEXING__')) { $this->doSearchIndexing(); } if ($vb_we_set_transaction) { $this->removeTransaction(true); } $this->_FIELD_VALUE_CHANGED = array(); return $vn_id; } else { foreach($o_db->errors() as $o_e) { $this->postError($o_e->getErrorNumber(), $o_e->getErrorDescription().' ['.$o_e->getErrorNumber().']', "BaseModel->insert()"); } if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } } else { foreach($o_db->errors() as $o_e) { switch($vn_err_num = $o_e->getErrorNumber()) { case 251: // violation of unique key (duplicate record) $va_indices = $o_db->getIndices($this->tableName()); // try to get key info if (preg_match("/for key [']{0,1}([\w]+)[']{0,1}$/", $o_e->getErrorDescription(), $va_matches)) { $va_field_labels = array(); foreach($va_indices[$va_matches[1]]['fields'] as $vs_col_name) { $va_tmp = $this->getFieldInfo($vs_col_name); $va_field_labels[] = $va_tmp['LABEL']; } $vs_last_name = array_pop($va_field_labels); if (sizeof($va_field_labels) > 0) { $vs_err_desc = _t("The combination of %1 and %2 must be unique", join(', ', $va_field_labels), $vs_last_name); } else { $vs_err_desc = _t("The value of %1 must be unique", $vs_last_name); } } else { $vs_err_desc = $o_e->getErrorDescription(); } $this->postError($vn_err_num, $vs_err_desc, "BaseModel->insert()"); break; default: $this->postError($vn_err_num, $o_e->getErrorDescription().' ['.$vn_err_num.']', "BaseModel->insert()"); break; } } if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } } else { $this->postError(400, _t("Mode was %1; must be write", $this->getMode(true)),"BaseModel->insert()"); return false; } } /** * Generic method to save content properties of object to database fields * Use this, if you've contructed your BaseModel object to represent an existing record * if you've loaded an existing record. * * @param array $pa_options options array * possible options (keys): * dont_check_circular_references = when dealing with strict monohierarchical lists (also known as trees), you can use this option to disable checks for circuits in the graph * update_only_media_versions = when set to an array of valid media version names, media is only processed for the specified versions * force = if set field values are not verified prior to performing the update * @return bool success state */ public function update ($pa_options=null) { if (!is_array($pa_options)) { $pa_options = array(); } $this->field_conflicts = array(); $this->clearErrors(); $va_rebuild_hierarchical_index = null; if (!$this->getPrimaryKey()) { $this->postError(765, _t("Can't do update() on new record; use insert() instead"),"BaseModel->update()"); return false; } if ($this->getMode() == ACCESS_WRITE) { // do form timestamp check if (isset($_REQUEST['form_timestamp']) && ($vn_form_timestamp = $_REQUEST['form_timestamp'])) { $va_possible_conflicts = $this->getChangeLog(null, array('range' => array('start' => $vn_form_timestamp, 'end' => time()), 'excludeUnitID' => $this->getCurrentLoggingUnitID())); if (sizeof($va_possible_conflicts)) { $va_conflict_users = array(); $va_conflict_fields = array(); foreach($va_possible_conflicts as $va_conflict) { $vs_user_desc = trim($va_conflict['fname'].' '.$va_conflict['lname']); if ($vs_user_email = trim($va_conflict['email'])) { $vs_user_desc .= ' ('.$vs_user_email.')'; } if ($vs_user_desc) { $va_conflict_users[$vs_user_desc] = true; } if(isset($va_conflict['snapshot']) && is_array($va_conflict['snapshot'])) { foreach($va_conflict['snapshot'] as $vs_field => $vs_value) { if ($va_conflict_fields[$vs_field]) { continue; } $va_conflict_fields[$vs_field] = true; } } } $this->field_conflicts = array_keys($va_conflict_fields); switch (sizeof($va_conflict_users)) { case 0: $this->postError(795, _t('Changes have been made since you loaded this data. Save again to overwrite the changes or cancel to keep the changes.'), "BaseModel->update()"); break; case 1: $this->postError(795, _t('Changes have been made since you loaded this data by %1. Save again to overwrite the changes or cancel to keep the changes.', join(', ', array_keys($va_conflict_users))), "BaseModel->update()"); break; default: $this->postError(795, _t('Changes have been made since you loaded this data by these users: %1. Save again to overwrite the changes or cancel to keep the changes.', join(', ', array_keys($va_conflict_users))), "BaseModel->update()"); break; } } } $vb_we_set_transaction = false; if (!$this->inTransaction()) { $this->setTransaction(new Transaction($this->getDb())); $vb_we_set_transaction = true; } $o_db = $this->getDb(); if ($vb_is_hierarchical = $this->isHierarchical()) { $vs_parent_id_fld = $this->getProperty('HIERARCHY_PARENT_ID_FLD'); $vs_hier_left_fld = $this->getProperty('HIERARCHY_LEFT_INDEX_FLD'); $vs_hier_right_fld = $this->getProperty('HIERARCHY_RIGHT_INDEX_FLD'); $vs_hier_id_fld = $this->getProperty('HIERARCHY_ID_FLD'); // save original left/right index values - we need them later to recalculate // the indexing values for children of this record $vn_orig_hier_left = $this->get($vs_hier_left_fld); $vn_orig_hier_right = $this->get($vs_hier_right_fld); $vn_parent_id = $this->get($vs_parent_id_fld); if ($vb_parent_id_changed = $this->changed($vs_parent_id_fld)) { $va_parent_info = $this->_getHierarchyParent($vn_parent_id); if (!$pa_options['dont_check_circular_references']) { $va_ids = $this->getHierarchyIDs($this->getPrimaryKey()); if (in_array($this->get($vs_parent_id_fld), $va_ids)) { $this->postError(2010,_t("Cannot move %1 under its sub-record", $this->getProperty('NAME_SINGULAR')),"BaseModel->update()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } } //if (is_null($this->getOriginalValue($vs_parent_id_fld))) { // don't allow moves of hierarchy roots - just ignore the move and keep on going with the update // $this->set($vs_parent_id_fld, null); // $vb_parent_id_changed = false; //} else { switch($this->getHierarchyType()) { case __CA_HIER_TYPE_SIMPLE_MONO__: // you only need to set parent_id for this type of hierarchy break; case __CA_HIER_TYPE_MULTI_MONO__: // you need to set parent_id; you only need to set hierarchy_id if you're creating a root if (!($vn_hierarchy_id = $this->get($this->getProperty('HIERARCHY_ID_FLD')))) { $this->set($this->getProperty('HIERARCHY_ID_FLD'), $va_parent_info[$this->getProperty('HIERARCHY_ID_FLD')]); } if (!($vn_hierarchy_id = $this->get($vs_hier_id_fld))) { $this->postError(2030, _t("Hierarchy ID must be specified for this update"), "BaseModel->update()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } // Moving between hierarchies if ($this->get($vs_hier_id_fld) != $va_parent_info[$vs_hier_id_fld]) { $vn_hierarchy_id = $va_parent_info[$vs_hier_id_fld]; $this->set($this->getProperty('HIERARCHY_ID_FLD'), $vn_hierarchy_id); if (is_array($va_children = $this->_getHierarchyChildren(array($this->getPrimaryKey())))) { $va_rebuild_hierarchical_index = $va_children; } } break; case __CA_HIER_TYPE_ADHOC_MONO__: // you need to set parent_id for this hierarchy; you never need to set hierarchy_id if ($va_parent_info) { // set hierarchy to that of root if (sizeof($va_ancestors = $this->getHierarchyAncestors($vn_parent_id, array('idsOnly' => true, 'includeSelf' => true)))) { $vn_hierarchy_id = array_pop($va_ancestors); } else { $vn_hierarchy_id = $this->getPrimaryKey(); } $this->set($this->getProperty('HIERARCHY_ID_FLD'), $vn_hierarchy_id); if (is_array($va_children = $this->_getHierarchyChildren(array($this->getPrimaryKey())))) { $va_rebuild_hierarchical_index = $va_children; } } // if there's no parent then this is a root in which case HIERARCHY_ID_FLD should be set to the primary // key of the row, which we'll know once we insert it (so we must set it after insert) break; case __CA_HIER_TYPE_MULTI_POLY__: // TODO: implement break; default: die("Invalid hierarchy type: ".$this->getHierarchyType()); break; } if ($va_parent_info) { $va_hier_indexing = $this->_calcHierarchicalIndexing($va_parent_info); } else { $va_hier_indexing = array('left' => 1, 'right' => pow(2,32)); } $this->set($this->getProperty('HIERARCHY_LEFT_INDEX_FLD'), $va_hier_indexing['left']); $this->set($this->getProperty('HIERARCHY_RIGHT_INDEX_FLD'), $va_hier_indexing['right']); //} } } $vs_sql = "UPDATE ".$this->TABLE." SET "; $va_many_to_one_relations = $this->_DATAMODEL->getManyToOneRelations($this->tableName()); $vn_fields_that_have_been_set = 0; foreach ($this->FIELDS as $vs_field => $va_attr) { if (isset($va_attr['DONT_PROCESS_DURING_INSERT_UPDATE']) && (bool)$va_attr['DONT_PROCESS_DURING_INSERT_UPDATE']) { continue; } if (isset($va_attr['IDENTITY']) && $va_attr['IDENTITY']) { continue; } // never update identity fields $vs_field_type = isset($va_attr["FIELD_TYPE"]) ? $va_attr["FIELD_TYPE"] : null; # field type $vn_datatype = $this->_getFieldTypeType($vs_field); # field's underlying datatype $vs_field_value = $this->get($vs_field, array("TIMECODE_FORMAT" => "RAW")); # --- check bounds (value, length and choice lists) $pb_need_reload = false; if (!isset($pa_options['force']) || !$pa_options['force']) { if (!$this->verifyFieldValue($vs_field, $vs_field_value, $pb_need_reload)) { # verifyFieldValue() posts errors so we don't have to do anything here # No query will be run if there are errors so we don't have to worry about invalid # values being written into the database. By not immediately bailing on an error we # can return a list of *all* input errors to the caller; this is perfect listing all form input errors in # a form-based user interface } } if ($pb_need_reload) { $vs_field_value = $this->get($vs_field, array("TIMECODE_FORMAT" => "RAW")); // } if (!isset($va_attr["IS_NULL"])) { $va_attr["IS_NULL"] = 0; } if ($va_attr["IS_NULL"] && ($vs_field_value=="")) { $vs_field_value_is_null = 1; } else { $vs_field_value_is_null = 0; } # --- check ->one relations if (isset($va_many_to_one_relations[$vs_field]) && $va_many_to_one_relations[$vs_field]) { # Nothing to verify if key is null if (!(($va_attr["IS_NULL"]) && ($vs_field_value == ""))) { if ($t_many_table = $this->_DATAMODEL->getTableInstance($va_many_to_one_relations[$vs_field]["one_table"])) { if ($this->inTransaction()) { $t_many_table->setTransaction($this->getTransaction()); } $t_many_table->load($this->get($va_many_to_one_relations[$vs_field]["many_table_field"])); } if ($t_many_table->numErrors()) { $this->postError(750,_t("%1 record with $vs_field = %2 does not exist", $t_many_table->tableName(), $this->get($vs_field)),"BaseModel->update()"); } } } if (($vs_field_value_is_null) && (!(isset($va_attr["UPDATE_ON_UPDATE"]) && $va_attr["UPDATE_ON_UPDATE"]))) { if (($vs_field_type == FT_DATERANGE) || ($vs_field_type == FT_HISTORIC_DATERANGE) || ($vs_field_type == FT_TIMERANGE)) { $start_field_name = $va_attr["START"]; $end_field_name = $va_attr["END"]; $vs_sql .= "$start_field_name = NULL, $end_field_name = NULL,"; } else { $vs_sql .= "$vs_field = NULL,"; } $vn_fields_that_have_been_set++; } else { if (($vs_field_type != FT_TIMESTAMP) && !$this->changed($vs_field)) { continue; } // don't try to update fields that haven't changed -- saves time, especially for large fields like FT_VARS and FT_TEXT when text is long switch($vs_field_type) { # ----------------------------- case (FT_NUMBER): case (FT_BIT): $vm_val = isset($this->_FIELD_VALUES[$vs_field]) ? $this->_FIELD_VALUES[$vs_field] : null; if (!trim($vm_val)) { $vm_val = 0; } if (!is_numeric($vm_val)) { $this->postError(1100,_t("Number is invalid for %1", $vs_field),"BaseModel->update()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } $vs_sql .= "{$vs_field} = {$vm_val},"; $vn_fields_that_have_been_set++; break; # ----------------------------- case (FT_TEXT): case (FT_PASSWORD): $vm_val = isset($this->_FIELD_VALUES[$vs_field]) ? $this->_FIELD_VALUES[$vs_field] : null; $vs_sql .= "{$vs_field} = ".$this->quote($vm_val).","; $vn_fields_that_have_been_set++; break; # ----------------------------- case (FT_VARS): $vm_val = isset($this->_FIELD_VALUES[$vs_field]) ? $this->_FIELD_VALUES[$vs_field] : null; $vs_sql .= "{$vs_field} = ".$this->quote(caSerializeForDatabase($vm_val, ((isset($va_attr['COMPRESS']) && $va_attr['COMPRESS']) ? true : false))).","; $vn_fields_that_have_been_set++; break; # ----------------------------- case (FT_DATETIME): case (FT_HISTORIC_DATETIME): case (FT_DATE): case (FT_HISTORIC_DATE): $vm_val = isset($this->_FIELD_VALUES[$vs_field]) ? $this->_FIELD_VALUES[$vs_field] : null; if ($vm_val == "") { $this->postError(1805,_t("Date is undefined but field does not support NULL values"),"BaseModel->update()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } if (!is_numeric($vm_val)) { $this->postError(1100,_t("Date is invalid for %1", $vs_field),"BaseModel->update()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } $vs_sql .= "{$vs_field} = {$vm_val},"; # output as is $vn_fields_that_have_been_set++; break; # ----------------------------- case (FT_TIME): $vm_val = isset($this->_FIELD_VALUES[$vs_field]) ? $this->_FIELD_VALUES[$vs_field] : null; if ($vm_val == "") { $this->postError(1805, _t("Time is undefined but field does not support NULL values"),"BaseModel->update()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } if (!is_numeric($vm_val)) { $this->postError(1100, _t("Time is invalid for %1", $vs_field),"BaseModel->update()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } $vs_sql .= "{$vs_field} = {$vm_val},"; # output as is $vn_fields_that_have_been_set++; break; # ----------------------------- case (FT_TIMESTAMP): if (isset($va_attr["UPDATE_ON_UPDATE"]) && $va_attr["UPDATE_ON_UPDATE"]) { $vs_sql .= "{$vs_field} = ".time().","; $vn_fields_that_have_been_set++; } break; # ----------------------------- case (FT_DATERANGE): case (FT_HISTORIC_DATERANGE): $vn_start_field_name = $va_attr["START"]; $vn_end_field_name = $va_attr["END"]; if (($this->_FIELD_VALUES[$vn_start_field_name] == "") || ($this->_FIELD_VALUES[$vn_end_field_name] == "")) { $this->postError(1805,_t("Daterange is undefined but field does not support NULL values"),"BaseModel->update()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } if (!is_numeric($this->_FIELD_VALUES[$vn_start_field_name])) { $this->postError(1100,_t("Starting date is invalid"),"BaseModel->update()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } if (!is_numeric($this->_FIELD_VALUES[$vn_end_field_name])) { $this->postError(1100,_t("Ending date is invalid"),"BaseModel->update()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } $vs_sql .= "{$vn_start_field_name} = ".$this->_FIELD_VALUES[$vn_start_field_name].", {$vn_end_field_name} = ".$this->_FIELD_VALUES[$vn_end_field_name].","; $vn_fields_that_have_been_set++; break; # ----------------------------- case (FT_TIMERANGE): $vn_start_field_name = $va_attr["START"]; $vn_end_field_name = $va_attr["END"]; if (($this->_FIELD_VALUES[$vn_start_field_name] == "") || ($this->_FIELD_VALUES[$vn_end_field_name] == "")) { $this->postError(1805,_t("Time range is undefined but field does not support NULL values"),"BaseModel->update()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } if (!is_numeric($this->_FIELD_VALUES[$vn_start_field_name])) { $this->postError(1100,_t("Starting time is invalid"),"BaseModel->update()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } if (!is_numeric($this->_FIELD_VALUES[$vn_end_field_name])) { $this->postError(1100,_t("Ending time is invalid"),"BaseModel->update()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } $vs_sql .= "{$vn_start_field_name} = ".$this->_FIELD_VALUES[$vn_start_field_name].", {$vn_end_field_name} = ".$this->_FIELD_VALUES[$vn_end_field_name].","; $vn_fields_that_have_been_set++; break; # ----------------------------- case (FT_TIMECODE): $vm_val = isset($this->_FIELD_VALUES[$vs_field]) ? $this->_FIELD_VALUES[$vs_field] : null; if (!trim($vm_val)) { $vm_val = 0; } if (!is_numeric($vm_val)) { $this->postError(1100,_t("Timecode is invalid"),"BaseModel->update()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } $vs_sql .= "{$vs_field} = {$vm_val},"; $vn_fields_that_have_been_set++; break; # ----------------------------- case (FT_MEDIA): $va_limit_to_versions = (isset($pa_options['update_only_media_versions']) ? $pa_options['update_only_media_versions'] : null); if ($vs_media_sql = $this->_processMedia($vs_field, array('these_versions_only' => $va_limit_to_versions))) { $vs_sql .= $vs_media_sql; $vn_fields_that_have_been_set++; } else { if ($this->numErrors() > 0) { if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } } break; # ----------------------------- case (FT_FILE): if ($vs_file_sql = $this->_processFiles($vs_field)) { $vs_sql .= $vs_file_sql; $vn_fields_that_have_been_set++; } else { if ($this->numErrors() > 0) { if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } } break; # ----------------------------- } } } if ($this->numErrors() == 0) { if ($vn_fields_that_have_been_set > 0) { $vs_sql = substr($vs_sql,0,strlen($vs_sql)-1); # remove trailing comma $vs_sql .= " WHERE ".$this->PRIMARY_KEY." = ".$this->getPrimaryKey(1); if ($this->debug) echo $vs_sql; $o_db->query($vs_sql); if ($o_db->numErrors()) { foreach($o_db->errors() as $o_e) { switch($vn_err_num = $o_e->getErrorNumber()) { case 251: // violation of unique key (duplicate record) // try to get key info $va_indices = $o_db->getIndices($this->tableName()); if (preg_match("/for key [']{0,1}([\w]+)[']{0,1}$/", $o_e->getErrorDescription(), $va_matches)) { $va_field_labels = array(); foreach($va_indices[$va_matches[1]]['fields'] as $vs_col_name) { $va_tmp = $this->getFieldInfo($vs_col_name); $va_field_labels[] = $va_tmp['LABEL']; } $vs_last_name = array_pop($va_field_labels); if (sizeof($va_field_labels) > 0) { $vs_err_desc = "The combination of ".join(', ', $va_field_labels).' and '.$vs_last_name." must be unique"; } else { $vs_err_desc = "The value of {$vs_last_name} must be unique"; } } else { $vs_err_desc = $o_e->getErrorDescription(); } $this->postError($vn_err_num, $vs_err_desc, "BaseModel->insert()"); break; default: $this->postError($vn_err_num, $o_e->getErrorDescription().' ['.$vn_err_num.']', "BaseModel->update()"); break; } } if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } else { if (($vb_is_hierarchical) && ($vb_parent_id_changed)) { // recalulate left/right indexing of sub-records $vn_interval_start = $this->get($vs_hier_left_fld); $vn_interval_end = $this->get($vs_hier_right_fld); if (($vn_interval_start > 0) && ($vn_interval_end > 0)) { if ($vs_hier_id_fld) { $vs_hier_sql = ' AND ('.$vs_hier_id_fld.' = '.$this->get($vs_hier_id_fld).')'; } else { $vs_hier_sql = ""; } $vn_ratio = ($vn_interval_end - $vn_interval_start)/($vn_orig_hier_right - $vn_orig_hier_left); $vs_sql = " UPDATE ".$this->tableName()." SET $vs_hier_left_fld = ($vn_interval_start + (($vs_hier_left_fld - $vn_orig_hier_left) * $vn_ratio)), $vs_hier_right_fld = ($vn_interval_end + (($vs_hier_right_fld - $vn_orig_hier_right) * $vn_ratio)) WHERE (".$vs_hier_left_fld." BETWEEN ".$vn_orig_hier_left." AND ".$vn_orig_hier_right.") $vs_hier_sql "; //print "<hr>$vs_sql<hr>"; $o_db->query($vs_sql); if ($vn_err = $o_db->numErrors()) { $this->postError(2030, _t("Could not update sub records in hierarchy: [%1] %2", $vs_sql, join(';', $o_db->getErrors())),"BaseModel->update()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } } else { $this->postError(2045, _t("Parent record had invalid hierarchical indexing (should not happen!)"), "BaseModel->update()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } } } if ((!isset($pa_options['dont_do_search_indexing']) || (!$pa_options['dont_do_search_indexing'])) && !defined('__CA_DONT_DO_SEARCH_INDEXING__')) { # update search index $this->doSearchIndexing(); } if (is_array($va_rebuild_hierarchical_index)) { //$this->rebuildHierarchicalIndex($this->get($vs_hier_id_fld)); $t_instance = $this->_DATAMODEL->getInstanceByTableName($this->tableName()); foreach($va_rebuild_hierarchical_index as $vn_child_id) { if ($t_instance->load($vn_child_id)) { $t_instance->setMode(ACCESS_WRITE); $t_instance->set($this->getProperty('HIERARCHY_ID_FLD'), $vn_hierarchy_id); $t_instance->update(); if ($t_instance->numErrors()) { $this->errors = array_merge($this->errors, $t_instance->errors); } } } } $this->logChange("U"); $this->_FILES_CLEAR = array(); } if ($vb_we_set_transaction) { $this->removeTransaction(true); } $this->_FIELD_VALUE_CHANGED = array(); return true; } else { if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } } else { $this->postError(400, _t("Mode was %1; must be write or admin", $this->getMode(true)),"BaseModel->update()"); return false; } } public function doSearchIndexing($pa_changed_field_values_array=null, $pb_reindex_mode=false, $ps_engine=null) { if (defined("__CA_DONT_DO_SEARCH_INDEXING__")) { return; } if (is_null($pa_changed_field_values_array)) { $pa_changed_field_values_array = $this->getChangedFieldValuesArray(); } if (!BaseModel::$search_indexer) { BaseModel::$search_indexer = new SearchIndexer($this->getDb(), $ps_engine); } BaseModel::$search_indexer->indexRow($this->tableNum(), $this->getPrimaryKey(), $this->getFieldValuesArray(), $pb_reindex_mode, null, $pa_changed_field_values_array, $this->_FIELD_VALUES_OLD); } /** * Delete record represented by this object. Uses the Datamodel object * to generate possible dependencies and relationships. * * @param bool $pb_delete_related delete stuff related to the record? pass non-zero value if you want to. * @param array $pa_options Options for delete process. Options are: * hard = if true records which can support "soft" delete are really deleted rather than simply being marked as deleted * @param array $pa_fields instead of deleting the record represented by this object instance you can * pass an array of field => value assignments which is used in a SQL-DELETE-WHERE clause. * @param array $pa_table_list this is your possibility to pass an array of table name => true assignments * to specify which tables to omit when deleting related stuff */ public function delete ($pb_delete_related=false, $pa_options=null, $pa_fields=null, $pa_table_list=null) { if ($this->hasField('deleted') && (!isset($pa_options['hard']) || !$pa_options['hard'])) { $this->setMode(ACCESS_WRITE); $this->set('deleted', 1); return $this->update(array('force' => true)); } $this->clearErrors(); if ((!$this->getPrimaryKey()) && (!is_array($pa_fields))) { # is there a record loaded? $this->postError(770, _t("No record loaded"),"BaseModel->delete()"); return false; } if (!is_array($pa_table_list)) { $pa_table_list = array(); } $pa_table_list[$this->tableName()] = true; if ($this->getMode() == ACCESS_WRITE) { $vb_we_set_transaction = false; if (!$this->inTransaction()) { $o_t = new Transaction($this->getDb()); $this->setTransaction($o_t); $vb_we_set_transaction = true; } $o_db = $this->getDb(); if (is_array($pa_fields)) { $vs_sql = "DELETE FROM ".$this->tableName()." WHERE "; $vs_wheres = ""; while(list($vs_field, $vm_val) = each($pa_fields)) { $vn_datatype = $this->_getFieldTypeType($vs_field); switch($vn_datatype) { # ----------------------------- case (0): # number if ($vm_val == "") { $vm_val = 0; } break; # ----------------------------- case (1): # string $vm_val = $this->quote($vm_val); break; # ----------------------------- } if ($vs_wheres) { $vs_wheres .= " AND "; } $vs_wheres .= "($vs_field = $vm_val)"; } $vs_sql .= $vs_wheres; } else { $vs_sql = "DELETE FROM ".$this->tableName()." WHERE ".$this->primaryKey()." = ".$this->getPrimaryKey(1); } if ($this->isHierarchical()) { // TODO: implement delete of children records $vs_parent_id_fld = $this->getProperty('HIERARCHY_PARENT_ID_FLD'); $qr_res = $o_db->query(" SELECT ".$this->primaryKey()." FROM ".$this->tableName()." WHERE {$vs_parent_id_fld} = ? ", $this->getPrimaryKey()); if ($qr_res->nextRow()) { $this->postError(780, _t("Can't delete item because it has sub-records"),"BaseModel->delete()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } } # # --- delete search index entries # $vn_id = $this->getPrimaryKey(); // TODO: FIX THIS ISSUE! // NOTE: we delete the indexing here, before we actually do the // SQL delete because the search indexer relies upon the relevant // relationships to be intact (ie. exist) in order to properly remove the indexing for them. // // In particular, the incremental indexing used by the MySQL Fulltext plugin fails to properly // update if it can't traverse the relationships it is to remove. // // By removing the search indexing here we run the risk of corrupting the search index if the SQL // delete subsequently fails. Specifically, the indexing for rows that still exist in the database // will be removed. Wrapping everything in a MySQL transaction deals with it for MySQL Fulltext, but // other non-SQL engines (Lucene, SOLR, etc.) are still affected. // // At some point we need to come up with something clever to handle this. Most likely it means moving all of the actual // analysis to startRowUnindexing() and only executing commands in commitRowUnIndexing(). For now we blithely assume that // SQL deletes always succeed. If they don't we can always reindex. Only the indexing is affected, not the underlying data. if(!defined('__CA_DONT_DO_SEARCH_INDEXING__')) { if (!BaseModel::$search_indexer) { BaseModel::$search_indexer = new SearchIndexer($this->getDb()); } BaseModel::$search_indexer->startRowUnIndexing($this->tableNum(), $vn_id); BaseModel::$search_indexer->commitRowUnIndexing($this->tableNum(), $vn_id); } # --- Check ->many and many<->many relations $va_one_to_many_relations = $this->_DATAMODEL->getOneToManyRelations($this->tableName()); # # Note: cascading delete code is very slow when used # on a record with a large number of related records as # each record in check individually for cascading deletes... # it is possible to make this *much* faster by crafting clever-er queries # if (is_array($va_one_to_many_relations)) { foreach($va_one_to_many_relations as $vs_many_table => $va_info) { foreach($va_info as $va_relationship) { if (isset($pa_table_list[$vs_many_table.'/'.$va_relationship["many_table_field"]]) && $pa_table_list[$vs_many_table.'/'.$va_relationship["many_table_field"]]) { continue; } # do any records exist? $t_related = $this->_DATAMODEL->getTableInstance($vs_many_table); $t_related->setTransaction($this->getTransaction()); $qr_record_check = $o_db->query(" SELECT ".$t_related->primaryKey()." FROM ".$vs_many_table." WHERE (".$va_relationship["many_table_field"]." = ".$this->getPrimaryKey(1).") "); $pa_table_list[$vs_many_table.'/'.$va_relationship["many_table_field"]] = true; //print "FOR ".$vs_many_table.'/'.$va_relationship["many_table_field"].":".$qr_record_check->numRows()."<br>\n"; if ($qr_record_check->numRows() > 0) { if ($pb_delete_related) { while($qr_record_check->nextRow()) { if ($t_related->load($qr_record_check->get($t_related->primaryKey()))) { $t_related->setMode(ACCESS_WRITE); $t_related->delete($pb_delete_related, $pa_options, null, $pa_table_list); if ($t_related->numErrors()) { $this->postError(790, _t("Can't delete item because items related to it have sub-records (%1)", $vs_many_table),"BaseModel->delete()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } } } } else { $this->postError(780, _t("Can't delete item because it is in use (%1)", $vs_many_table),"BaseModel->delete()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } } } } } # --- do deletion if ($this->debug) echo $vs_sql; $o_db->query($vs_sql); if ($o_db->numErrors() > 0) { $this->errors = $o_db->errors(); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } # cancel and pending queued tasks against this record $tq = new TaskQueue(); $tq->cancelPendingTasksForRow(join("/", array($this->tableName(), $vn_id))); $this->_FILES_CLEAR = array(); # --- delete media and file field files foreach($this->FIELDS as $f => $attr) { switch($attr['FIELD_TYPE']) { case FT_MEDIA: $versions = $this->getMediaVersions($f); foreach ($versions as $v) { $this->_removeMedia($f, $v); } break; case FT_FILE: @unlink($this->getFilePath($f)); #--- delete conversions # foreach ($this->getFileConversions($f) as $vs_format => $va_file_conversion) { @unlink($this->getFileConversionPath($f, $vs_format)); } break; } } if ($o_db->numErrors() == 0) { //if ($vb_is_hierarchical = $this->isHierarchical()) { //} # clear object $this->logChange("D"); $this->clear(); } else { if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } if ($vb_we_set_transaction) { $this->removeTransaction(true); } return true; } else { $this->postError(400, _t("Mode was %1; must be write", $this->getMode(true)),"BaseModel->delete()"); return false; } } # -------------------------------------------------------------------------------- # --- Uploaded media handling # -------------------------------------------------------------------------------- /** * Check if media content is mirrored (depending on settings in configuration file) * * @return bool */ public function mediaIsMirrored($field, $version) { $media_info = $this->get($field); if (!is_array($media_info)) { return ""; } $vi = $this->_MEDIA_VOLUMES->getVolumeInformation($media_info[$version]["VOLUME"]); if (!is_array($vi)) { return ""; } if (is_array($vi["mirrors"])) { return true; } else { return false; } } /** * Get status of media mirror * * @param string $field field name * @param string $version version of the media file, as defined in media_processing.conf * @param string media mirror name, as defined in media_volumes.conf * @return mixed media mirror status */ public function getMediaMirrorStatus($field, $version, $mirror="") { $media_info = $this->get($field); if (!is_array($media_info)) { return ""; } $vi = $this->_MEDIA_VOLUMES->getVolumeInformation($media_info[$version]["VOLUME"]); if (!is_array($vi)) { return ""; } if ($mirror) { return $media_info["MIRROR_STATUS"][$mirror]; } else { return $media_info["MIRROR_STATUS"][$vi["accessUsingMirror"]]; } } /** * Retry mirroring of given media field. Sets global error properties on failure. * * @param string $ps_field field name * @param string $ps_version version of the media file, as defined in media_processing.conf * @return null */ public function retryMediaMirror($ps_field, $ps_version) { global $AUTH_CURRENT_USER_ID; $va_media_info = $this->get($ps_field); if (!is_array($va_media_info)) { return ""; } $va_volume_info = $this->_MEDIA_VOLUMES->getVolumeInformation($va_media_info[$ps_version]["VOLUME"]); if (!is_array($va_volume_info)) { return ""; } $o_tq = new TaskQueue(); $vs_row_key = join("/", array($this->tableName(), $this->getPrimaryKey())); $vs_entity_key = join("/", array($this->tableName(), $ps_field, $this->getPrimaryKey(), $ps_version)); foreach($va_media_info["MIRROR_STATUS"] as $vs_mirror_code => $vs_status) { $va_mirror_info = $va_volume_info["mirrors"][$vs_mirror_code]; $vs_mirror_method = $va_mirror_info["method"]; $vs_queue = $vs_mirror_method."mirror"; switch($vs_status) { case 'FAIL': case 'PARTIAL': if (!($o_tq->cancelPendingTasksForEntity($vs_entity_key))) { //$this->postError(560, _t("Could not cancel pending tasks: %1", $this->error),"BaseModel->retryMediaMirror()"); //return false; } if ($o_tq->addTask( $vs_queue, array( "MIRROR" => $vs_mirror_code, "VOLUME" => $va_media_info[$ps_version]["VOLUME"], "FIELD" => $ps_field, "TABLE" => $this->tableName(), "VERSION" => $ps_version, "FILES" => array( array( "FILE_PATH" => $this->getMediaPath($ps_field, $ps_version), "ABS_PATH" => $va_volume_info["absolutePath"], "HASH" => $this->_FIELD_VALUES[$ps_field][$ps_version]["HASH"], "FILENAME" => $this->_FIELD_VALUES[$ps_field][$ps_version]["FILENAME"] ) ), "MIRROR_INFO" => $va_mirror_info, "PK" => $this->primaryKey(), "PK_VAL" => $this->getPrimaryKey() ), array("priority" => 100, "entity_key" => $vs_entity_key, "row_key" => $vs_row_key, 'user_id' => $AUTH_CURRENT_USER_ID))) { $va_media_info["MIRROR_STATUS"][$vs_mirror_code] = ""; // pending $this->setMediaInfo($ps_field, $va_media_info); $this->setMode(ACCESS_WRITE); $this->update(); continue; } else { $this->postError(100, _t("Couldn't queue mirror using '%1' for version '%2' (handler '%3')", $vs_mirror_method, $ps_version, $queue),"BaseModel->retryMediaMirror()"); } break; } } } /** * Returns url of media file * * @param string $ps_field field name * @param string $ps_version version of the media file, as defined in media_processing.conf * @param int $pn_page page number, defaults to 1 * @return string the url */ public function getMediaUrl($ps_field, $ps_version, $pn_page=1) { $va_media_info = $this->getMediaInfo($ps_field); if (!is_array($va_media_info)) { return ""; } # # Is this version externally hosted? # if (isset($va_media_info[$ps_version]["EXTERNAL_URL"]) && ($va_media_info[$ps_version]["EXTERNAL_URL"])) { return $va_media_info[$ps_version]["EXTERNAL_URL"]; } # # Is this version queued for processing? # if (isset($va_media_info[$ps_version]["QUEUED"]) && ($va_media_info[$ps_version]["QUEUED"])) { if ($va_media_info[$ps_version]["QUEUED_ICON"]["src"]) { return $va_media_info[$ps_version]["QUEUED_ICON"]["src"]; } else { return ""; } } $va_volume_info = $this->_MEDIA_VOLUMES->getVolumeInformation($va_media_info[$ps_version]["VOLUME"]); if (!is_array($va_volume_info)) { return ""; } # is this mirrored? if ( (isset($va_volume_info["accessUsingMirror"]) && $va_volume_info["accessUsingMirror"]) && ( isset($va_media_info["MIRROR_STATUS"][$va_volume_info["accessUsingMirror"]]) && ($va_media_info["MIRROR_STATUS"][$va_volume_info["accessUsingMirror"]] == "SUCCESS") ) ) { $vs_protocol = $va_volume_info["mirrors"][$va_volume_info["accessUsingMirror"]]["accessProtocol"]; $vs_host = $va_volume_info["mirrors"][$va_volume_info["accessUsingMirror"]]["accessHostname"]; $vs_url_path = $va_volume_info["mirrors"][$va_volume_info["accessUsingMirror"]]["accessUrlPath"]; } else { $vs_protocol = $va_volume_info["protocol"]; $vs_host = $va_volume_info["hostname"]; $vs_url_path = $va_volume_info["urlPath"]; } if ($va_media_info[$ps_version]["FILENAME"]) { $vs_fpath = join("/",array($vs_url_path, $va_media_info[$ps_version]["HASH"], $va_media_info[$ps_version]["MAGIC"]."_".$va_media_info[$ps_version]["FILENAME"])); return $vs_protocol."://$vs_host".$vs_fpath; } else { return ""; } } /** * Returns path of media file * * @param string $ps_field field name * @param string $ps_version version of the media file, as defined in media_processing.conf * @param int $pn_page page number, defaults to 1 * @return string path of the media file */ public function getMediaPath($ps_field, $ps_version, $pn_page=1) { $va_media_info = $this->getMediaInfo($ps_field); if (!is_array($va_media_info)) { return ""; } # # Is this version externally hosted? # if (isset($va_media_info[$ps_version]["EXTERNAL_URL"]) && ($va_media_info[$ps_version]["EXTERNAL_URL"])) { return ''; // no local path for externally hosted media } # # Is this version queued for processing? # if (isset($va_media_info[$ps_version]["QUEUED"]) && $va_media_info[$ps_version]["QUEUED"]) { if ($va_media_info[$ps_version]["QUEUED_ICON"]["filepath"]) { return $va_media_info[$ps_version]["QUEUED_ICON"]["filepath"]; } else { return ""; } } $va_volume_info = $this->_MEDIA_VOLUMES->getVolumeInformation($va_media_info[$ps_version]["VOLUME"]); if (!is_array($va_volume_info)) { return ""; } if ($va_media_info[$ps_version]["FILENAME"]) { return join("/",array($va_volume_info["absolutePath"], $va_media_info[$ps_version]["HASH"], $va_media_info[$ps_version]["MAGIC"]."_".$va_media_info[$ps_version]["FILENAME"])); } else { return ""; } } /** * Returns appropriate representation of that media version in an html tag, including attributes for display * * @param string $field field name * @param string $version version of the media file, as defined in media_processing.conf * @param string $name name attribute of the img tag * @param string $vspace vspace attribute of the img tag - note: deprecated in HTML 4.01, not supported in XHTML 1.0 Strict * @param string $hspace hspace attribute of the img tag - note: deprecated in HTML 4.01, not supported in XHTML 1.0 Strict * @param string $alt alt attribute of the img tag * @param int $border border attribute of the img tag - note: deprecated in HTML 4.01, not supported in XHTML 1.0 Strict * @param string $usemap usemap attribute of the img tag * @param int $align align attribute of the img tag - note: deprecated in HTML 4.01, not supported in XHTML 1.0 Strict * @return string html tag */ public function getMediaTag($field, $version, $pa_options=null) { $media_info = $this->getMediaInfo($field); if (!is_array($media_info[$version])) { return ""; } # # Is this version queued for processing? # if (isset($media_info[$version]["QUEUED"]) && ($media_info[$version]["QUEUED"])) { if ($media_info[$version]["QUEUED_ICON"]["src"]) { return "<img src='".$media_info[$version]["QUEUED_ICON"]["src"]."' width='".$media_info[$version]["QUEUED_ICON"]["width"]."' height='".$media_info[$version]["QUEUED_ICON"]["height"]."' alt='".$media_info[$version]["QUEUED_ICON"]["alt"]."'>"; } else { return $media_info[$version]["QUEUED_MESSAGE"]; } } $url = $this->getMediaUrl($field, $version, isset($options["page"]) ? $options["page"] : null); $m = new Media(); $o_vol = new MediaVolumes(); $va_volume = $o_vol->getVolumeInformation($media_info[$version]['VOLUME']); return $m->htmlTag($media_info[$version]["MIMETYPE"], $url, $media_info[$version]["PROPERTIES"], $pa_options, $va_volume); } /** * Get media information for the given field * * @param string $field field name * @param string $version version of the media file, as defined in media_processing.conf, can be omitted to retrieve information about all versions * @param string $property this is your opportunity to restrict the result to a certain property for the given (field,version) pair. * possible values are: * -VOLUME * -MIMETYPE * -WIDTH * -HEIGHT * -PROPERTIES: returns an array with some media metadata like width, height, mimetype, etc. * -FILENAME * -HASH * -MAGIC * -EXTENSION * -MD5 * @return mixed media information */ public function &getMediaInfo($field, $version="", $property="") { $media_info = $this->get($field, array('USE_MEDIA_FIELD_VALUES' => true)); if (!is_array($media_info)) { return ""; } if ($version) { if (!$property) { return $media_info[$version]; } else { return $media_info[$version][$property]; } } else { return $media_info; } } /** * Fetches media input type for the given field, e.g. "image" * * @param $ps_field field name * @return string media input type */ public function getMediaInputType($ps_field) { if ($va_media_info = $this->getMediaInfo($ps_field)) { $o_media_proc_settings = new MediaProcessingSettings($this, $ps_field); return $o_media_proc_settings->canAccept($va_media_info["INPUT"]["MIMETYPE"]); } else { return null; } } /** * Fetches media input type for the given field, e.g. "image" and version * * @param string $ps_field field name * @param string $ps_version version * @return string media input type */ public function getMediaInputTypeForVersion($ps_field, $ps_version) { if ($va_media_info = $this->getMediaInfo($ps_field)) { $o_media_proc_settings = new MediaProcessingSettings($this, $ps_field); if($vs_media_type = $o_media_proc_settings->canAccept($va_media_info["INPUT"]["MIMETYPE"])) { $va_media_type_info = $o_media_proc_settings->getMediaTypeInfo($vs_media_type); if (isset($va_media_type_info['VERSIONS'][$ps_version])) { if ($va_rule = $o_media_proc_settings->getMediaTransformationRule($va_media_type_info['VERSIONS'][$ps_version]['RULE'])) { return $o_media_proc_settings->canAccept($va_rule['SET']['format']); } } } } return null; } /** * Returns default version to display for the given field based upon the currently loaded row * * @param string $ps_field field name */ public function getDefaultMediaVersion($ps_field) { if ($va_media_info = $this->getMediaInfo($ps_field)) { $o_media_proc_settings = new MediaProcessingSettings($this, $ps_field); $va_type_info = $o_media_proc_settings->getMediaTypeInfo($o_media_proc_settings->canAccept($va_media_info["INPUT"]["MIMETYPE"])); return ($va_type_info['MEDIA_VIEW_DEFAULT_VERSION']) ? $va_type_info['MEDIA_VIEW_DEFAULT_VERSION'] : array_shift($this->getMediaVersions($ps_field)); } else { return null; } } /** * Returns default version to display as a preview for the given field based upon the currently loaded row * * @param string $ps_field field name */ public function getDefaultMediaPreviewVersion($ps_field) { if ($va_media_info = $this->getMediaInfo($ps_field)) { $o_media_proc_settings = new MediaProcessingSettings($this, $ps_field); $va_type_info = $o_media_proc_settings->getMediaTypeInfo($o_media_proc_settings->canAccept($va_media_info["INPUT"]["MIMETYPE"])); return ($va_type_info['MEDIA_PREVIEW_DEFAULT_VERSION']) ? $va_type_info['MEDIA_PREVIEW_DEFAULT_VERSION'] : array_shift($this->getMediaVersions($ps_field)); } else { return null; } } /** * Fetches available media versions for the given field (and optional mimetype), as defined in media_processing.conf * * @param string $ps_field field name * @param string $ps_mimetype optional mimetype restriction * @return array list of available media versions */ public function getMediaVersions($ps_field, $ps_mimetype="") { if (!$ps_mimetype) { # figure out mimetype from field content $va_media_desc = $this->get($ps_field); if (is_array($va_media_desc)) { unset($va_media_desc["ORIGINAL_FILENAME"]); unset($va_media_desc["INPUT"]); unset($va_media_desc["VOLUME"]); return array_keys($va_media_desc); } } else { $o_media_proc_settings = new MediaProcessingSettings($this, $ps_field); if ($vs_media_type = $o_media_proc_settings->canAccept($ps_mimetype)) { $va_version_list = $o_media_proc_settings->getMediaTypeVersions($vs_media_type); if (is_array($va_version_list)) { return array_keys($va_version_list); } } } return array(); } /** * Checks if a media version for the given field exists. * * @param string $ps_field field name * @param string $ps_version string representation of the version you are asking for * @return bool */ public function hasMediaVersion($ps_field, $ps_version) { return in_array($ps_version, $this->getMediaVersions($ps_field)); } /** * Fetches processing settings information for the given field with respect to the given mimetype * * @param string $ps_field field name * @param string $ps_mimetype mimetype * @return array containing the information defined in media_processing.conf */ public function &getMediaTypeInfo($ps_field, $ps_mimetype="") { $o_media_proc_settings = new MediaProcessingSettings($this, $ps_field); if (!$ps_mimetype) { # figure out mimetype from field content $va_media_desc = $this->get($ps_field); if ($vs_media_type = $o_media_proc_settings->canAccept($media_desc["INPUT"]["MIMETYPE"])) { return $o_media_proc_settings->getMediaTypeInfo($vs_media_type); } } else { if ($vs_media_type = $o_media_proc_settings->canAccept($ps_mimetype)) { return $o_media_proc_settings->getMediaTypeInfo($vs_media_type); } } return null; } /** * Sets media information * * @param $field field name * @param array $info * @return bool success state */ public function setMediaInfo($field, $info) { if(($this->getFieldInfo($field,"FIELD_TYPE")) == FT_MEDIA) { $this->_FIELD_VALUES[$field] = $info; $this->_FIELD_VALUE_CHANGED[$field] = 1; return true; } return false; } /** * Clear media * * @param string $field field name * @return bool always true */ public function clearMedia($field) { $this->_FILES_CLEAR[$field] = 1; $this->_FIELD_VALUE_CHANGED[$field] = 1; return true; } /** * Generate name for media file representation. * Makes the application die if you try to call this on a BaseModel object not representing an actual db row. * * @access private * @param string $field * @return string the media name */ public function _genMediaName($field) { $pk = $this->getPrimaryKey(); if ($pk) { return $this->TABLE."_".$field."_".$pk; } else { die("NO PK TO MAKE media name for $field!"); } } /** * Removes media * * @access private * @param string $ps_field field name * @param string $ps_version string representation of the version (e.g. original) * @param string $ps_dont_delete_path * @param string $ps_dont_delete extension * @return null */ public function _removeMedia($ps_field, $ps_version, $ps_dont_delete_path="", $ps_dont_delete_extension="") { global $AUTH_CURRENT_USER_ID; $va_media_info = $this->getMediaInfo($ps_field,$ps_version); if (!$va_media_info) { return true; } $vs_volume = $va_media_info["VOLUME"]; $va_volume_info = $this->_MEDIA_VOLUMES->getVolumeInformation($vs_volume); # # Get list of media files to delete # $va_files_to_delete = array(); $vs_delete_path = $va_volume_info["absolutePath"]."/".$va_media_info["HASH"]."/".$va_media_info["MAGIC"]."_".$va_media_info["FILENAME"]; if (($va_media_info["FILENAME"]) && ($vs_delete_path != $ps_dont_delete_path.".".$ps_dont_delete_extension)) { $va_files_to_delete[] = $va_media_info["MAGIC"]."_".$va_media_info["FILENAME"]; @unlink($vs_delete_path); } # if media is mirrored, delete file off of mirrored server if (is_array($va_volume_info["mirrors"]) && sizeof($va_volume_info["mirrors"]) > 0) { $o_tq = new TaskQueue(); $vs_row_key = join("/", array($this->tableName(), $this->getPrimaryKey())); $vs_entity_key = join("/", array($this->tableName(), $ps_field, $this->getPrimaryKey(), $ps_version)); if (!($o_tq->cancelPendingTasksForEntity($vs_entity_key))) { $this->postError(560, _t("Could not cancel pending tasks: %1", $this->error),"BaseModel->_removeMedia()"); return false; } foreach ($va_volume_info["mirrors"] as $vs_mirror_code => $va_mirror_info) { $vs_mirror_method = $va_mirror_info["method"]; $vs_queue = $vs_mirror_method."mirror"; if (!($o_tq->cancelPendingTasksForEntity($vs_entity_key))) { $this->postError(560, _t("Could not cancel pending tasks: %1", $this->error),"BaseModel->_removeMedia()"); return false; } $va_tq_filelist = array(); foreach($va_files_to_delete as $vs_filename) { $va_tq_filelist[] = array( "HASH" => $va_media_info["HASH"], "FILENAME" => $vs_filename ); } if ($o_tq->addTask( $vs_queue, array( "MIRROR" => $vs_mirror_code, "VOLUME" => $vs_volume, "FIELD" => $f, "TABLE" => $this->tableName(), "DELETE" => 1, "VERSION" => $ps_version, "FILES" => $va_tq_filelist, "MIRROR_INFO" => $va_mirror_info, "PK" => $this->primaryKey(), "PK_VAL" => $this->getPrimaryKey() ), array("priority" => 50, "entity_key" => $vs_entity_key, "row_key" => $vs_row_key, 'user_id' => $AUTH_CURRENT_USER_ID))) { continue; } else { $this->postError(100, _t("Couldn't queue mirror using '%1' for version '%2' (handler '%3')", $vs_mirror_method, $v, $queue),"BaseModel->_removeMedia()"); } } } } /** * perform media processing for the given field if sth. has been uploaded * * @access private * @param string $ps_field field name * @param array options * * Supported options: * delete_old_media = set to zero to prevent that old media files are deleted; defaults to 1 * these_versions_only = if set to an array of valid version names, then only the specified versions are updated with the currently updated file; ignored if no media already exists */ public function _processMedia($ps_field, $pa_options=null) { global $AUTH_CURRENT_USER_ID; if(!is_array($pa_options)) { $pa_options = array(); } if(!isset($pa_options['delete_old_media'])) { $pa_options['delete_old_media'] = true; } if(!isset($pa_options['these_versions_only'])) { $pa_options['these_versions_only'] = null; } $vs_sql = ""; $vn_max_execution_time = ini_get('max_execution_time'); set_time_limit(7200); $o_tq = new TaskQueue(); $o_media_proc_settings = new MediaProcessingSettings($this, $ps_field); # only set file if something was uploaded # (ie. don't nuke an existing file because none # was uploaded) $va_field_info = $this->getFieldInfo($ps_field); if ((isset($this->_FILES_CLEAR[$ps_field])) && ($this->_FILES_CLEAR[$ps_field])) { // // Clear files // $va_versions = $this->getMediaVersions($ps_field); #--- delete files foreach ($va_versions as $v) { $this->_removeMedia($ps_field, $v); } $this->_FILES[$ps_field] = null; $this->_FIELD_VALUES[$ps_field] = null; $vs_sql = "{$ps_field} = ".$this->quote(caSerializeForDatabase($this->_FILES[$ps_field], true)).","; } else { // // Process incoming files // $m = new Media(); // is it a URL? $vs_url_fetched_from = null; $vn_url_fetched_on = null; $vb_allow_fetching_of_urls = (bool)$this->_CONFIG->get('allow_fetching_of_media_from_remote_urls'); $vb_is_fetched_file = false; if ($vb_allow_fetching_of_urls && (bool)ini_get('allow_url_fopen') && isURL($this->_SET_FILES[$ps_field]['tmp_name'])) { $vs_tmp_file = tempnam(__CA_APP_DIR__.'/tmp', 'caUrlCopy'); $r_incoming_fp = @fopen($this->_SET_FILES[$ps_field]['tmp_name'], 'r'); if (!$r_incoming_fp) { $this->postError(1600, _t('Cannot open remote URL [%1] to fetch media', $this->_SET_FILES[$ps_field]['tmp_name']),"BaseModel->_processMedia()"); set_time_limit($vn_max_execution_time); return false; } $r_outgoing_fp = fopen($vs_tmp_file, 'w'); if (!$r_outgoing_fp) { $this->postError(1600, _t('Cannot open file for media fetched from URL [%1]', $this->_SET_FILES[$ps_field]['tmp_name']),"BaseModel->_processMedia()"); set_time_limit($vn_max_execution_time); return false; } while(($vs_content = fgets($r_incoming_fp, 4096)) !== false) { fwrite($r_outgoing_fp, $vs_content); } fclose($r_incoming_fp); fclose($r_outgoing_fp); $vs_url_fetched_from = $this->_SET_FILES[$ps_field]['tmp_name']; $vn_url_fetched_on = time(); $this->_SET_FILES[$ps_field]['tmp_name'] = $vs_tmp_file; $vb_is_fetched_file = true; } if (isset($this->_SET_FILES[$ps_field]['tmp_name']) && (file_exists($this->_SET_FILES[$ps_field]['tmp_name']))) { // ImageMagick partly relies on file extensions to properly identify images (RAW images in particular) // therefore we rename the temporary file here (using the extension of the original filename, if any) $va_matches = array(); $vb_renamed_tmpfile = false; preg_match("/[.]*\.([a-zA-Z0-9]+)$/",$this->_SET_FILES[$ps_field]['tmp_name'],$va_matches); if(!isset($va_matches[1])){ // file has no extension, i.e. is probably PHP upload tmp file $va_matches = array(); preg_match("/[.]*\.([a-zA-Z0-9]+)$/",$this->_SET_FILES[$ps_field]['original_filename'],$va_matches); if(strlen($va_matches[1])>0){ $va_parts = explode("/",$this->_SET_FILES[$ps_field]['tmp_name']); $vs_new_filename = sys_get_temp_dir()."/".$va_parts[sizeof($va_parts)-1].".".$va_matches[1]; if (!move_uploaded_file($this->_SET_FILES[$ps_field]['tmp_name'],$vs_new_filename)) { rename($this->_SET_FILES[$ps_field]['tmp_name'],$vs_new_filename); } $this->_SET_FILES[$ps_field]['tmp_name'] = $vs_new_filename; $vb_renamed_tmpfile = true; } } $input_mimetype = $m->divineFileFormat($this->_SET_FILES[$ps_field]['tmp_name']); if (!$input_type = $o_media_proc_settings->canAccept($input_mimetype)) { # error - filetype not accepted by this field $this->postError(1600, ($input_mimetype) ? _t("File type %1 not accepted by %2", $input_mimetype, $ps_field) : _t("Unknown file type not accepted by %1", $ps_field),"BaseModel->_processMedia()"); set_time_limit($vn_max_execution_time); if ($vb_is_fetched_file) { @unlink($vs_tmp_file); } return false; } # ok process file... if (!($m->read($this->_SET_FILES[$ps_field]['tmp_name']))) { $this->errors = array_merge($this->errors, $m->errors()); // copy into model plugin errors //$this->postError(1600, _t("File for %1 could not be read", $ps_field),"BaseModel->_processMedia()"); set_time_limit($vn_max_execution_time); if ($vb_is_fetched_file) { @unlink($vs_tmp_file); } return false; } $media_desc = array( "ORIGINAL_FILENAME" => $this->_SET_FILES[$ps_field]['original_filename'], "INPUT" => array( "MIMETYPE" => $m->get("mimetype"), "WIDTH" => $m->get("width"), "HEIGHT" => $m->get("height"), "MD5" => md5_file($this->_SET_FILES[$ps_field]['tmp_name']), "FILESIZE" => filesize($this->_SET_FILES[$ps_field]['tmp_name']), "FETCHED_FROM" => $vs_url_fetched_from, "FETCHED_ON" => $vn_url_fetched_on ) ); # # Extract metadata from file # $media_metadata = $m->getExtractedMetadata(); # get versions to create $va_versions = $this->getMediaVersions($ps_field, $input_mimetype); $error = 0; # don't process files that are not going to be processed or converted # we don't want to waste time opening file we're not going to do anything with # also, we don't want to recompress JPEGs... $media_type = $o_media_proc_settings->canAccept($input_mimetype); $version_info = $o_media_proc_settings->getMediaTypeVersions($media_type); $va_default_queue_settings = $o_media_proc_settings->getMediaTypeQueueSettings($media_type); if (!($va_media_write_options = $this->_FILES[$ps_field]['options'])) { $va_media_write_options = $this->_SET_FILES[$ps_field]['options']; } $va_process_these_versions_only = array(); if (isset($pa_options['these_versions_only']) && is_array($pa_options['these_versions_only']) && sizeof($pa_options['these_versions_only'])) { $va_tmp = $this->_FIELD_VALUES[$ps_field]; foreach($pa_options['these_versions_only'] as $vs_this_version_only) { if (in_array($vs_this_version_only, $va_versions)) { if (is_array($this->_FIELD_VALUES[$ps_field])) { $va_process_these_versions_only[] = $vs_this_version_only; } } } // Copy metadata for version we're not processing if (sizeof($va_process_these_versions_only)) { foreach (array_keys($va_tmp) as $v) { if (!in_array($v, $va_process_these_versions_only)) { $media_desc[$v] = $va_tmp[$v]; } } } } $va_files_to_delete = array(); $va_queued_versions = array(); $queue_enabled = (!sizeof($va_process_these_versions_only) && $this->getAppConfig()->get('queue_enabled')) ? true : false; $vs_path_to_queue_media = null; foreach ($va_versions as $v) { if (sizeof($va_process_these_versions_only) && (!in_array($v, $va_process_these_versions_only))) { // only processing certain versions... and this one isn't it so skip continue; } $queue = $va_default_queue_settings['QUEUE']; $queue_threshold = isset($version_info[$v]['QUEUE_WHEN_FILE_LARGER_THAN']) ? intval($version_info[$v]['QUEUE_WHEN_FILE_LARGER_THAN']) : (int)$va_default_queue_settings['QUEUE_WHEN_FILE_LARGER_THAN']; $rule = isset($version_info[$v]['RULE']) ? $version_info[$v]['RULE'] : ''; $volume = isset($version_info[$v]['VOLUME']) ? $version_info[$v]['VOLUME'] : ''; # get volume $vi = $this->_MEDIA_VOLUMES->getVolumeInformation($volume); if (!is_array($vi)) { print "Invalid volume '{$volume}'<br>"; exit; } // Send to queue it it's too big to process here if (($queue_enabled) && ($queue) && ($queue_threshold > 0) && ($queue_threshold < (int)$media_desc["INPUT"]["FILESIZE"]) && ($va_default_queue_settings['QUEUE_USING_VERSION'] != $v)) { $va_queued_versions[$v] = array( 'VOLUME' => $volume ); $media_desc[$v]["QUEUED"] = $queue; if ($version_info[$v]["QUEUED_MESSAGE"]) { $media_desc[$v]["QUEUED_MESSAGE"] = $version_info[$v]["QUEUED_MESSAGE"]; } else { $media_desc[$v]["QUEUED_MESSAGE"] = ($va_default_queue_settings['QUEUED_MESSAGE']) ? $va_default_queue_settings['QUEUED_MESSAGE'] : _t("Media is being processed and will be available shortly."); } if ($pa_options['delete_old_media']) { $va_files_to_delete[] = array( 'field' => $ps_field, 'version' => $v ); } continue; } # get transformation rules $rules = $o_media_proc_settings->getMediaTransformationRule($rule); if (sizeof($rules) == 0) { $output_mimetype = $input_mimetype; $m->set("version", $v); # # don't process this media, just copy the file # $ext = $m->mimetype2extension($output_mimetype); if (!$ext) { $this->postError(1600, _t("File could not be copied for %1; can't convert mimetype '%2' to extension", $ps_field, $output_mimetype),"BaseModel->_processMedia()"); $m->cleanup(); set_time_limit($vn_max_execution_time); if ($vb_is_fetched_file) { @unlink($vs_tmp_file); } return false; } if (($dirhash = $this->_getDirectoryHash($vi["absolutePath"], $this->getPrimaryKey())) === false) { $this->postError(1600, _t("Could not create subdirectory for uploaded file in %1. Please ask your administrator to check the permissions of your media directory.", $vi["absolutePath"]),"BaseModel->_processMedia()"); set_time_limit($vn_max_execution_time); if ($vb_is_fetched_file) { @unlink($vs_tmp_file); } return false; } if ((bool)$version_info[$v]["USE_EXTERNAL_URL_WHEN_AVAILABLE"]) { $filepath = $this->_SET_FILES[$ps_field]['tmp_name']; if ($pa_options['delete_old_media']) { $va_files_to_delete[] = array( 'field' => $ps_field, 'version' => $v ); } $media_desc[$v] = array( "VOLUME" => $volume, "MIMETYPE" => $output_mimetype, "WIDTH" => $m->get("width"), "HEIGHT" => $m->get("height"), "PROPERTIES" => $m->getProperties(), "EXTERNAL_URL" => $media_desc['INPUT']['FETCHED_FROM'], "FILENAME" => null, "HASH" => null, "MAGIC" => null, "EXTENSION" => $ext, "MD5" => md5_file($filepath) ); } else { $magic = rand(0,99999); $filepath = $vi["absolutePath"]."/".$dirhash."/".$magic."_".$this->_genMediaName($ps_field)."_".$v.".".$ext; if (!copy($this->_SET_FILES[$ps_field]['tmp_name'], $filepath)) { $this->postError(1600, _t("File could not be copied. Ask your administrator to check permissions and file space for %1",$vi["absolutePath"]),"BaseModel->_processMedia()"); $m->cleanup(); set_time_limit($vn_max_execution_time); if ($vb_is_fetched_file) { @unlink($vs_tmp_file); } return false; } if ($v === $va_default_queue_settings['QUEUE_USING_VERSION']) { $vs_path_to_queue_media = $filepath; } if ($pa_options['delete_old_media']) { $va_files_to_delete[] = array( 'field' => $ps_field, 'version' => $v, 'dont_delete_path' => $vi["absolutePath"]."/".$dirhash."/".$magic."_".$this->_genMediaName($ps_field)."_".$v, 'dont_delete_extension' => $ext ); } if (is_array($vi["mirrors"]) && sizeof($vi["mirrors"]) > 0) { $vs_entity_key = join("/", array($this->tableName(), $ps_field, $this->getPrimaryKey(), $v)); $vs_row_key = join("/", array($this->tableName(), $this->getPrimaryKey())); foreach ($vi["mirrors"] as $vs_mirror_code => $va_mirror_info) { $vs_mirror_method = $va_mirror_info["method"]; $vs_queue = $vs_mirror_method."mirror"; if (!($o_tq->cancelPendingTasksForEntity($vs_entity_key))) { //$this->postError(560, _t("Could not cancel pending tasks: %1", $this->error),"BaseModel->_processMedia()"); //$m->cleanup(); //return false; } if ($o_tq->addTask( $vs_queue, array( "MIRROR" => $vs_mirror_code, "VOLUME" => $volume, "FIELD" => $ps_field, "TABLE" => $this->tableName(), "VERSION" => $v, "FILES" => array( array( "FILE_PATH" => $filepath, "ABS_PATH" => $vi["absolutePath"], "HASH" => $dirhash, "FILENAME" => $magic."_".$this->_genMediaName($ps_field)."_".$v.".".$ext ) ), "MIRROR_INFO" => $va_mirror_info, "PK" => $this->primaryKey(), "PK_VAL" => $this->getPrimaryKey() ), array("priority" => 100, "entity_key" => $vs_entity_key, "row_key" => $vs_row_key, 'user_id' => $AUTH_CURRENT_USER_ID))) { continue; } else { $this->postError(100, _t("Couldn't queue mirror using '%1' for version '%2' (handler '%3')", $vs_mirror_method, $v, $queue),"BaseModel->_processMedia()"); } } } $media_desc[$v] = array( "VOLUME" => $volume, "MIMETYPE" => $output_mimetype, "WIDTH" => $m->get("width"), "HEIGHT" => $m->get("height"), "PROPERTIES" => $m->getProperties(), "FILENAME" => $this->_genMediaName($ps_field)."_".$v.".".$ext, "HASH" => $dirhash, "MAGIC" => $magic, "EXTENSION" => $ext, "MD5" => md5_file($filepath) ); } } else { $m->set("version", $v); while(list($operation, $parameters) = each($rules)) { if ($operation === 'SET') { foreach($parameters as $pp => $pv) { if ($pp == 'format') { $output_mimetype = $pv; } else { $m->set($pp, $pv); } } } else { if (!($m->transform($operation, $parameters))) { $error = 1; $error_msg = "Couldn't do transformation '$operation'"; break(2); } } } if (!$output_mimetype) { $output_mimetype = $input_mimetype; } if (!($ext = $m->mimetype2extension($output_mimetype))) { $this->postError(1600, _t("File could not be processed for %1; can't convert mimetype '%2' to extension", $ps_field, $output_mimetype),"BaseModel->_processMedia()"); $m->cleanup(); set_time_limit($vn_max_execution_time); if ($vb_is_fetched_file) { @unlink($vs_tmp_file); } return false; } if (($dirhash = $this->_getDirectoryHash($vi["absolutePath"], $this->getPrimaryKey())) === false) { $this->postError(1600, _t("Could not create subdirectory for uploaded file in %1. Please ask your administrator to check the permissions of your media directory.", $vi["absolutePath"]),"BaseModel->_processMedia()"); set_time_limit($vn_max_execution_time); if ($vb_is_fetched_file) { @unlink($vs_tmp_file); } return false; } $magic = rand(0,99999); $filepath = $vi["absolutePath"]."/".$dirhash."/".$magic."_".$this->_genMediaName($ps_field)."_".$v; $va_output_files = array(); if (!($vs_output_file = $m->write($filepath, $output_mimetype, $va_media_write_options))) { $this->postError(1600,_t("Couldn't write file: %1", join("; ", $m->getErrors())),"BaseModel->_processMedia()"); $m->cleanup(); set_time_limit($vn_max_execution_time); if ($vb_is_fetched_file) { @unlink($vs_tmp_file); } return false; break; } else { $va_output_files[] = $vs_output_file; } if ($v === $va_default_queue_settings['QUEUE_USING_VERSION']) { $vs_path_to_queue_media = $vs_output_file; } if (($pa_options['delete_old_media']) && (!$error)) { if($vs_old_media_path = $this->getMediaPath($ps_field, $v)) { $va_files_to_delete[] = array( 'field' => $ps_field, 'version' => $v, 'dont_delete_path' => $filepath, 'dont_delete_extension' => $ext ); } } if (is_array($vi["mirrors"]) && sizeof($vi["mirrors"]) > 0) { $vs_entity_key = join("/", array($this->tableName(), $ps_field, $this->getPrimaryKey(), $v)); $vs_row_key = join("/", array($this->tableName(), $this->getPrimaryKey())); foreach ($vi["mirrors"] as $vs_mirror_code => $va_mirror_info) { $vs_mirror_method = $va_mirror_info["method"]; $vs_queue = $vs_mirror_method."mirror"; if (!($o_tq->cancelPendingTasksForEntity($vs_entity_key))) { //$this->postError(560, _t("Could not cancel pending tasks: %1", $this->error),"BaseModel->_processMedia()"); //$m->cleanup(); //return false; } if ($o_tq->addTask( $vs_queue, array( "MIRROR" => $vs_mirror_code, "VOLUME" => $volume, "FIELD" => $ps_field, "TABLE" => $this->tableName(), "VERSION" => $v, "FILES" => array( array( "FILE_PATH" => $filepath.".".$ext, "ABS_PATH" => $vi["absolutePath"], "HASH" => $dirhash, "FILENAME" => $magic."_".$this->_genMediaName($ps_field)."_".$v.".".$ext ) ), "MIRROR_INFO" => $va_mirror_info, "PK" => $this->primaryKey(), "PK_VAL" => $this->getPrimaryKey() ), array("priority" => 100, "entity_key" => $vs_entity_key, "row_key" => $vs_row_key, 'user_id' => $AUTH_CURRENT_USER_ID))) { continue; } else { $this->postError(100, _t("Couldn't queue mirror using '%1' for version '%2' (handler '%3')", $vs_mirror_method, $v, $queue),"BaseModel->_processMedia()"); } } } $media_desc[$v] = array( "VOLUME" => $volume, "MIMETYPE" => $output_mimetype, "WIDTH" => $m->get("width"), "HEIGHT" => $m->get("height"), "PROPERTIES" => $m->getProperties(), "FILENAME" => $this->_genMediaName($ps_field)."_".$v.".".$ext, "HASH" => $dirhash, "MAGIC" => $magic, "EXTENSION" => $ext, "MD5" => md5_file($vi["absolutePath"]."/".$dirhash."/".$magic."_".$this->_genMediaName($ps_field)."_".$v.".".$ext) ); $m->reset(); } } if (sizeof($va_queued_versions)) { $vs_entity_key = md5(join("/", array_merge(array($this->tableName(), $ps_field, $this->getPrimaryKey()), array_keys($va_queued_versions)))); $vs_row_key = join("/", array($this->tableName(), $this->getPrimaryKey())); if (!($o_tq->cancelPendingTasksForEntity($vs_entity_key, $queue))) { // TODO: log this } if (!($filename = $vs_path_to_queue_media)) { // if we're not using a designated not-queued representation to generate the queued ones // then copy the uploaded file to the tmp dir and use that $filename = $o_tq->copyFileToQueueTmp($va_default_queue_settings['QUEUE'], $this->_SET_FILES[$ps_field]['tmp_name']); } if ($filename) { if ($o_tq->addTask( $va_default_queue_settings['QUEUE'], array( "TABLE" => $this->tableName(), "FIELD" => $ps_field, "PK" => $this->primaryKey(), "PK_VAL" => $this->getPrimaryKey(), "INPUT_MIMETYPE" => $input_mimetype, "FILENAME" => $filename, "VERSIONS" => $va_queued_versions, "OPTIONS" => $va_media_write_options, "DONT_DELETE_OLD_MEDIA" => ($filename == $vs_path_to_queue_media) ? true : false ), array("priority" => 100, "entity_key" => $vs_entity_key, "row_key" => $vs_row_key, 'user_id' => $AUTH_CURRENT_USER_ID))) { if ($pa_options['delete_old_media']) { foreach($va_queued_versions as $vs_version => $va_version_info) { $va_files_to_delete[] = array( 'field' => $ps_field, 'version' => $vs_version ); } } } else { $this->postError(100, _t("Couldn't queue processing for version '%1' using handler '%2'", !$v, $queue),"BaseModel->_processMedia()"); } } else { $this->errors = $o_tq->errors; } } else { // Generate preview frames for media that support that (Eg. video) // and add them as "multifiles" assuming the current model supports that (ca_object_representations does) if (!sizeof($va_process_these_versions_only) && ((bool)$this->_CONFIG->get('video_preview_generate_frames') || (bool)$this->_CONFIG->get('document_preview_generate_pages')) && method_exists($this, 'addFile')) { $va_preview_frame_list = $m->writePreviews( array( 'width' => $m->get("width"), 'height' => $m->get("height"), 'minNumberOfFrames' => $this->_CONFIG->get('video_preview_min_number_of_frames'), 'maxNumberOfFrames' => $this->_CONFIG->get('video_preview_max_number_of_frames'), 'numberOfPages' => $this->_CONFIG->get('document_preview_max_number_of_pages'), 'frameInterval' => $this->_CONFIG->get('video_preview_interval_between_frames'), 'pageInterval' => $this->_CONFIG->get('document_preview_interval_between_pages'), 'startAtTime' => $this->_CONFIG->get('video_preview_start_at'), 'endAtTime' => $this->_CONFIG->get('video_preview_end_at'), 'startAtPage' => $this->_CONFIG->get('document_preview_start_page'), 'outputDirectory' => __CA_APP_DIR__.'/tmp' ) ); $this->removeAllFiles(); // get rid of any previously existing frames (they might be hanging around if we're editing an existing record) if (is_array($va_preview_frame_list)) { foreach($va_preview_frame_list as $vn_time => $vs_frame) { $this->addFile($vs_frame, $vn_time, true); // the resource path for each frame is it's time, in seconds (may be fractional) for video, or page number for documents @unlink($vs_frame); // clean up tmp preview frame file } } } } if (!$error) { # # --- Clean up old media from versions that are not supported in the new media # if ($pa_options['delete_old_media']) { foreach ($this->getMediaVersions($ps_field) as $old_version) { if (!is_array($media_desc[$old_version])) { $this->_removeMedia($ps_field, $old_version); } } } foreach($va_files_to_delete as $va_file_to_delete) { $this->_removeMedia($va_file_to_delete['field'], $va_file_to_delete['version'], $va_file_to_delete['dont_delete_path'], $va_file_to_delete['dont_delete_extension']); } $this->_FILES[$ps_field] = $media_desc; $this->_FIELD_VALUES[$ps_field] = $media_desc; $vs_serialized_data = caSerializeForDatabase($this->_FILES[$ps_field], true); $vs_sql = "$ps_field = ".$this->quote($vs_serialized_data).","; if (($vs_metadata_field_name = $o_media_proc_settings->getMetadataFieldName()) && $this->hasField($vs_metadata_field_name)) { $this->set($vs_metadata_field_name, $media_metadata); $vs_sql .= " ".$vs_metadata_field_name." = ".$this->quote(caSerializeForDatabase($media_metadata, true)).","; } if (($vs_content_field_name = $o_media_proc_settings->getMetadataContentName()) && $this->hasField($vs_content_field_name)) { $this->_FIELD_VALUES[$vs_content_field_name] = $this->quote($m->getExtractedText()); $vs_sql .= " ".$vs_content_field_name." = ".$this->_FIELD_VALUES[$vs_content_field_name].","; } } else { # error - invalid media $this->postError(1600, _t("File could not be processed for %1: %2", $ps_field, $error_msg),"BaseModel->_processMedia()"); # return false; } $m->cleanup(); if($vb_renamed_tmpfile){ @unlink($this->_SET_FILES[$ps_field]['tmp_name']); } } else { if(is_array($this->_FIELD_VALUES[$ps_field])) { $this->_FILES[$ps_field] = $this->_FIELD_VALUES[$ps_field]; $vs_sql = "$ps_field = ".$this->quote(caSerializeForDatabase($this->_FILES[$ps_field], true)).","; } } $this->_SET_FILES[$ps_field] = null; } set_time_limit($vn_max_execution_time); if ($vb_is_fetched_file) { @unlink($vs_tmp_file); } return $vs_sql; } # -------------------------------------------------------------------------------- /** * Fetches hash directory * * @access private * @param string $basepath path * @param int $id identifier * @return string directory */ public function _getDirectoryHash ($basepath, $id) { $n = intval($id / 100); $dirs = array(); $l = strlen($n); for($i=0;$i<$l; $i++) { $dirs[] = substr($n,$i,1); if (!file_exists($basepath."/".join("/", $dirs))) { if (!@mkdir($basepath."/".join("/", $dirs))) { return false; } } } return join("/", $dirs); } # -------------------------------------------------------------------------------- # --- Uploaded file handling # -------------------------------------------------------------------------------- /** * Returns url of file * * @access public * @param $field field name * @return string file url */ public function getFileUrl($ps_field) { $va_file_info = $this->get($ps_field); if (!is_array($va_file_info)) { return null; } $va_volume_info = $this->_FILE_VOLUMES->getVolumeInformation($va_file_info["VOLUME"]); if (!is_array($va_volume_info)) { return null; } $vs_protocol = $va_volume_info["protocol"]; $vs_host = $va_volume_info["hostname"]; $vs_path = join("/",array($va_volume_info["urlPath"], $va_file_info["HASH"], $va_file_info["MAGIC"]."_".$va_file_info["FILENAME"])); return $va_file_info["FILENAME"] ? "{$vs_protocol}://{$vs_host}.{$vs_path}" : ""; } # -------------------------------------------------------------------------------- /** * Returns path of file * * @access public * @param string $field field name * @return string path in local filesystem */ public function getFilePath($ps_field) { $va_file_info = $this->get($ps_field); if (!is_array($va_file_info)) { return null; } $va_volume_info = $this->_FILE_VOLUMES->getVolumeInformation($va_file_info["VOLUME"]); if (!is_array($va_volume_info)) { return null; } return join("/",array($va_volume_info["absolutePath"], $va_file_info["HASH"], $va_file_info["MAGIC"]."_".$va_file_info["FILENAME"])); } # -------------------------------------------------------------------------------- /** * Wrapper around BaseModel::get(), used to fetch information about files * * @access public * @param string $field field name * @return array file information */ public function &getFileInfo($ps_field) { $va_file_info = $this->get($ps_field); if (!is_array($va_file_info)) { return null; } return $va_file_info; } # -------------------------------------------------------------------------------- /** * Clear file * * @access public * @param string $field field name * @return bool always true */ public function clearFile($ps_field) { $this->_FILES_CLEAR[$ps_field] = 1; $this->_FIELD_VALUE_CHANGED[$ps_field] = 1; return true; } # -------------------------------------------------------------------------------- /** * Returns list of mimetypes of available conversions of files * * @access public * @param string $ps_field field name * @return array */ public function getFileConversions($ps_field) { $va_info = $this->getFileInfo($ps_field); if (!is_array($va_info["CONVERSIONS"])) { return array(); } return $va_info["CONVERSIONS"]; } # -------------------------------------------------------------------------------- /** * Returns file path to converted version of file * * @access public * @param string $ps_field field name * @param string $ps_format format of the converted version * @return string file path */ public function getFileConversionPath($ps_field, $ps_format) { $va_info = $this->getFileInfo($ps_field); if (!is_array($va_info)) { return ""; } $vi = $this->_FILE_VOLUMES->getVolumeInformation($va_info["VOLUME"]); if (!is_array($vi)) { return ""; } $va_conversions = $this->getFileConversions($ps_field); if ($va_conversions[$ps_format]) { return join("/",array($vi["absolutePath"], $va_info["HASH"], $va_info["MAGIC"]."_".$va_conversions[$ps_format]["FILENAME"])); } else { return ""; } } # -------------------------------------------------------------------------------- /** * Returns url to converted version of file * * @access public * @param string $ps_field field name * @param string $ps_format format of the converted version * @return string url */ public function getFileConversionUrl($ps_field, $ps_format) { $va_info = $this->getFileInfo($ps_field); if (!is_array($va_info)) { return ""; } $vi = $this->_FILE_VOLUMES->getVolumeInformation($va_info["VOLUME"]); if (!is_array($vi)) { return ""; } $va_conversions = $this->getFileConversions($ps_field); if ($va_conversions[$ps_format]) { return $vi["protocol"]."://".join("/", array($vi["hostname"], $vi["urlPath"], $va_info["HASH"], $va_info["MAGIC"]."_".$va_conversions[$ps_format]["FILENAME"])); } else { return ""; } } # ------------------------------------------------------------------------------- /** * Generates filenames as follows: <table>_<field>_<primary_key> * Makes the application die if no record is loaded * * @access private * @param string $field field name * @return string file name */ public function _genFileName($field) { $pk = $this->getPrimaryKey(); if ($pk) { return $this->TABLE."_".$field."_".$pk; } else { die("NO PK TO MAKE file name for $field!"); } } # -------------------------------------------------------------------------------- /** * Processes uploaded files (only if something was uploaded) * * @access private * @param string $field field name * @return string */ public function _processFiles($field) { $vs_sql = ""; # only set file if something was uploaded # (ie. don't nuke an existing file because none # was uploaded) if ((isset($this->_FILES_CLEAR[$field])) && ($this->_FILES_CLEAR[$field])) { #--- delete file @unlink($this->getFilePath($field)); #--- delete conversions # # TODO: wvWWare MSWord conversion to HTML generates untracked graphics files for embedded images... they are currently # *not* deleted when the file and associated conversions are deleted. We will need to parse the HTML to derive the names # of these files... # foreach ($this->getFileConversions($field) as $vs_format => $va_file_conversion) { @unlink($this->getFileConversionPath($field, $vs_format)); } $this->_FILES[$field] = ""; $this->_FIELD_VALUES[$field] = ""; $vs_sql = "$field = ".$this->quote(caSerializeForDatabase($this->_FILES[$field], true)).","; } else { $va_field_info = $this->getFieldInfo($field); if ((file_exists($this->_SET_FILES[$field]['tmp_name']))) { $ff = new File(); $mimetype = $ff->divineFileFormat($this->_SET_FILES[$field]['tmp_name'], $this->_SET_FILES[$field]['original_filename']); if (is_array($va_field_info["FILE_FORMATS"]) && sizeof($va_field_info["FILE_FORMATS"]) > 0) { if (!in_array($mimetype, $va_field_info["FILE_FORMATS"])) { $this->postError(1605, _t("File is not a valid format"),"BaseModel->_processFiles()"); return false; } } $vn_dangerous = 0; if (!$mimetype) { $mimetype = "application/octet-stream"; $vn_dangerous = 1; } # get volume $vi = $this->_FILE_VOLUMES->getVolumeInformation($va_field_info["FILE_VOLUME"]); if (!is_array($vi)) { print "Invalid volume ".$va_field_info["FILE_VOLUME"]."<br>"; exit; } $properties = $ff->getProperties(); if ($properties['dangerous'] > 0) { $vn_dangerous = 1; } if (($dirhash = $this->_getDirectoryHash($vi["absolutePath"], $this->getPrimaryKey())) === false) { $this->postError(1600, _t("Could not create subdirectory for uploaded file in %1. Please ask your administrator to check the permissions of your media directory.", $vi["absolutePath"]),"BaseModel->_processFiles()"); return false; } $magic = rand(0,99999); $va_pieces = explode("/", $this->_SET_FILES[$field]['original_filename']); $ext = array_pop($va_tmp = explode(".", array_pop($va_pieces))); if ($properties["dangerous"]) { $ext .= ".bin"; } if (!$ext) $ext = "bin"; $filestem = $vi["absolutePath"]."/".$dirhash."/".$magic."_".$this->_genMediaName($field); $filepath = $filestem.".".$ext; $filesize = isset($properties["filesize"]) ? $properties["filesize"] : 0; if (!$filesize) { $properties["filesize"] = filesize($this->_SET_FILES[$field]['tmp_name']); } $file_desc = array( "FILE" => 1, # signifies is file "VOLUME" => $va_field_info["FILE_VOLUME"], "ORIGINAL_FILENAME" => $this->_SET_FILES[$field]['original_filename'], "MIMETYPE" => $mimetype, "FILENAME" => $this->_genMediaName($field).".".$ext, "HASH" => $dirhash, "MAGIC" => $magic, "PROPERTIES" => $properties, "DANGEROUS" => $vn_dangerous, "CONVERSIONS" => array(), "MD5" => md5_file($this->_SET_FILES[$field]['tmp_name']) ); if (!copy($this->_SET_FILES[$field]['tmp_name'], $filepath)) { $this->postError(1600, _t("File could not be copied. Ask your administrator to check permissions and file space for %1",$vi["absolutePath"]),"BaseModel->_processFiles()"); return false; } # -- delete old file if its name is different from the one we just wrote (otherwise, we overwrote it) if ($filepath != $this->getFilePath($field)) { @unlink($this->getFilePath($field)); } # # -- Attempt to do file conversions # if (isset($va_field_info["FILE_CONVERSIONS"]) && is_array($va_field_info["FILE_CONVERSIONS"]) && (sizeof($va_field_info["FILE_CONVERSIONS"]) > 0)) { foreach($va_field_info["FILE_CONVERSIONS"] as $vs_output_format) { if ($va_tmp = $ff->convert($vs_output_format, $filepath,$filestem)) { # new extension is added to end of stem by conversion $vs_file_ext = $va_tmp["extension"]; $vs_format_name = $va_tmp["format_name"]; $vs_long_format_name = $va_tmp["long_format_name"]; $file_desc["CONVERSIONS"][$vs_output_format] = array( "MIMETYPE" => $vs_output_format, "FILENAME" => $this->_genMediaName($field)."_conv.".$vs_file_ext, "PROPERTIES" => array( "filesize" => filesize($filestem."_conv.".$vs_file_ext), "extension" => $vs_file_ext, "format_name" => $vs_format_name, "long_format_name" => $vs_long_format_name ) ); } } } $this->_FILES[$field] = $file_desc; $vs_sql = "$field = ".$this->quote(caSerializeForDatabase($this->_FILES[$field], true)).","; $this->_FIELD_VALUES[$field]= $this->_SET_FILES[$field] = $file_desc; } } return $vs_sql; } # -------------------------------------------------------------------------------- # --- Utilities # -------------------------------------------------------------------------------- /** * Can be called in two ways: * 1. Called with two arguments: returns $val quoted and escaped for use with $field. * That is, it will only quote $val if the field type requires it. * 2. Called with one argument: simply returns $val quoted and escaped. * * @access public * @param string $field field name * @param string $val optional field value */ public function &quote ($field, $val=null) { if (is_null($val)) { # just quote it! $field = "'".$this->escapeForDatabase($field)."'"; return $field;# quote only if field needs it } else { if ($this->_getFieldTypeType($field) == 1) { $val = "'".$this->escapeForDatabase($val)."'"; } return $val; } } # -------------------------------------------------------------------------------- /** * Escapes a string for SQL use * * @access public * @param string $ps_value * @return string */ public function escapeForDatabase ($ps_value) { $o_db = $this->getDb(); return $o_db->escape($ps_value); } # -------------------------------------------------------------------------------- /** * Make copy of BaseModel object with all fields information intact *EXCEPT* for the * primary key value and all media and file fields, all of which are empty. * * @access public * @return BaseModel the copy */ public function &cloneRecord() { $o_clone = $this; $o_clone->set($o_clone->getPrimaryKey(), null); foreach($o_clone->getFields() as $vs_f) { switch($o_clone->getFieldInfo($vs_f, "FIELD_TYPE")) { case FT_MEDIA: $o_clone->_FIELD_VALUES[$vs_f] = ""; break; case FT_FILE: $o_clone->_FIELD_VALUES[$vs_f] = ""; break; } } return $o_clone; } # -------------------------------------------------------------------------------- /** * Clears all fields in object * * @access public */ public function clear () { $this->clearErrors(); foreach($this->FIELDS as $field => $attr) { if (isset($this->FIELDS[$field]['START']) && ($vs_start_fld = $this->FIELDS[$field]['START'])) { unset($this->_FIELD_VALUES[$vs_start_fld]); unset($this->_FIELD_VALUES[$this->FIELDS[$field]['END']]); } unset($this->_FIELD_VALUES[$field]); } } # -------------------------------------------------------------------------------- /** * Prints contents of all fields in object * * @access public */ public function dump () { $this->clearErrors(); reset($this->FIELDS); while (list($field, $attr) = each($this->FIELDS)) { echo "$field = ".$this->_FIELD_VALUES[$field]."<BR>\n"; } } # -------------------------------------------------------------------------------- /** * Returns true if field exists in this object * * @access public * @param string $field field name * @return bool */ public function hasField ($field) { return (isset($this->FIELDS[$field]) && $this->FIELDS[$field]) ? 1 : 0; } # -------------------------------------------------------------------------------- /** * Returns underlying datatype for given field type * 0 = numeric, 1 = string * * @access private * @param string $fieldname * @return int */ public function _getFieldTypeType ($fieldname) { switch($this->FIELDS[$fieldname]["FIELD_TYPE"]) { case (FT_TEXT): case (FT_MEDIA): case (FT_FILE): case (FT_PASSWORD): case (FT_VARS): return 1; break; case (FT_NUMBER): case (FT_TIMESTAMP): case (FT_DATETIME): case (FT_TIME): case (FT_TIMERANGE): case (FT_HISTORIC_DATETIME): case (FT_DATE): case (FT_HISTORIC_DATE): case (FT_DATERANGE): case (FT_TIMECODE): case (FT_HISTORIC_DATERANGE): case (FT_BIT): return 0; break; default: print "Invalid field type in _getFieldTypeType: ". $this->FIELDS[$fieldname]["FIELD_TYPE"]; exit; } } # -------------------------------------------------------------------------------- /** * Fetches the choice list value for a given field * * @access public * @param string $field field name * @param string $value choice list name * @return string */ public function getChoiceListValue($field, $value) { $va_attr = $this->getFieldInfo($field); $va_list = $va_attr["BOUNDS_CHOICE_LIST"]; if (isset($va_attr['LIST']) && $va_attr['LIST']) { $t_list = new ca_lists(); if ($t_list->load(array('list_code' => $va_attr['LIST']))) { $va_items = caExtractValuesByUserLocale($t_list->getItemsForList($va_attr['LIST'])); $va_list = array(); foreach($va_items as $vn_item_id => $va_item_info) { $va_list[$va_item_info['name_singular']] = $va_item_info['item_value']; } } } if ($va_list) { foreach ($va_list as $k => $v) { if ($v == $value) { return $k; } } } else { return; } } # -------------------------------------------------------------------------------- # --- Field input verification # -------------------------------------------------------------------------------- /** * Does bounds checks specified for field $field on value $value. * Returns 0 and throws an exception is it fails, returns 1 on success. * * @access public * @param string $field field name * @param string $value value */ public function verifyFieldValue ($field, $value, &$pb_need_reload) { $pb_need_reload = false; $va_attr = $this->FIELDS[$field]; if (!$va_attr) { $this->postError(716,_t("%1 does not exist", $field),"BaseModel->verifyFieldValue()"); return false; } $data_type = $this->_getFieldTypeType($field); $field_type = $this->getFieldInfo($field,"FIELD_TYPE"); if ((isset($va_attr["FILTER"]) && ($filter = $va_attr["FILTER"]))) { if (!preg_match($filter, $value)) { $this->postError(1102,_t("%1 is invalid", $va_attr["LABEL"]),"BaseModel->verifyFieldValue()"); return false; } } if ($data_type == 0) { # number; check value if (isset($va_attr["BOUNDS_VALUE"][0])) { $min_value = $va_attr["BOUNDS_VALUE"][0]; } if (isset($va_attr["BOUNDS_VALUE"][1])) { $max_value = $va_attr["BOUNDS_VALUE"][1]; } if (!($va_attr["IS_NULL"] && (!$value))) { if ((isset($min_value)) && ($value < $min_value)) { $this->postError(1101,_t("%1 must not be less than %2", $va_attr["LABEL"], $min_value),"BaseModel->verifyFieldValue()"); return false; } if ((isset($max_value)) && ($value > $max_value)) { $this->postError(1101,_t("%1 must not be greater than %2", $va_attr["LABEL"], $max_value),"BaseModel->verifyFieldValue()"); return false; } } } if (!isset($va_attr["IS_NULL"])) { $va_attr["IS_NULL"] = 0; } if (!($va_attr["IS_NULL"] && (!$value))) { # check length if (isset($va_attr["BOUNDS_LENGTH"]) && is_array($va_attr["BOUNDS_LENGTH"])) { $min_length = $va_attr["BOUNDS_LENGTH"][0]; $max_length = $va_attr["BOUNDS_LENGTH"][1]; } if ((isset($min_length)) && (strlen($value) < $min_length)) { $this->postError(1102, _t("%1 must be at least %2 characters", $va_attr["LABEL"], $min_length),"BaseModel->verifyFieldValue()"); return false; } if ((isset($max_length)) && (strlen($value) > $max_length)) { $this->postError(1102,_t("%1 must not be more than %2 characters long", $va_attr["LABEL"], $max_length),"BaseModel->verifyFieldValue()"); return false; } $va_list = isset($va_attr["BOUNDS_CHOICE_LIST"]) ? $va_attr["BOUNDS_CHOICE_LIST"] : null; if (isset($va_attr['LIST']) && $va_attr['LIST']) { $t_list = new ca_lists(); if ($t_list->load(array('list_code' => $va_attr['LIST']))) { $va_items = caExtractValuesByUserLocale($t_list->getItemsForList($va_attr['LIST'])); $va_list = array(); $vs_list_default = null; foreach($va_items as $vn_item_id => $va_item_info) { if(is_null($vs_list_default) || (isset($va_item_info['is_default']) && $va_item_info['is_default'])) { $vs_list_default = $va_item_info['item_value']; } $va_list[$va_item_info['name_singular']] = $va_item_info['item_value']; } $va_attr['DEFAULT'] = $vs_list_default; } } if ((in_array($data_type, array(FT_NUMBER, FT_TEXT))) && (isset($va_list)) && (is_array($va_list)) && (count($va_list) > 0)) { # string; check choice list if (isset($va_attr['DEFAULT']) && !strlen($value)) { $value = $va_attr['DEFAULT']; if (strlen($value)) { $this->set($field, $value); $pb_need_reload = true; } } // force default value if nothing is set if (!is_array($value)) { $value = explode(":",$value); } if (!isset($va_attr['LIST_MULTIPLE_DELIMITER']) || !($vs_list_multiple_delimiter = $va_attr['LIST_MULTIPLE_DELIMITER'])) { $vs_list_multiple_delimiter = ';'; } foreach($value as $v) { if ((sizeof($value) > 1) && (!$v)) continue; if ($va_attr['DISPLAY_TYPE'] == DT_LIST_MULTIPLE) { $va_tmp = explode($vs_list_multiple_delimiter, $v); foreach($va_tmp as $vs_mult_item) { if (!in_array($vs_mult_item,$va_list)) { $this->postError(1103,_t("'%1' is not valid choice for %2", $v, $va_attr["LABEL"]),"BaseModel->verifyFieldValue()"); return false; } } } else { if (!in_array($v,$va_list)) { $this->postError(1103, _t("'%1' is not valid choice for %2", $v, $va_attr["LABEL"]),"BaseModel->verifyFieldValue()"); return false; } } } } } return true; } # -------------------------------------------------------------------------------------------- /** * Verifies values of each field and returns a hash keyed on field name with values set to * and array of error messages for each field. Returns false (0) if no errors. * * @access public * @return array|bool */ public function verifyForm() { $this->clearErrors(); $errors = array(); $errors_found = 0; $fields = $this->getFormFields(); $err_halt = $this->error->getHaltOnError(); $err_report = $this->error->getReportOnError(); $this->error->setErrorOutput(0); while(list($field,$attr) = each($fields)) { $pb_need_reload = false; $this->verifyFieldValue ($field, $this->get($field), $pb_need_reload); if ($errnum = $this->error->getErrorNumber()) { $errors[$field][$errnum] = $this->error->getErrorDescription(); $errors_found++; } } $this->error->setHaltOnError($err_halt); $this->error->setReportOnError($err_report); if ($errors_found) { return $errors; } else { return false; } } # -------------------------------------------------------------------------------------------- # --- Field info # -------------------------------------------------------------------------------------------- /** * Returns a hash with field names as keys and attributes hashes as values * If $names_only is set, only the field names are returned in an indexed array (NOT a hash) * Only returns fields that belong in public forms - it omits those fields with a display type of 7 ("PRIVATE") * * @param bool $return_all * @param bool $names_only * @return array */ public function getFormFields ($return_all = 0, $names_only = 0) { if (($return_all) && (!$names_only)) { return $this->FIELDS; } $form_fields = array(); if (!$names_only) { foreach($this->FIELDS as $field => $attr) { if ($return_all || ($attr["DISPLAY_TYPE"] != DT_OMIT)) { $form_fields[$field] = $attr; } } } else { foreach($this->FIELDS as $field => $attr) { if ($return_all || ($attr["DISPLAY_TYPE"] != DT_OMIT)) { $form_fields[] = $field; } } } return $form_fields; } # -------------------------------------------------------------------------------------------- /** * Returns (array) snapshot of the record represented by this BaseModel object * * @access public * @param bool $pb_changes_only optional, just return changed fields * @return array */ public function &getSnapshot($pb_changes_only=false) { $va_field_list = $this->getFormFields(true, true); $va_snapshot = array(); foreach($va_field_list as $vs_field) { if (!$pb_changes_only || ($pb_changes_only && $this->changed($vs_field))) { $va_snapshot[$vs_field] = $this->get($vs_field); } } // We need to include the element_id when storing snapshots of ca_attributes and ca_attribute_values // whether is has changed or not (actually, it shouldn't really be changing after insert in normal use) // We need it available to assist in proper display of attributes in the change log if (in_array($this->tableName(), array('ca_attributes', 'ca_attribute_values'))) { $va_snapshot['element_id'] = $this->get('element_id'); $va_snapshot['attribute_id'] = $this->get('attribute_id'); } return $va_snapshot; } # -------------------------------------------------------------------------------------------- /** * Returns attributes hash for specified field * * @access public * @param string $field field name * @param string $attribute optional restriction to a single attribute */ public function getFieldInfo($field, $attribute = "") { if (isset($this->FIELDS[$field])) { $fieldinfo = $this->FIELDS[$field]; if ($attribute) { return (isset($fieldinfo[$attribute])) ? $fieldinfo[$attribute] : ""; } else { return $fieldinfo; } } else { $this->postError(710,_t("'%1' does not exist in this object", $field),"BaseModel->getFieldInfo()"); return false; } } # -------------------------------------------------------------------------------------------- /** * Returns display label for element specified by standard "get" bundle code (eg. <table_name>.<field_name> format) */ public function getDisplayLabel($ps_field) { $va_tmp = explode('.', $ps_field); if ($va_tmp[0] == 'created') { return _t('Creation date/time'); } if ($va_tmp[0] == 'modified') { return _t('Modification date/time'); } if ($va_tmp[0] != $this->tableName()) { return null; } if ($this->hasField($va_tmp[1])) { return $this->getFieldInfo($va_tmp[1], 'LABEL'); } if ($va_tmp[1] == 'created') { return _t('Creation date/time'); } if ($va_tmp[1] == 'lastModified') { return _t('Last modification date/time'); } return null; } # -------------------------------------------------------------------------------------------- /** * Returns display description for element specified by standard "get" bundle code (eg. <table_name>.<bundle_name> format) */ public function getDisplayDescription($ps_field) { $va_tmp = explode('.', $ps_field); if ($va_tmp[0] == 'created') { return _t('Date and time %1 was created', $this->getProperty('NAME_SINGULAR')); } if ($va_tmp[0] == 'modified') { return _t('Date and time %1 was modified', $this->getProperty('NAME_SINGULAR')); } if ($va_tmp[0] != $this->tableName()) { return null; } if ($this->hasField($va_tmp[1])) { return $this->getFieldInfo($va_tmp[1], 'DESCRIPTION'); } if ($va_tmp[1] == 'created') { return _t('Date and time %1 was created', $this->getProperty('NAME_SINGULAR')); } if ($va_tmp[1] == 'lastModified') { return _t('Date and time %1 was last modified', $this->getProperty('NAME_SINGULAR')); } return null; } # -------------------------------------------------------------------------------------------- /** * Returns HTML search form input widget for bundle specified by standard "get" bundle code (eg. <table_name>.<bundle_name> format) * This method handles generation of search form widgets for intrinsic fields in the primary table. If this method can't handle * the bundle (because it is not an intrinsic field in the primary table...) it will return null. * * @param $po_request HTTPRequest * @param $ps_field string * @param $pa_options array * @return string HTML text of form element. Will return null if it is not possible to generate an HTML form widget for the bundle. * */ public function htmlFormElementForSearch($po_request, $ps_field, $pa_options=null) { if (!is_array($pa_options)) { $pa_options = array(); } if (isset($pa_options['width'])) { if ($va_dim = caParseFormElementDimension($pa_options['width'])) { if ($va_dim['type'] == 'pixels') { unset($pa_options['width']); $pa_options['maxPixelWidth'] = $va_dim['dimension']; } } } $va_tmp = explode('.', $ps_field); if (in_array($va_tmp[0], array('created', 'modified'))) { return caHTMLTextInput($ps_field, array( 'id' => str_replace(".", "_", $ps_field), 'width' => (isset($pa_options['width']) && ($pa_options['width'] > 0)) ? $pa_options['width'] : 30, 'height' => (isset($pa_options['height']) && ($pa_options['height'] > 0)) ? $pa_options['height'] : 1, 'value' => (isset($pa_options['values'][$ps_field]) ? $pa_options['values'][$ps_field] : '')) ); } if ($va_tmp[0] != $this->tableName()) { return null; } if ($this->hasField($va_tmp[1])) { return $this->htmlFormElement($va_tmp[1], '^ELEMENT', array_merge($pa_options, array( 'name' => $ps_field, 'id' => str_replace(".", "_", $ps_field), 'nullOption' => '-', 'value' => (isset($pa_options['values'][$ps_field]) ? $pa_options['values'][$ps_field] : ''), 'width' => (isset($pa_options['width']) && ($pa_options['width'] > 0)) ? $pa_options['width'] : 30, 'height' => (isset($pa_options['height']) && ($pa_options['height'] > 0)) ? $pa_options['height'] : 1, 'no_tooltips' => true ))); } return null; } # -------------------------------------------------------------------------------------------- /** * Return list of fields that had conflicts with existing data during last update() * (ie. someone else had already saved to this field while the user of this instance was working) * * @access public */ public function getFieldConflicts() { return $this->field_conflicts; } # -------------------------------------------------------------------------------------------- # --- Change log # -------------------------------------------------------------------------------------------- /** * Log a change * * @access private * @param string $ps_change_type 'I', 'U' or 'D', meaning INSERT, UPDATE or DELETE * @param int $pn_user_id user identifier, defaults to null */ private function logChange($ps_change_type, $pn_user_id=null) { $vb_is_metadata = $vb_is_metadata_value = false; if ($this->tableName() == 'ca_attributes') { $vb_log_changes_to_self = false; $va_subject_config = null; $vb_is_metadata = true; } elseif($this->tableName() == 'ca_attribute_values') { $vb_log_changes_to_self = false; $va_subject_config = null; $vb_is_metadata_value = true; } else { $vb_log_changes_to_self = $this->getProperty('LOG_CHANGES_TO_SELF'); $va_subject_config = $this->getProperty('LOG_CHANGES_USING_AS_SUBJECT'); } global $AUTH_CURRENT_USER_ID; if (!$pn_user_id) { $pn_user_id = $AUTH_CURRENT_USER_ID; } if (!$pn_user_id) { $pn_user_id = null; } if (!in_array($ps_change_type, array('I', 'U', 'D'))) { return false; }; // invalid change type (shouldn't happen) if (!($vn_row_id = $this->getPrimaryKey())) { return false; } // no logging without primary key value // get unit id (if set) global $g_change_log_unit_id; $vn_unit_id = $g_change_log_unit_id; if (!$vn_unit_id) { $vn_unit_id = null; } // get subject ids $va_subjects = array(); if ($vb_is_metadata) { // special case for logging attribute changes if (($vn_id = $this->get('row_id')) > 0) { $va_subjects[$this->get('table_num')][] = $vn_id; } } elseif ($vb_is_metadata_value) { // special case for logging metadata changes $t_attr = new ca_attributes($this->get('attribute_id')); if (($vn_id = $t_attr->get('row_id')) > 0) { $va_subjects[$t_attr->get('table_num')][] = $vn_id; } } else { if (is_array($va_subject_config)) { if(is_array($va_subject_config['FOREIGN_KEYS'])) { foreach($va_subject_config['FOREIGN_KEYS'] as $vs_field) { $va_relationships = $this->_DATAMODEL->getManyToOneRelations($this->tableName(), $vs_field); if ($va_relationships['one_table']) { $vn_table_num = $this->_DATAMODEL->getTableNum($va_relationships['one_table']); if (!isset($va_subjects[$vn_table_num]) || !is_array($va_subjects[$vn_table_num])) { $va_subjects[$vn_table_num] = array(); } if (($vn_id = $this->get($vs_field)) > 0) { $va_subjects[$vn_table_num][] = $vn_id; } } } } if(is_array($va_subject_config['RELATED_TABLES'])) { if (!isset($o_db) || !$o_db) { $o_db = new Db(); $o_db->dieOnError(false); } foreach($va_subject_config['RELATED_TABLES'] as $vs_dest_table => $va_path_to_dest) { $t_dest = $this->_DATAMODEL->getTableInstance($vs_dest_table); if (!$t_dest) { continue; } $vn_dest_table_num = $t_dest->tableNum(); $vs_dest_primary_key = $t_dest->primaryKey(); $va_path_to_dest[] = $vs_dest_table; $vs_cur_table = $this->tableName(); $vs_sql = "SELECT ".$vs_dest_table.".".$vs_dest_primary_key." FROM ".$this->tableName()."\n"; foreach($va_path_to_dest as $vs_ltable) { $va_relations = $this->_DATAMODEL->getRelationships($vs_cur_table, $vs_ltable); $vs_sql .= "INNER JOIN $vs_ltable ON $vs_cur_table.".$va_relations[$vs_cur_table][$vs_ltable][0][0]." = $vs_ltable.".$va_relations[$vs_cur_table][$vs_ltable][0][1]."\n"; $vs_cur_table = $vs_ltable; } $vs_sql .= "WHERE ".$this->tableName().".".$this->primaryKey()." = ".$this->getPrimaryKey(); if ($qr_subjects = $o_db->query($vs_sql)) { if (!isset($va_subjects[$vn_dest_table_num]) || !is_array($va_subjects[$vn_dest_table_num])) { $va_subjects[$vn_dest_table_num] = array(); } while($qr_subjects->nextRow()) { if (($vn_id = $qr_subjects->get($vs_dest_primary_key)) > 0) { $va_subjects[$vn_dest_table_num][] = $vn_id; } } } else { print "<hr>Error in subject logging: "; print "<br>$vs_sql<hr>\n"; } } } } } if (!sizeof($va_subjects) && !$vb_log_changes_to_self) { return true; } if (!$this->opqs_change_log) { $o_db = $this->getDb(); $o_db->dieOnError(false); $vs_change_log_database = ''; if ($vs_change_log_database = $this->_CONFIG->get("change_log_database")) { $vs_change_log_database .= "."; } if (!($this->opqs_change_log = $o_db->prepare(" INSERT INTO ".$vs_change_log_database."ca_change_log ( log_datetime, user_id, unit_id, changetype, logged_table_num, logged_row_id ) VALUES (?, ?, ?, ?, ?, ?) "))) { // prepare failed - shouldn't happen return false; } if (!($this->opqs_change_log_snapshot = $o_db->prepare(" INSERT INTO ".$vs_change_log_database."ca_change_log_snapshots ( log_id, snapshot ) VALUES (?, ?) "))) { // prepare failed - shouldn't happen return false; } if (!($this->opqs_change_log_subjects = $o_db->prepare(" INSERT INTO ".$vs_change_log_database."ca_change_log_subjects ( log_id, subject_table_num, subject_row_id ) VALUES (?, ?, ?) "))) { // prepare failed - shouldn't happen return false; } } // get snapshot of changes made to record $va_snapshot = $this->getSnapshot(($ps_change_type === 'U') ? true : false); $vs_snapshot = caSerializeForDatabase($va_snapshot, true); if (!(($ps_change_type == 'U') && (!sizeof($va_snapshot)))) { // Create primary log entry $this->opqs_change_log->execute( time(), $pn_user_id, $vn_unit_id, $ps_change_type, $this->tableNum(), $vn_row_id ); $vn_log_id = $this->opqs_change_log->getLastInsertID(); $this->opqs_change_log_snapshot->execute( $vn_log_id, $vs_snapshot ); foreach($va_subjects as $vn_subject_table_num => $va_subject_ids) { foreach($va_subject_ids as $vn_subject_row_id) { $this->opqs_change_log_subjects->execute($vn_log_id, $vn_subject_table_num, $vn_subject_row_id); } } } } # -------------------------------------------------------------------------------------------- /** * Get change log for the current record represented by this BaseModel object, or for another specified row. * * @access public * @param int $pn_row_id Return change log for row with specified primary key id. If omitted currently loaded record is used. * @param array $pa_options Array of options. Valid options are: * range = optional range to restrict returned entries to. Should be array with 0th key set to start and 1st key set to end of range. Both values should be Unix timestamps. You can also use 'start' and 'end' as keys if desired. * limit = maximum number of entries returned. Omit or set to zero for no limit. [default=all] * forTable = if true only return changes made directly to the current table (ie. omit changes to related records that impact this record [default=false] * excludeUnitID = if set, log records with the specific unit_id are not returned [default=not set] * changeType = if set to I, U or D, will limit change log to inserts, updates or deletes respectively. If not set all types are returned. * @return array Change log data */ public function getChangeLog($pn_row_id=null, $pa_options=null) { $pa_datetime_range = (isset($pa_options['range']) && is_array($pa_options['range'])) ? $pa_options['range'] : null; $pn_max_num_entries_returned = (isset($pa_options['limit']) && (int)$pa_options['limit']) ? (int)$pa_options['limit'] : 0; $pb_for_table = (isset($pa_options['forTable'])) ? (bool)$pa_options['forTable'] : false; $ps_exclude_unit_id = (isset($pa_options['excludeUnitID']) && $pa_options['excludeUnitID']) ? $pa_options['excludeUnitID'] : null; $ps_change_type = (isset($pa_options['changeType']) && in_array($pa_options['changeType'], array('I', 'U', 'D'))) ? $pa_options['changeType'] : null; $vs_daterange_sql = ''; if ($pa_datetime_range) { $vn_start = $vn_end = null; if (isset($pa_datetime_range[0])) { $vn_start = (int)$pa_datetime_range[0]; } else { if (isset($pa_datetime_range['start'])) { $vn_start = (int)$pa_datetime_range['start']; } } if (isset($pa_datetime_range[1])) { $vn_end = (int)$pa_datetime_range[1]; } else { if (isset($pa_datetime_range['end'])) { $vn_end = (int)$pa_datetime_range['end']; } } if ($vn_start <= 0) { $vn_start = time() - 3600; } if (!$vn_end <= 0) { $vn_end = time(); } if ($vn_end < $vn_start) { $vn_end = $vn_start; } if (!$pn_row_id) { if (!($pn_row_id = $this->getPrimaryKey())) { return array(); } } $vs_daterange_sql = " AND (wcl.log_datetime > ? AND wcl.log_datetime < ?)"; } if (!$this->opqs_get_change_log) { $vs_change_log_database = ''; if ($vs_change_log_database = $this->_CONFIG->get("change_log_database")) { $vs_change_log_database .= "."; } $o_db = $this->getDb(); if ($pb_for_table) { if (!($this->opqs_get_change_log = $o_db->prepare(" SELECT DISTINCT wcl.log_id, wcl.log_datetime log_datetime, wcl.user_id, wcl.changetype, wcl.logged_table_num, wcl.logged_row_id, wclsnap.snapshot, wcl.unit_id, wu.email, wu.fname, wu.lname FROM ca_change_log wcl INNER JOIN ca_change_log_snapshots AS wclsnap ON wclsnap.log_id = wcl.log_id LEFT JOIN ca_change_log_subjects AS wcls ON wcl.log_id = wcls.log_id LEFT JOIN ca_users AS wu ON wcl.user_id = wu.user_id WHERE ( (wcl.logged_table_num = ".((int)$this->tableNum()).") AND ".(($ps_change_type) ? "(wcl.changetype = '".$ps_change_type."') AND " : "")." (wcl.logged_row_id = ?) ) {$vs_daterange_sql} ORDER BY log_datetime "))) { # should not happen return false; } } else { if (!($this->opqs_get_change_log = $o_db->prepare(" SELECT DISTINCT wcl.log_id, wcl.log_datetime log_datetime, wcl.user_id, wcl.changetype, wcl.logged_table_num, wcl.logged_row_id, wclsnap.snapshot, wcl.unit_id, wu.email, wu.fname, wu.lname FROM ca_change_log wcl INNER JOIN ca_change_log_snapshots AS wclsnap ON wclsnap.log_id = wcl.log_id LEFT JOIN ca_change_log_subjects AS wcls ON wcl.log_id = wcls.log_id LEFT JOIN ca_users AS wu ON wcl.user_id = wu.user_id WHERE ( (wcl.logged_table_num = ".((int)$this->tableNum()).") AND ".(($ps_change_type) ? "(wcl.changetype = '".$ps_change_type."') AND " : "")." (wcl.logged_row_id = ?) ) {$vs_daterange_sql} UNION SELECT DISTINCT wcl.log_id, wcl.log_datetime, wcl.user_id, wcl.changetype, wcl.logged_table_num, wcl.logged_row_id, wclsnap.snapshot, wcl.unit_id, wu.email, wu.fname, wu.lname FROM ca_change_log wcl INNER JOIN ca_change_log_snapshots AS wclsnap ON wclsnap.log_id = wcl.log_id LEFT JOIN ca_change_log_subjects AS wcls ON wcl.log_id = wcls.log_id LEFT JOIN ca_users AS wu ON wcl.user_id = wu.user_id WHERE ( (wcls.subject_table_num = ".((int)$this->tableNum()).") AND ".(($ps_change_type) ? "(wcl.changetype = '".$ps_change_type."') AND " : "")." (wcls.subject_row_id = ?) ) {$vs_daterange_sql} ORDER BY log_datetime "))) { # should not happen return false; } } if ($pn_max_num_entries_returned > 0) { $this->opqs_get_change_log->setLimit($pn_max_num_entries_returned); } } // get directly logged records $va_log = array(); if ($pb_for_table) { $qr_log = $this->opqs_get_change_log->execute($vs_daterange_sql ? array((int)$pn_row_id, (int)$vn_start, (int)$vn_end) : array((int)$pn_row_id)); } else { $qr_log = $this->opqs_get_change_log->execute($vs_daterange_sql ? array((int)$pn_row_id, (int)$vn_start, (int)$vn_end, (int)$pn_row_id, (int)$vn_start, (int)$vn_end) : array((int)$pn_row_id, (int)$pn_row_id)); } while($qr_log->nextRow()) { if ($ps_exclude_unit_id && ($ps_exclude_unit_id == $qr_log->get('unit_id'))) { continue; } $va_log[] = $qr_log->getRow(); $va_log[sizeof($va_log)-1]['snapshot'] = caUnserializeForDatabase($va_log[sizeof($va_log)-1]['snapshot']); } return $va_log; } # -------------------------------------------------------------------------------------------- /** * Get list of users (containing username, user id, forename, last name and email adress) who changed something * in a) this record (if the parameter is omitted) or b) the whole table (if the parameter is set). * * @access public * @param bool $pb_for_table * @return array */ public function getChangeLogUsers($pb_for_table=false) { $o_db = $this->getDb(); if ($pb_for_table) { $qr_users = $o_db->query(" SELECT DISTINCT wu.user_id, wu.user_name, wu.fname, wu.lname, wu.email FROM ca_users wu INNER JOIN ca_change_log AS wcl ON wcl.user_id = wu.user_id LEFT JOIN ca_change_log_subjects AS wcls ON wcl.log_id = wcls.log_id WHERE ((wcls.subject_table_num = ?) OR (wcl.logged_table_num = ?)) ORDER BY wu.lname, wu.fname ", $this->tableNum(), $this->tableNum()); } else { $qr_users = $o_db->query(" SELECT DISTINCT wu.user_id, wu.user_name, wu.fname, wu.lname, wu.email FROM ca_users wu INNER JOIN ca_change_log AS wcl ON wcl.user_id = wu.user_id LEFT JOIN ca_change_log_subjects AS wcls ON wcl.log_id = wcls.log_id WHERE ((wcls.subject_table_num = ?) OR (wcl.logged_table_num = ?)) AND ((wcl.logged_row_id = ?) OR (wcls.subject_row_id = ?)) ORDER BY wu.lname, wu.fname ", $this->tableNum(), $this->tableNum(), $this->getPrimaryKey(), $this->getPrimaryKey()); } $va_users = array(); while($qr_users->nextRow()) { $vs_user_name = $qr_users->get('user_name'); $va_users[$vs_user_name] = array( 'user_name' => $vs_user_name, 'user_id' => $qr_users->get('user_id'), 'fname' => $qr_users->get('fname'), 'lname' => $qr_users->get('lname'), 'email' => $qr_users->get('email') ); } return $va_users; } # -------------------------------------------------------------------------------------------- /** * Returns information about the creation currently loaded row * * @param int $pn_row_id If set information is returned about the specified row instead of the currently loaded one. * @param array $pa_options Array of options. Supported options are: * timestampOnly = if set to true an integer Unix timestamp for the date/time of creation is returned. If false (default) then an array is returned with timestamp and user information about the creation. * @return mixed An array detailing the date/time and creator of the row. Array includes the user_id, fname, lname and email of the user who executed the change as well as an integer Unix-style timestamp. If the timestampOnly option is set then only the timestamp is returned. */ public function getCreationTimestamp($pn_row_id=null, $pa_options=null) { if (!($vn_row_id = $pn_row_id)) { if (!($vn_row_id = $this->getPrimaryKey())) { return null; } } $o_db = $this->getDb(); $qr_res = $o_db->query(" SELECT wcl.log_datetime, wu.user_id, wu.fname, wu.lname, wu.email FROM ca_change_log wcl LEFT JOIN ca_users AS wu ON wcl.user_id = wu.user_id WHERE (wcl.logged_table_num = ?) AND (wcl.logged_row_id = ?) AND(wcl.changetype = 'I')", $this->tableNum(), $vn_row_id); if ($qr_res->nextRow()) { if (isset($pa_options['timestampOnly']) && $pa_options['timestampOnly']) { return $qr_res->get('log_datetime'); } return array( 'user_id' => $qr_res->get('user_id'), 'fname' => $qr_res->get('fname'), 'lname' => $qr_res->get('lname'), 'email' => $qr_res->get('email'), 'timestamp' => $qr_res->get('log_datetime') ); } return null; } # -------------------------------------------------------------------------------------------- /** * Returns information about the last change made to the currently loaded row * * @param int $pn_row_id If set information is returned about the specified row instead of the currently loaded one. * @param array $pa_options Array of options. Supported options are: * timestampOnly = if set to true an integer Unix timestamp for the last change is returned. If false (default) then an array is returned with timestamp and user information about the change. * @return mixed An array detailing the date/time and initiator of the last change. Array includes the user_id, fname, lname and email of the user who executed the change as well as an integer Unix-style timestamp. If the timestampOnly option is set then only the timestamp is returned. */ public function getLastChangeTimestamp($pn_row_id=null, $pa_options=null) { if (!($vn_row_id = $pn_row_id)) { if (!($vn_row_id = $this->getPrimaryKey())) { return null; } } $o_db = $this->getDb(); $qr_res = $o_db->query(" SELECT wcl.log_datetime, wu.user_id, wu.fname, wu.lname, wu.email FROM ca_change_log wcl LEFT JOIN ca_users AS wu ON wcl.user_id = wu.user_id INNER JOIN ca_change_log_subjects AS wcls ON wcl.log_id = wcls.log_id WHERE (wcls.subject_table_num = ?) AND (wcls.subject_row_id = ?) AND (wcl.changetype IN ('I', 'U')) ORDER BY wcl.log_datetime DESC LIMIT 1", $this->tableNum(), $vn_row_id); $vn_last_change_timestamp = 0; $va_last_change_info = null; if ($qr_res->nextRow()) { $vn_last_change_timestamp = $qr_res->get('log_datetime'); $va_last_change_info = array( 'user_id' => $qr_res->get('user_id'), 'fname' => $qr_res->get('fname'), 'lname' => $qr_res->get('lname'), 'email' => $qr_res->get('email'), 'timestamp' => $qr_res->get('log_datetime') ); } $qr_res = $o_db->query(" SELECT wcl.log_datetime, wu.user_id, wu.fname, wu.lname, wu.email FROM ca_change_log wcl LEFT JOIN ca_users AS wu ON wcl.user_id = wu.user_id WHERE (wcl.logged_table_num = ?) AND (wcl.logged_row_id = ?) AND (wcl.changetype IN ('I', 'U')) ORDER BY wcl.log_datetime DESC LIMIT 1", $this->tableNum(), $vn_row_id); if ($qr_res->nextRow()) { if ($qr_res->get('log_datetime') > $vn_last_change_timestamp) { $vn_last_change_timestamp = $qr_res->get('log_datetime'); $va_last_change_info = array( 'user_id' => $qr_res->get('user_id'), 'fname' => $qr_res->get('fname'), 'lname' => $qr_res->get('lname'), 'email' => $qr_res->get('email'), 'timestamp' => $qr_res->get('log_datetime') ); } } if ($vn_last_change_timestamp > 0) { if (isset($pa_options['timestampOnly']) && $pa_options['timestampOnly']) { return $vn_last_change_timestamp; } return $va_last_change_info; } return null; } # -------------------------------------------------------------------------------------------- # --- Hierarchical functions # -------------------------------------------------------------------------------------------- /** * Are we dealing with a hierarchical structure in this table? * * @access public * @return bool */ public function isHierarchical() { return (!is_null($this->getProperty("HIERARCHY_TYPE"))) ? true : false; } # -------------------------------------------------------------------------------------------- /** * What type of hierarchical structure is used by this table? * * @access public * @return int (__CA_HIER_*__ constant) */ public function getHierarchyType() { return $this->getProperty("HIERARCHY_TYPE"); } # -------------------------------------------------------------------------------------------- /** * Fetches primary key of the hierarchy root. * DOES NOT CREATE ROOT - YOU HAVE TO DO THAT YOURSELF (this differs from previous versions of these libraries). * * @param int $pn_hierarchy_id optional, points to record in related table containing hierarchy description * @return int root id */ public function getHierarchyRootID($pn_hierarchy_id=null) { $vn_root_id = null; $o_db = $this->getDb(); switch($this->getHierarchyType()) { # ------------------------------------------------------------------ case __CA_HIER_TYPE_SIMPLE_MONO__: // For simple "table is one big hierarchy" setups all you need // to do is look for the row where parent_id is NULL $qr_res = $o_db->query(" SELECT ".$this->primaryKey()." FROM ".$this->tableName()." WHERE (".$this->getProperty('HIERARCHY_PARENT_ID_FLD')." IS NULL) "); if ($qr_res->nextRow()) { $vn_root_id = $qr_res->get($this->primaryKey()); } break; # ------------------------------------------------------------------ case __CA_HIER_TYPE_MULTI_MONO__: // For tables that house multiple hierarchies defined in a second table // you need to look for the row where parent_id IS NULL and hierarchy_id = the value // passed in $pn_hierarchy_id if (!$pn_hierarchy_id) { // if hierarchy_id is not explicitly set use the value in the currently loaded row $pn_hierarchy_id = $this->get($this->getProperty('HIERARCHY_PARENT_ID_FLD')); } $qr_res = $o_db->query(" SELECT ".$this->primaryKey()." FROM ".$this->tableName()." WHERE (".$this->getProperty('HIERARCHY_PARENT_ID_FLD')." IS NULL) AND (".$this->getProperty('HIERARCHY_ID_FLD')." = ?) ", (int)$pn_hierarchy_id); if ($qr_res->nextRow()) { $vn_root_id = $qr_res->get($this->primaryKey()); } break; # ------------------------------------------------------------------ case __CA_HIER_TYPE_ADHOC_MONO__: // For ad-hoc hierarchies you just return the hierarchy_id value if (!$pn_hierarchy_id) { // if hierarchy_id is not explicitly set use the value in the currently loaded row $pn_hierarchy_id = $this->get($this->getProperty('HIERARCHY_ID_FLD')); } $vn_root_id = $pn_hierarchy_id; break; # ------------------------------------------------------------------ case __CA_HIER_TYPE_MULTI_POLY__: // TODO: implement this break; # ------------------------------------------------------------------ default: die("Invalid hierarchy type: ".$this->getHierarchyType()); break; # ------------------------------------------------------------------ } return $vn_root_id; } # -------------------------------------------------------------------------------------------- /** * Fetch a DbResult representation of the whole hierarchy * * @access public * @param int $pn_id optional, id of record to be treated as root * @param array $pa_options * returnDeleted = return deleted records in list (def. false) * additionalTableToJoin: name of table to join to hierarchical table (and return fields from); only fields related many-to-one are currently supported * * @return DbResult */ public function &getHierarchy($pn_id=null, $pa_options=null) { if (!is_array($pa_options)) { $pa_options = array(); } $vs_table_name = $this->tableName(); if ($this->isHierarchical()) { $vs_hier_left_fld = $this->getProperty("HIERARCHY_LEFT_INDEX_FLD"); $vs_hier_right_fld = $this->getProperty("HIERARCHY_RIGHT_INDEX_FLD"); $vs_hier_parent_id_fld = $this->getProperty("HIERARCHY_PARENT_ID_FLD"); $vs_hier_id_fld = $this->getProperty("HIERARCHY_ID_FLD"); $vs_hier_id_table = $this->getProperty("HIERARCHY_DEFINITION_TABLE"); if (!$pn_id) { if (!($pn_id = $this->getHierarchyRootID($this->get($vs_hier_id_fld)))) { return null; } } $vn_hierarchy_id = $this->get($vs_hier_id_fld); $vs_hier_id_sql = ""; if ($vn_hierarchy_id) { // TODO: verify hierarchy_id exists $vs_hier_id_sql = " AND (".$vs_hier_id_fld." = ".$vn_hierarchy_id.")"; } $o_db = $this->getDb(); $qr_root = $o_db->query(" SELECT $vs_hier_left_fld, $vs_hier_right_fld ".(($this->hasField($vs_hier_id_fld)) ? ", $vs_hier_id_fld" : "")." FROM ".$this->tableName()." WHERE (".$this->primaryKey()." = ?) ", intval($pn_id)); if ($o_db->numErrors()) { $this->errors = array_merge($this->errors, $o_db->errors()); return null; } else { if ($qr_root->nextRow()) { $va_count = array(); if (($this->hasField($vs_hier_id_fld)) && (!($vn_hierarchy_id = $this->get($vs_hier_id_fld))) && (!($vn_hierarchy_id = $qr_root->get($vs_hier_id_fld)))) { $this->postError(2030, _t("Hierarchy ID must be specified"), "Table->getHierarchy()"); return false; } $vs_table_name = $this->tableName(); $vs_hier_id_sql = ""; if ($vn_hierarchy_id) { $vs_hier_id_sql = " AND ({$vs_table_name}.{$vs_hier_id_fld} = {$vn_hierarchy_id})"; } $va_sql_joins = array(); if (isset($pa_options['additionalTableToJoin']) && ($pa_options['additionalTableToJoin'])){ $ps_additional_table_to_join = $pa_options['additionalTableToJoin']; // what kind of join are we doing for the additional table? LEFT or INNER? (default=INNER) $ps_additional_table_join_type = 'INNER'; if (isset($pa_options['additionalTableJoinType']) && ($pa_options['additionalTableJoinType'] === 'LEFT')) { $ps_additional_table_join_type = 'LEFT'; } if (is_array($va_rel = $this->getAppDatamodel()->getOneToManyRelations($this->tableName(), $ps_additional_table_to_join))) { // one-many rel $va_sql_joins[] = "{$ps_additional_table_join_type} JOIN {$ps_additional_table_to_join} ON ".$this->tableName().'.'.$va_rel['one_table_field']." = {$ps_additional_table_to_join}.".$va_rel['many_table_field']; } else { // TODO: handle many-many cases } // are there any SQL WHERE criteria for the additional table? $va_additional_table_wheres = null; if (isset($pa_options['additionalTableWheres']) && is_array($pa_options['additionalTableWheres'])) { $va_additional_table_wheres = $pa_options['additionalTableWheres']; } $vs_additional_wheres = ''; if (is_array($va_additional_table_wheres) && (sizeof($va_additional_table_wheres) > 0)) { $vs_additional_wheres = ' AND ('.join(' AND ', $va_additional_table_wheres).') '; } } $vs_deleted_sql = ''; if ($this->hasField('deleted') && (!isset($pa_options['returnDeleted']) || (!$pa_options['returnDeleted']))) { $vs_deleted_sql = " AND ({$vs_table_name}.deleted = 0)"; } $vs_sql_joins = join("\n", $va_sql_joins); $vs_sql = " SELECT * FROM {$vs_table_name} {$vs_sql_joins} WHERE ({$vs_table_name}.{$vs_hier_left_fld} BETWEEN ".$qr_root->get($vs_hier_left_fld)." AND ".$qr_root->get($vs_hier_right_fld).") {$vs_hier_id_sql} {$vs_deleted_sql} {$vs_additional_wheres} ORDER BY {$vs_table_name}.{$vs_hier_left_fld} "; //print $vs_sql; $qr_hier = $o_db->query($vs_sql); if ($o_db->numErrors()) { $this->errors = array_merge($this->errors, $o_db->errors()); return null; } else { return $qr_hier; } } else { return null; } } } else { return null; } } # -------------------------------------------------------------------------------------------- /** * Get the hierarchy in list form * * @param int $pn_id * @param array $pa_options * * additionalTableToJoin: name of table to join to hierarchical table (and return fields from); only fields related many-to-one are currently supported * idsOnly: if true, only the primary key id values of the chidlren records are returned * returnDeleted = return deleted records in list (def. false) * maxLevels = * dontIncludeRoot = * * @return array */ public function &getHierarchyAsList($pn_id=null, $pa_options=null) { $pb_ids_only = (isset($pa_options['idsOnly']) && $pa_options['idsOnly']) ? true : false; $pn_max_levels = isset($pa_options['maxLevels']) ? intval($pa_options['maxLevels']) : null; $ps_additional_table_to_join = isset($pa_options['additionalTableToJoin']) ? $pa_options['additionalTableToJoin'] : null; $pb_dont_include_root = (isset($pa_options['dontIncludeRoot']) && $pa_options['dontIncludeRoot']) ? true : false; if ($qr_hier = $this->getHierarchy($pn_id, $pa_options)) { $vs_hier_right_fld = $this->getProperty("HIERARCHY_RIGHT_INDEX_FLD"); $va_indent_stack = array(); $va_hier = array(); $vn_cur_level = -1; $va_omit_stack = array(); $vn_root_id = $pn_id; while($qr_hier->nextRow()) { $vn_row_id = $qr_hier->get($this->primaryKey()); if (is_null($vn_root_id)) { $vn_root_id = $vn_row_id; } if ($pb_dont_include_root && ($vn_row_id == $vn_root_id)) { continue; } // skip root if desired $vn_r = $qr_hier->get($vs_hier_right_fld); $vn_c = sizeof($va_indent_stack); if($vn_c > 0) { while (($vn_c) && ($va_indent_stack[$vn_c - 1] <= $vn_r)){ array_pop($va_indent_stack); $vn_c = sizeof($va_indent_stack); } } if($vn_cur_level != sizeof($va_indent_stack)) { if ($vn_cur_level > sizeof($va_indent_stack)) { $va_omit_stack = array(); } $vn_cur_level = intval(sizeof($va_indent_stack)); } if (is_null($pn_max_levels) || ($vn_cur_level < $pn_max_levels)) { $va_field_values = $qr_hier->getRow(); foreach($va_field_values as $vs_key => $vs_val) { $va_field_values[$vs_key] = stripSlashes($vs_val); } if ($pb_ids_only) { $va_hier[] = $vn_row_id; } else { $va_node = array( "NODE" => $va_field_values, "LEVEL" => $vn_cur_level ); $va_hier[] = $va_node; } } $va_indent_stack[] = $vn_r; } return $va_hier; } else { return null; } } # -------------------------------------------------------------------------------------------- /** * Returns a list of primary keys comprising all child rows * * @param int $pn_id node to start from - default is the hierarchy root * @return array id list */ public function &getHierarchyIDs($pn_id=null, $pa_options=null) { if ($qr_hier = $this->getHierarchy($pn_id, $pa_options)) { $va_ids = array(); $vs_pk = $this->primaryKey(); while($qr_hier->nextRow()) { $va_ids[] = $qr_hier->get($vs_pk); } return $va_ids; } else { return null; } } # -------------------------------------------------------------------------------------------- /** * Get *direct* child records for currently loaded record or one specified by $pn_id * Note that this only returns direct children, *NOT* children of children and further descendents * If you need to get a chunk of the hierarchy use getHierarchy() * * @access public * @param int optional, primary key value of a record. * Use this if you want to know the children of a record different than $this * @param array, optional associative array of options. Valid keys for the array are: * additionalTableToJoin: name of table to join to hierarchical table (and return fields from); only fields related many-to-one are currently supported * returnChildCounts: if true, the number of children under each returned child is calculated and returned in the result set under the column name 'child_count'. Note that this count is always at least 1, even if there are no children. The 'has_children' column will be null if the row has, in fact no children, or non-null if it does have children. You should check 'has_children' before using 'child_count' and disregard 'child_count' if 'has_children' is null. * returnDeleted = return deleted records in list (def. false) * @return DbResult */ public function &getHierarchyChildrenAsQuery($pn_id=null, $pa_options=null) { $o_db = $this->getDb(); $vs_table_name = $this->tableName(); // return counts of child records for each child found? $pb_return_child_counts = isset($pa_options['returnChildCounts']) ? true : false; $va_additional_table_wheres = array(); $va_additional_table_select_fields = array(); // additional table to join into query? $ps_additional_table_to_join = isset($pa_options['additionalTableToJoin']) ? $pa_options['additionalTableToJoin'] : null; if ($ps_additional_table_to_join) { // what kind of join are we doing for the additional table? LEFT or INNER? (default=INNER) $ps_additional_table_join_type = 'INNER'; if (isset($pa_options['additionalTableJoinType']) && ($pa_options['additionalTableJoinType'] === 'LEFT')) { $ps_additional_table_join_type = 'LEFT'; } // what fields from the additional table are we going to return? if (isset($pa_options['additionalTableSelectFields']) && is_array($pa_options['additionalTableSelectFields'])) { foreach($pa_options['additionalTableSelectFields'] as $vs_fld) { $va_additional_table_select_fields[] = "{$ps_additional_table_to_join}.{$vs_fld}"; } } // are there any SQL WHERE criteria for the additional table? if (isset($pa_options['additionalTableWheres']) && is_array($pa_options['additionalTableWheres'])) { $va_additional_table_wheres = $pa_options['additionalTableWheres']; } } if ($this->hasField('deleted') && (!isset($pa_options['returnDeleted']) || (!$pa_options['returnDeleted']))) { $va_additional_table_wheres[] = "({$vs_table_name}.deleted = 0)"; } if ($this->isHierarchical()) { if (!$pn_id) { if (!($pn_id = $this->getPrimaryKey())) { return null; } } $va_sql_joins = array(); $vs_additional_table_to_join_group_by = ''; if ($ps_additional_table_to_join){ if (is_array($va_rel = $this->getAppDatamodel()->getOneToManyRelations($this->tableName(), $ps_additional_table_to_join))) { // one-many rel $va_sql_joins[] = $ps_additional_table_join_type." JOIN {$ps_additional_table_to_join} ON ".$this->tableName().'.'.$va_rel['one_table_field']." = {$ps_additional_table_to_join}.".$va_rel['many_table_field']; } else { // TODO: handle many-many cases } $t_additional_table_to_join = $this->_DATAMODEL->getTableInstance($ps_additional_table_to_join); $vs_additional_table_to_join_group_by = ', '.$ps_additional_table_to_join.'.'.$t_additional_table_to_join->primaryKey(); } $vs_sql_joins = join("\n", $va_sql_joins); $vs_hier_parent_id_fld = $this->getProperty("HIERARCHY_PARENT_ID_FLD"); if ($vs_rank_fld = $this->getProperty('RANK')) { $vs_order_by = $this->tableName().'.'.$vs_rank_fld; } else { $vs_order_by = $this->tableName().".".$this->primaryKey(); } if ($pb_return_child_counts) { $qr_hier = $o_db->query(" SELECT ".$this->tableName().".* ".(sizeof($va_additional_table_select_fields) ? ', '.join(', ', $va_additional_table_select_fields) : '').", count(*) child_count, p2.".$this->primaryKey()." has_children FROM ".$this->tableName()." {$vs_sql_joins} LEFT JOIN ".$this->tableName()." AS p2 ON p2.".$vs_hier_parent_id_fld." = ".$this->tableName().".".$this->primaryKey()." WHERE (".$this->tableName().".{$vs_hier_parent_id_fld} = ?) ".((sizeof($va_additional_table_wheres) > 0) ? ' AND '.join(' AND ', $va_additional_table_wheres) : '')." GROUP BY ".$this->tableName().".".$this->primaryKey()." {$vs_additional_table_to_join_group_by} ORDER BY ".$vs_order_by." ", $pn_id); } else { $qr_hier = $o_db->query(" SELECT ".$this->tableName().".* ".(sizeof($va_additional_table_select_fields) ? ', '.join(', ', $va_additional_table_select_fields) : '')." FROM ".$this->tableName()." {$vs_sql_joins} WHERE (".$this->tableName().".{$vs_hier_parent_id_fld} = ?) ".((sizeof($va_additional_table_wheres) > 0) ? ' AND '.join(' AND ', $va_additional_table_wheres) : '')." ORDER BY ".$vs_order_by." ", $pn_id); } if ($o_db->numErrors()) { $this->errors = array_merge($this->errors, $o_db->errors()); return null; } else { return $qr_hier; } } else { return null; } } # -------------------------------------------------------------------------------------------- /** * Get *direct* child records for currently loaded record or one specified by $pn_id * Note that this only returns direct children, *NOT* children of children and further descendents * If you need to get a chunk of the hierarchy use getHierarchy(). * * Results are returned as an array with either associative array values for each child record, or if the * idsOnly option is set, then the primary key values. * * @access public * @param int optional, primary key value of a record. * Use this if you want to know the children of a record different than $this * @param array, optional associative array of options. Valid keys for the array are: * additionalTableToJoin: name of table to join to hierarchical table (and return fields from); only fields related many-to-one are currently supported * returnChildCounts: if true, the number of children under each returned child is calculated and returned in the result set under the column name 'child_count'. Note that this count is always at least 1, even if there are no children. The 'has_children' column will be null if the row has, in fact no children, or non-null if it does have children. You should check 'has_children' before using 'child_count' and disregard 'child_count' if 'has_children' is null. * idsOnly: if true, only the primary key id values of the chidlren records are returned * returnDeleted = return deleted records in list (def. false) * @return array */ public function getHierarchyChildren($pn_id=null, $pa_options=null) { $pb_ids_only = (isset($pa_options['idsOnly']) && $pa_options['idsOnly']) ? true : false; if (!$pn_id) { $pn_id = $this->getPrimaryKey(); } if (!$pn_id) { return null; } $qr_children = $this->getHierarchyChildrenAsQuery($pn_id, $pa_options); $va_children = array(); $vs_pk = $this->primaryKey(); while($qr_children->nextRow()) { if ($pb_ids_only) { $va_row = $qr_children->getRow(); $va_children[] = $va_row[$vs_pk]; } else { $va_children[] = $qr_children->getRow(); } } return $va_children; } # -------------------------------------------------------------------------------------------- /** * Get "siblings" records - records with the same parent - as the currently loaded record * or the record with its primary key = $pn_id * * Results are returned as an array with either associative array values for each sibling record, or if the * idsOnly option is set, then the primary key values. * * @access public * @param int optional, primary key value of a record. * Use this if you want to know the siblings of a record different than $this * @param array, optional associative array of options. Valid keys for the array are: * additionalTableToJoin: name of table to join to hierarchical table (and return fields from); only fields related many-to-one are currently supported * returnChildCounts: if true, the number of children under each returned sibling is calculated and returned in the result set under the column name 'sibling_count'.d * idsOnly: if true, only the primary key id values of the chidlren records are returned * returnDeleted = return deleted records in list (def. false) * @return array */ public function &getHierarchySiblings($pn_id=null, $pa_options=null) { $pb_ids_only = (isset($pa_options['idsOnly']) && $pa_options['idsOnly']) ? true : false; if (!$pn_id) { $pn_id = $this->getPrimaryKey(); } if (!$pn_id) { return null; } $vs_table_name = $this->tableName(); $va_additional_table_wheres = array($this->primaryKey()." = ?"); if ($this->hasField('deleted') && (!isset($pa_options['returnDeleted']) || (!$pa_options['returnDeleted']))) { $va_additional_table_wheres[] = "({$vs_table_name}.deleted = 0)"; } // convert id into parent_id - get the children of the parent is equivalent to getting the siblings for the id if ($qr_parent = $this->getDb()->query(" SELECT ".$this->getProperty('HIERARCHY_PARENT_ID_FLD')." FROM ".$this->tableName()." WHERE ".join(' AND ', $va_additional_table_wheres), (int)$pn_id)) { if ($qr_parent->nextRow()) { $pn_id = $qr_parent->get($this->getProperty('HIERARCHY_PARENT_ID_FLD')); } else { $this->postError(250, _t('Could not get parent_id to load siblings by: %1', join(';', $this->getDb()->getErrors())), 'BaseModel->getHierarchySiblings'); return false; } } else { $this->postError(250, _t('Could not get hierarchy siblings: %1', join(';', $this->getDb()->getErrors())), 'BaseModel->getHierarchySiblings'); return false; } if (!$pn_id) { return array(); } $qr_children = $this->getHierarchyChildrenAsQuery($pn_id, $pa_options); $va_siblings = array(); $vs_pk = $this->primaryKey(); while($qr_children->nextRow()) { if ($pb_ids_only) { $va_row = $qr_children->getRow(); $va_siblings[] = $va_row[$vs_pk]; } else { $va_siblings[] = $qr_children->getRow(); } } return $va_siblings; } # -------------------------------------------------------------------------------------------- /** * Get hierarchy ancestors * * @access public * @param int optional, primary key value of a record. * Use this if you want to know the ancestors of a record different than $this * @param array optional, options * idsOnly = just return the ids of the ancestors (def. false) * includeSelf = include this record (def. false) * additionalTableToJoin = name of additonal table data to return * returnDeleted = return deleted records in list (def. false) * @return array */ public function &getHierarchyAncestors($pn_id=null, $pa_options=null) { $pb_include_self = (isset($pa_options['includeSelf']) && $pa_options['includeSelf']) ? true : false; $pb_ids_only = (isset($pa_options['idsOnly']) && $pa_options['idsOnly']) ? true : false; $vs_table_name = $this->tableName(); $va_additional_table_select_fields = array(); $va_additional_table_wheres = array(); // additional table to join into query? $ps_additional_table_to_join = isset($pa_options['additionalTableToJoin']) ? $pa_options['additionalTableToJoin'] : null; if ($ps_additional_table_to_join) { // what kind of join are we doing for the additional table? LEFT or INNER? (default=INNER) $ps_additional_table_join_type = 'INNER'; if (isset($pa_options['additionalTableJoinType']) && ($pa_options['additionalTableJoinType'] === 'LEFT')) { $ps_additional_table_join_type = 'LEFT'; } // what fields from the additional table are we going to return? if (isset($pa_options['additionalTableSelectFields']) && is_array($pa_options['additionalTableSelectFields'])) { foreach($pa_options['additionalTableSelectFields'] as $vs_fld) { $va_additional_table_select_fields[] = "{$ps_additional_table_to_join}.{$vs_fld}"; } } // are there any SQL WHERE criteria for the additional table? if (isset($pa_options['additionalTableWheres']) && is_array($pa_options['additionalTableWheres'])) { $va_additional_table_wheres = $pa_options['additionalTableWheres']; } } if ($this->hasField('deleted') && (!isset($pa_options['returnDeleted']) || (!$pa_options['returnDeleted']))) { $va_additional_table_wheres[] = "({$vs_table_name}.deleted = 0)"; } if ($this->isHierarchical()) { if (!$pn_id) { if (!($pn_id = $this->getPrimaryKey())) { return null; } } $vs_hier_left_fld = $this->getProperty("HIERARCHY_LEFT_INDEX_FLD"); $vs_hier_right_fld = $this->getProperty("HIERARCHY_RIGHT_INDEX_FLD"); $vs_hier_id_fld = $this->getProperty("HIERARCHY_ID_FLD"); $vs_hier_id_table = $this->getProperty("HIERARCHY_DEFINITION_TABLE"); $vs_hier_parent_id_fld = $this->getProperty("HIERARCHY_PARENT_ID_FLD"); $va_sql_joins = array(); if ($ps_additional_table_to_join){ $va_path = $this->getAppDatamodel()->getPath($vs_table_name, $ps_additional_table_to_join); switch(sizeof($va_path)) { case 2: $va_rels = $this->getAppDatamodel()->getRelationships($vs_table_name, $ps_additional_table_to_join); $va_sql_joins[] = $ps_additional_table_join_type." JOIN {$ps_additional_table_to_join} ON ".$vs_table_name.'.'.$va_rels[$ps_additional_table_to_join][$vs_table_name][0][1]." = {$ps_additional_table_to_join}.".$va_rels[$ps_additional_table_to_join][$vs_table_name][0][0]; break; case 3: // TODO: handle many-many cases break; } } $vs_sql_joins = join("\n", $va_sql_joins); $o_db = $this->getDb(); $qr_root = $o_db->query(" SELECT {$vs_table_name}.* ".(sizeof($va_additional_table_select_fields) ? ', '.join(', ', $va_additional_table_select_fields) : '')." FROM {$vs_table_name} {$vs_sql_joins} WHERE ({$vs_table_name}.".$this->primaryKey()." = ?) ".((sizeof($va_additional_table_wheres) > 0) ? ' AND '.join(' AND ', $va_additional_table_wheres) : '')." ", intval($pn_id)); if ($o_db->numErrors()) { $this->errors = array_merge($this->errors, $o_db->errors()); return null; } else { if ($qr_root->numRows()) { $va_ancestors = array(); $vn_parent_id = null; $vn_level = 0; if ($pb_include_self) { while ($qr_root->nextRow()) { if (!$vn_parent_id) { $vn_parent_id = $qr_root->get($vs_hier_parent_id_fld); } if ($pb_ids_only) { $va_ancestors[] = $qr_root->get($this->primaryKey()); } else { $va_ancestors[] = array( "NODE" => $qr_root->getRow(), "LEVEL" => $vn_level ); } $vn_level++; } } else { $qr_root->nextRow(); $vn_parent_id = $qr_root->get($vs_hier_parent_id_fld); } if($vn_parent_id) { do { $vs_sql = " SELECT {$vs_table_name}.* ".(sizeof($va_additional_table_select_fields) ? ', '.join(', ', $va_additional_table_select_fields) : '')." FROM {$vs_table_name} {$vs_sql_joins} WHERE ({$vs_table_name}.".$this->primaryKey()." = ?) ".((sizeof($va_additional_table_wheres) > 0) ? ' AND '.join(' AND ', $va_additional_table_wheres) : '')." "; $qr_hier = $o_db->query($vs_sql, $vn_parent_id); $vn_parent_id = null; while ($qr_hier->nextRow()) { if (!$vn_parent_id) { $vn_parent_id = $qr_hier->get($vs_hier_parent_id_fld); } if ($pb_ids_only) { $va_ancestors[] = $qr_hier->get($this->primaryKey()); } else { $va_ancestors[] = array( "NODE" => $qr_hier->getRow(), "LEVEL" => $vn_level ); } } $vn_level++; } while($vn_parent_id); return $va_ancestors; } else { return $va_ancestors; } } else { return null; } } } else { return null; } } # -------------------------------------------------------------------------------------------- public function rebuildAllHierarchicalIndexes() { $vs_hier_left_fld = $this->getProperty("HIERARCHY_LEFT_INDEX_FLD"); $vs_hier_right_fld = $this->getProperty("HIERARCHY_RIGHT_INDEX_FLD"); $vs_hier_id_fld = $this->getProperty("HIERARCHY_ID_FLD"); $vs_hier_id_table = $this->getProperty("HIERARCHY_DEFINITION_TABLE"); $vs_hier_parent_id_fld = $this->getProperty("HIERARCHY_PARENT_ID_FLD"); if (!$vs_hier_id_fld) { return false; } $o_db = $this->getDb(); $qr_hier_ids = $o_db->query(" SELECT DISTINCT ".$vs_hier_id_fld." FROM ".$this->tableName()." "); while($qr_hier_ids->nextRow()) { $this->rebuildHierarchicalIndex($qr_hier_ids->get($vs_hier_id_fld)); } return true; } # -------------------------------------------------------------------------------------------- public function rebuildHierarchicalIndex($pn_hierarchy_id=null) { if ($this->isHierarchical()) { $vb_we_set_transaction = false; if (!$this->inTransaction()) { $this->setTransaction(new Transaction($this->getDb())); $vb_we_set_transaction = true; } if ($vn_root_id = $this->getHierarchyRootID($pn_hierarchy_id)) { $this->_rebuildHierarchicalIndex($vn_root_id, 1); if ($vb_we_set_transaction) { $this->removeTransaction(true);} return true; } else { if ($vb_we_set_transaction) { $this->removeTransaction(false);} return null; } } else { return null; } } # -------------------------------------------------------------------------------------------- private function _rebuildHierarchicalIndex($pn_parent_id, $pn_hier_left) { $vs_hier_parent_id_fld = $this->getProperty("HIERARCHY_PARENT_ID_FLD"); $vs_hier_left_fld = $this->getProperty("HIERARCHY_LEFT_INDEX_FLD"); $vs_hier_right_fld = $this->getProperty("HIERARCHY_RIGHT_INDEX_FLD"); $vs_hier_id_fld = $this->getProperty("HIERARCHY_ID_FLD"); $vs_hier_id_table = $this->getProperty("HIERARCHY_DEFINITION_TABLE"); $vn_hier_right = $pn_hier_left + 100; $vs_pk = $this->primaryKey(); $o_db = $this->getDb(); if (is_null($pn_parent_id)) { $vs_sql = " SELECT * FROM ".$this->tableName()." WHERE (".$vs_hier_parent_id_fld." IS NULL) "; } else { $vs_sql = " SELECT * FROM ".$this->tableName()." WHERE (".$vs_hier_parent_id_fld." = ".intval($pn_parent_id).") "; } $qr_level = $o_db->query($vs_sql); if ($o_db->numErrors()) { $this->errors = array_merge($this->errors, $o_db->errors()); return null; } else { while($qr_level->nextRow()) { $vn_hier_right = $this->_rebuildHierarchicalIndex($qr_level->get($vs_pk), $vn_hier_right); } $qr_up = $o_db->query(" UPDATE ".$this->tableName()." SET ".$vs_hier_left_fld." = ".intval($pn_hier_left).", ".$vs_hier_right_fld." = ".intval($vn_hier_right)." WHERE (".$vs_pk." = ?) ", intval($pn_parent_id)); if ($o_db->numErrors()) { $this->errors = array_merge($this->errors, $o_db->errors()); return null; } else { return $vn_hier_right + 100; } } } # -------------------------------------------------------------------------------------------- /** * HTML Form element generation * Optional name parameter allows you to generate a form element for a field but give it a * name different from the field name * * @param string $ps_field field name * @param string $ps_format field format * @param array $pa_options additional options * TODO: document them. */ public function htmlFormElement($ps_field, $ps_format=null, $pa_options=null) { $o_db = $this->getDb(); // init options if (!is_array($pa_options)) { $pa_options = array(); } foreach (array( 'display_form_field_tips', 'classname', 'maxOptionLength', 'textAreaTagName', 'display_use_count', 'display_omit_items__with_zero_count', 'display_use_count_filters', 'display_use_count_filters', 'selection', 'name', 'value', 'dont_show_null_value', 'size', 'multiple', 'show_text_field_for_vars', 'nullOption', 'empty_message', 'displayMessageForFieldValues', 'DISPLAY_FIELD', 'WHERE', 'select_item_text', 'hide_select_if_only_one_option', 'field_errors', 'display_form_field_tips', 'form_name', 'no_tooltips', 'tooltip_namespace', 'extraLabelText', 'width', 'height', 'label', 'list_code', 'hide_select_if_no_options', 'id', 'lookup_url', 'progress_indicator', 'error_icon', 'maxPixelWidth', 'displayMediaVersion', 'FIELD_TYPE', 'DISPLAY_TYPE', 'choiceList', 'readonly' ) as $vs_key) { if(!isset($pa_options[$vs_key])) { $pa_options[$vs_key] = null; } } $va_attr = $this->getFieldInfo($ps_field); foreach (array( 'DISPLAY_WIDTH', 'DISPLAY_USE_COUNT', 'DISPLAY_SHOW_COUNT', 'DISPLAY_OMIT_ITEMS_WITH_ZERO_COUNT', 'DISPLAY_TYPE', 'IS_NULL', 'DEFAULT_ON_NULL', 'DEFAULT', 'LIST_MULTIPLE_DELIMITER', 'FIELD_TYPE', 'LIST_CODE', 'DISPLAY_FIELD', 'WHERE', 'DISPLAY_WHERE', 'DISPLAY_ORDERBY', 'LIST', 'BOUNDS_CHOICE_LIST', 'BOUNDS_LENGTH', 'DISPLAY_DESCRIPTION', 'LABEL', 'DESCRIPTION', 'SUB_LABEL', 'SUB_DESCRIPTION', 'MAX_PIXEL_WIDTH' ) as $vs_key) { if(!isset($va_attr[$vs_key])) { $va_attr[$vs_key] = null; } } if (isset($pa_options['FIELD_TYPE'])) { $va_attr['FIELD_TYPE'] = $pa_options['FIELD_TYPE']; } if (isset($pa_options['DISPLAY_TYPE'])) { $va_attr['DISPLAY_TYPE'] = $pa_options['DISPLAY_TYPE']; } $vn_display_width = (isset($pa_options['width']) && ($pa_options['width'] > 0)) ? $pa_options['width'] : $va_attr["DISPLAY_WIDTH"]; $vn_display_height = (isset($pa_options['height']) && ($pa_options['height'] > 0)) ? $pa_options['height'] : $va_attr["DISPLAY_HEIGHT"]; $va_parsed_width = caParseFormElementDimension($vn_display_width); $va_parsed_height = caParseFormElementDimension($vn_display_height); $va_dim_styles = array(); if ($va_parsed_width['type'] == 'pixels') { $va_dim_styles[] = "width: ".$va_parsed_width['dimension']."px;"; } if ($va_parsed_height['type'] == 'pixels') { $va_dim_styles[] = "height: ".$va_parsed_height['dimension']."px;"; } if ($vn_max_pixel_width) { $va_dim_styles[] = "max-width: {$vn_max_pixel_width}px;"; } $vs_dim_style = trim(join(" ", $va_dim_styles)); $vs_field_label = (isset($pa_options['label']) && (strlen($pa_options['label']) > 0)) ? $pa_options['label'] : $va_attr["LABEL"]; $vs_errors = ''; // TODO: PULL THIS FROM A CONFIG FILE $pa_options["display_form_field_tips"] = true; if (isset($pa_options['classname'])) { $vs_css_class_attr = ' class="'.$pa_options['classname'].'" '; } else { $vs_css_class_attr = ''; } if (!isset($pa_options['id'])) { $pa_options['id'] = $pa_options['name']; } if (!isset($pa_options['id'])) { $pa_options['id'] = $ps_field; } if (!isset($pa_options['maxPixelWidth']) || ((int)$pa_options['maxPixelWidth'] <= 0)) { $vn_max_pixel_width = $va_attr['MAX_PIXEL_WIDTH']; } else { $vn_max_pixel_width = (int)$pa_options['maxPixelWidth']; } if ($vn_max_pixel_width <= 0) { $vn_max_pixel_width = null; } if (!isset($pa_options["maxOptionLength"]) && isset($vn_display_width)) { $pa_options["maxOptionLength"] = isset($vn_display_width) ? $vn_display_width : null; } $vs_text_area_tag_name = 'textarea'; if (isset($pa_options["textAreaTagName"]) && $pa_options['textAreaTagName']) { $vs_text_area_tag_name = isset($pa_options['textAreaTagName']) ? $pa_options['textAreaTagName'] : null; } if (!isset($va_attr["DISPLAY_USE_COUNT"]) || !($vs_display_use_count = $va_attr["DISPLAY_USE_COUNT"])) { $vs_display_use_count = isset($pa_options["display_use_count"]) ? $pa_options["display_use_count"] : null; } if (!isset($va_attr["DISPLAY_SHOW_COUNT"]) || !($vb_display_show_count = (boolean)$va_attr["DISPLAY_SHOW_COUNT"])) { $vb_display_show_count = isset($pa_options["display_show_count"]) ? (boolean)$pa_options["display_show_count"] : null; } if (!isset($va_attr["DISPLAY_OMIT_ITEMS_WITH_ZERO_COUNT"]) || !($vb_display_omit_items__with_zero_count = (boolean)$va_attr["DISPLAY_OMIT_ITEMS_WITH_ZERO_COUNT"])) { $vb_display_omit_items__with_zero_count = isset($pa_options["display_omit_items__with_zero_count"]) ? (boolean)$pa_options["display_omit_items__with_zero_count"] : null; } if (!isset($va_attr["DISPLAY_OMIT_ITEMS_WITH_ZERO_COUNT"]) || !($va_display_use_count_filters = $va_attr["DISPLAY_USE_COUNT_FILTERS"])) { $va_display_use_count_filters = isset($pa_options["display_use_count_filters"]) ? $pa_options["display_use_count_filters"] : null; } if (!isset($va_display_use_count_filters) || !is_array($va_display_use_count_filters)) { $va_display_use_count_filters = null; } if (isset($pa_options["selection"]) && is_array($pa_options["selection"])) { $va_selection = isset($pa_options["selection"]) ? $pa_options["selection"] : null; } else { $va_selection = array(); } if (isset($pa_options["choiceList"]) && is_array($pa_options["choiceList"])) { $va_attr["BOUNDS_CHOICE_LIST"] = $pa_options["choiceList"]; } $vs_element = $vs_subelement = ""; if ($va_attr) { # --- Skip omitted fields completely if ($va_attr["DISPLAY_TYPE"] == DT_OMIT) { return ""; } if (!isset($pa_options["name"]) || !$pa_options["name"]) { $pa_options["name"] = htmlspecialchars($ps_field, ENT_QUOTES, 'UTF-8'); } $va_js = array(); $va_handlers = array("onclick", "onchange", "onkeypress", "onkeydown", "onkeyup"); foreach($va_handlers as $vs_handler) { if (isset($pa_options[$vs_handler]) && $pa_options[$vs_handler]) { $va_js[] = "$vs_handler='".($pa_options[$vs_handler])."'"; } } $vs_js = join(" ", $va_js); if (!isset($pa_options["value"])) { // allow field value to be overriden with value from options array $vm_field_value = $this->get($ps_field, $pa_options); } else { $vm_field_value = $pa_options["value"]; } $vm_raw_field_value = $vm_field_value; $vb_is_null = isset($va_attr["IS_NULL"]) ? $va_attr["IS_NULL"] : false; if (isset($pa_options['dont_show_null_value']) && $pa_options['dont_show_null_value']) { $vb_is_null = false; } if ( (!is_array($vm_field_value) && (strlen($vm_field_value) == 0)) && ( (!isset($vb_is_null) || (!$vb_is_null)) || ((isset($va_attr["DEFAULT_ON_NULL"]) ? $va_attr["DEFAULT_ON_NULL"] : 0)) ) ) { $vm_field_value = isset($va_attr["DEFAULT"]) ? $va_attr["DEFAULT"] : ""; } # --- Return hidden fields if ($va_attr["DISPLAY_TYPE"] == DT_HIDDEN) { return '<input type="hidden" name="'.$pa_options["name"].'" value="'.$this->escapeHTML($vm_field_value).'"/>'; } if (isset($pa_options["size"]) && ($pa_options["size"] > 0)) { $ps_size = " size='".$pa_options["size"]."'"; } else{ if ((($va_attr["DISPLAY_TYPE"] == DT_LIST_MULTIPLE) || ($va_attr["DISPLAY_TYPE"] == DT_LIST)) && ($vn_display_height > 1)) { $ps_size = " size='".$vn_display_height."'"; } else { $ps_size = ''; } } $vs_multiple_name_extension = ''; if ($vs_is_multiple = ((isset($pa_options["multiple"]) && $pa_options["multiple"]) || ($va_attr["DISPLAY_TYPE"] == DT_LIST_MULTIPLE) ? "multiple='1'" : "")) { $vs_multiple_name_extension = '[]'; if (!($vs_list_multiple_delimiter = $va_attr['LIST_MULTIPLE_DELIMITER'])) { $vs_list_multiple_delimiter = ';'; } $va_selection = array_merge($va_selection, explode($vs_list_multiple_delimiter, $vm_field_value)); } # --- Return form element switch($va_attr["FIELD_TYPE"]) { # ---------------------------- case(FT_NUMBER): case(FT_TEXT): case(FT_VARS): if ($va_attr["FIELD_TYPE"] == FT_VARS) { if (!$pa_options['show_text_field_for_vars']) { break; } if (!is_string($vm_field_value) && !is_numeric($vm_field_value)) { $vm_value = ''; } } if ($va_attr['DISPLAY_TYPE'] == DT_COUNTRY_LIST) { $vs_element = caHTMLSelect($ps_field, caGetCountryList(), array('id' => $ps_field), array('value' => $vm_field_value)); if ($va_attr['STATEPROV_FIELD']) { $vs_element .="<script type='text/javascript'>\n"; $vs_element .= "var caStatesByCountryList = ".json_encode(caGetStateList()).";\n"; $vs_element .= " jQuery('#{$ps_field}').click({countryID: '{$ps_field}', stateProvID: '".$va_attr['STATEPROV_FIELD']."', value: '".addslashes($this->get($va_attr['STATEPROV_FIELD']))."', statesByCountryList: caStatesByCountryList}, caUI.utils.updateStateProvinceForCountry); jQuery(document).ready(function() { caUI.utils.updateStateProvinceForCountry({data: {countryID: '{$ps_field}', stateProvID: '".$va_attr['STATEPROV_FIELD']."', value: '".addslashes($this->get($va_attr['STATEPROV_FIELD']))."', statesByCountryList: caStatesByCountryList}}); }); "; $vs_element .="</script>\n"; } break; } if ($va_attr['DISPLAY_TYPE'] == DT_STATEPROV_LIST) { $vs_element = caHTMLSelect($ps_field.'_select', array(), array('id' => $ps_field.'_select'), array('value' => $vm_field_value)); $vs_element .= caHTMLTextInput($ps_field.'_name', array('id' => $ps_field.'_text', 'value' => $vm_field_value)); break; } if (($vn_display_width > 0) && (in_array($va_attr["DISPLAY_TYPE"], array(DT_SELECT, DT_LIST, DT_LIST_MULTIPLE)))) { # # Generate auto generated <select> (from foreign key, from ca_lists or from field-defined choice list) # # TODO: CLEAN UP THIS CODE, RUNNING VARIOUS STAGES THROUGH HELPER FUNCTIONS; ALSO FORMALIZE AND DOCUMENT VARIOUS OPTIONS // ----- // from ca_lists // ----- if(!($vs_list_code = $pa_options['list_code'])) { if(isset($va_attr['LIST_CODE']) && $va_attr['LIST_CODE']) { $vs_list_code = $va_attr['LIST_CODE']; } } if ($vs_list_code) { $va_many_to_one_relations = $this->_DATAMODEL->getManyToOneRelations($this->tableName()); if ($va_many_to_one_relations[$ps_field]) { $vs_key = 'item_id'; } else { $vs_key = 'item_value'; } $vs_null_option = null; if (!$pa_options["nullOption"] && $vb_is_null) { $vs_null_option = "- NONE -"; } else { if ($pa_options["nullOption"]) { $vs_null_option = $pa_options["nullOption"]; } } $t_list = new ca_lists(); $va_list_attrs = array( 'id' => $pa_options['id']); if ($vn_max_pixel_width) { $va_list_attrs['style'] = $vs_width_style; } // NOTE: "raw" field value (value passed into method, before the model default value is applied) is used so as to allow the list default to be used if needed $vs_element = $t_list->getListAsHTMLFormElement($vs_list_code, $pa_options["name"].$vs_multiple_name_extension, $va_list_attrs, array('value' => $vm_raw_field_value, 'key' => $vs_key, 'nullOption' => $vs_null_option, 'readonly' => $pa_options['readonly'])); if (isset($pa_options['hide_select_if_no_options']) && $pa_options['hide_select_if_no_options'] && (!$vs_element)) { $vs_element = ""; $ps_format = '^ERRORS^ELEMENT'; } } else { // ----- // from related table // ----- $va_many_to_one_relations = $this->_DATAMODEL->getManyToOneRelations($this->tableName()); if (isset($va_many_to_one_relations[$ps_field]) && $va_many_to_one_relations[$ps_field]) { # # Use foreign key to populate <select> # $o_one_table = $this->_DATAMODEL->getTableInstance($va_many_to_one_relations[$ps_field]["one_table"]); $vs_one_table_primary_key = $o_one_table->primaryKey(); if ($o_one_table->isHierarchical()) { # # Hierarchical <select> # $va_hier = $o_one_table->getHierarchyAsList(0, $vs_display_use_count, $va_display_use_count_filters, $vb_display_omit_items__with_zero_count); $va_display_fields = $va_attr["DISPLAY_FIELD"]; if (!in_array($vs_one_table_primary_key, $va_display_fields)) { $va_display_fields[] = $o_one_table->tableName().".".$vs_one_table_primary_key; } if (!is_array($va_display_fields) || sizeof($va_display_fields) < 1) { $va_display_fields = array("*"); } $vs_hier_parent_id_fld = $o_one_table->getProperty("HIER_PARENT_ID_FLD"); $va_options = array(); if ($pa_options["nullOption"]) { $va_options[""] = array($pa_options["nullOption"]); } $va_suboptions = array(); $va_suboption_values = array(); $vn_selected = 0; $vm_cur_top_level_val = null; $vm_selected_top_level_val = null; foreach($va_hier as $va_option) { if (!$va_option["NODE"][$vs_hier_parent_id_fld]) { continue; } $vn_val = $va_option["NODE"][$o_one_table->primaryKey()]; $vs_selected = ($vn_val == $vm_field_value) ? 'selected="1"' : ""; $vn_indent = $va_option["LEVEL"] - 1; $va_display_data = array(); foreach ($va_display_fields as $vs_fld) { $va_bits = explode(".", $vs_fld); if ($va_bits[1] != $vs_one_table_primary_key) { $va_display_data[] = $va_option["NODE"][$va_bits[1]]; } } $vs_option_label = join(" ", $va_display_data); $va_options[$vn_val] = array($vs_option_label, $vn_indent, $va_option["HITS"], $va_option['NODE']); } if (sizeof($va_options) == 0) { $vs_element = isset($pa_options['empty_message']) ? $pa_options['empty_message'] : 'No options available'; } else { $vs_element = "<select name='".$pa_options["name"].$vs_multiple_name_extension."' ".$vs_js." ".$vs_is_multiple." ".$ps_size." id='".$pa_options["id"].$vs_multiple_name_extension."' {$vs_css_class_attr} style='{$vs_dim_style}'".($pa_options['readonly'] ? ' disabled="disabled" ' : '').">\n"; if (!$pa_options["nullOption"] && $vb_is_null) { $vs_element .= "<option value=''>- NONE -</option>\n"; } else { if ($pa_options["nullOption"]) { $vs_element .= "<option value=''>".$pa_options["nullOption"]."</option>\n"; } } foreach($va_options as $vn_val => $va_option_info) { $vs_selected = (($vn_val == $vm_field_value) || in_array($vn_val, $va_selection)) ? "selected='selected'" : ""; $vs_element .= "<option value='".$vn_val."' $vs_selected>"; $vn_indent = ($va_option_info[1]) * 2; $vs_indent = ""; if ($vn_indent > 0) { $vs_indent = str_repeat("&nbsp;", ($vn_indent - 1) * 2)." "; $vn_indent++; } $vs_option_text = $va_option_info[0]; $vs_use_count = ""; if($vs_display_use_count && $vb_display_show_count&& ($vn_val != "")) { $vs_use_count = " (".intval($va_option_info[2]).")"; } $vs_display_message = ''; if (is_array($pa_options['displayMessageForFieldValues'])) { foreach($pa_options['displayMessageForFieldValues'] as $vs_df => $va_df_vals) { if ((isset($va_option_info[3][$vs_df])) && is_array($va_df_vals)) { $vs_tmp = $va_option_info[3][$vs_df]; if (isset($va_df_vals[$vs_tmp])) { $vs_display_message = ' '.$va_df_vals[$vs_tmp]; } } } } if ( ($pa_options["maxOptionLength"]) && (strlen($vs_option_text) + strlen($vs_use_count) + $vn_indent > $pa_options["maxOptionLength"]) ) { if (($vn_strlen = $pa_options["maxOptionLength"] - strlen($vs_indent) - strlen($vs_use_count) - 3) < $pa_options["maxOptionLength"]) { $vn_strlen = $pa_options["maxOptionLength"]; } $vs_option_text = unicode_substr($vs_option_text, 0, $vn_strlen)."..."; } $vs_element .= $vs_indent.$vs_option_text.$vs_use_count.$vs_display_message."</option>\n"; } $vs_element .= "</select>\n"; } } else { # # "Flat" <select> # if (!is_array($va_display_fields = $pa_options["DISPLAY_FIELD"])) { $va_display_fields = $va_attr["DISPLAY_FIELD"]; } if (!is_array($va_display_fields)) { return "Configuration error: DISPLAY_FIELD directive for field '$ps_field' must be an array of field names in the format tablename.fieldname"; } if (!in_array($vs_one_table_primary_key, $va_display_fields)) { $va_display_fields[] = $o_one_table->tableName().".".$vs_one_table_primary_key; } if (!is_array($va_display_fields) || sizeof($va_display_fields) < 1) { $va_display_fields = array("*"); } $vs_sql = " SELECT * FROM ".$va_many_to_one_relations[$ps_field]["one_table"]." "; if (isset($pa_options["WHERE"]) && (is_array($pa_options["WHERE"]) && ($vs_where = join(" AND ",$pa_options["WHERE"]))) || ((is_array($va_attr["DISPLAY_WHERE"])) && ($vs_where = join(" AND ",$va_attr["DISPLAY_WHERE"])))) { $vs_sql .= " WHERE $vs_where "; } if ((isset($va_attr["DISPLAY_ORDERBY"])) && ($va_attr["DISPLAY_ORDERBY"]) && ($vs_orderby = join(",",$va_attr["DISPLAY_ORDERBY"]))) { $vs_sql .= " ORDER BY $vs_orderby "; } $qr_res = $o_db->query($vs_sql); if ($o_db->numErrors()) { $vs_element = "Error creating menu: ".join(';', $o_db->getErrors()); break; } $va_opts = array(); if (isset($pa_options["nullOption"]) && $pa_options["nullOption"]) { $va_opts[$pa_options["nullOption"]] = array($pa_options["nullOption"], null); } else { if ($vb_is_null) { $va_opts["- NONE -"] = array("- NONE -", null); } } if ($pa_options["select_item_text"]) { $va_opts[$pa_options["select_item_text"]] = array($pa_options["select_item_text"], null); } $va_fields = array(); foreach($va_display_fields as $vs_field) { $va_tmp = explode(".", $vs_field); $va_fields[] = $va_tmp[1]; } while ($qr_res->nextRow()) { $vs_display = ""; foreach($va_fields as $vs_field) { if ($vs_field != $vs_one_table_primary_key) { $vs_display .= $qr_res->get($vs_field). " "; } } $va_opts[] = array($vs_display, $qr_res->get($vs_one_table_primary_key), $qr_res->getRow()); } if (sizeof($va_opts) == 0) { $vs_element = isset($pa_options['empty_message']) ? $pa_options['empty_message'] : 'No options available'; } else { if (isset($pa_options['hide_select_if_only_one_option']) && $pa_options['hide_select_if_only_one_option'] && (sizeof($va_opts) == 1)) { $vs_element = "<input type='hidden' name='".$pa_options["name"]."' ".$vs_js." ".$ps_size." id='".$pa_options["id"]."' value='".($vm_field_value ? $vm_field_value : $va_opts[0][1])."' {$vs_css_class_attr}/>"; $ps_format = '^ERRORS^ELEMENT'; } else { $vs_element = "<select name='".$pa_options["name"].$vs_multiple_name_extension."' ".$vs_js." ".$vs_is_multiple." ".$ps_size." id='".$pa_options["id"].$vs_multiple_name_extension."' {$vs_css_class_attr} style='{$vs_dim_style}'".($pa_options['readonly'] ? ' disabled="disabled" ' : '').">\n"; foreach ($va_opts as $va_opt) { $vs_option_text = $va_opt[0]; $vs_value = $va_opt[1]; $vs_selected = (($vs_value == $vm_field_value) || in_array($vs_value, $va_selection)) ? "selected='selected'" : ""; $vs_use_count = ""; if ($vs_display_use_count && $vb_display_show_count && ($vs_value != "")) { $vs_use_count = "(".intval($va_option_info[2]).")"; } if ( ($pa_options["maxOptionLength"]) && (strlen($vs_option_text) + strlen($vs_use_count) > $pa_options["maxOptionLength"]) ) { $vs_option_text = unicode_substr($vs_option_text,0, $pa_options["maxOptionLength"] - 3 - strlen($vs_use_count))."..."; } $vs_display_message = ''; if (is_array($pa_options['displayMessageForFieldValues'])) { foreach($pa_options['displayMessageForFieldValues'] as $vs_df => $va_df_vals) { if ((isset($va_opt[2][$vs_df])) && is_array($va_df_vals)) { $vs_tmp = $va_opt[2][$vs_df]; if (isset($va_df_vals[$vs_tmp])) { $vs_display_message = ' '.$va_df_vals[$vs_tmp]; } } } } $vs_element.= "<option value='$vs_value' $vs_selected>"; $vs_element .= $vs_option_text.$vs_use_count.$vs_display_message; $vs_element .= "</option>\n"; } $vs_element .= "</select>\n"; } } } } else { # # choice list # $vs_element = ''; // if 'LIST' is set try to stock over choice list with the contents of the list if (isset($va_attr['LIST']) && $va_attr['LIST']) { // NOTE: "raw" field value (value passed into method, before the model default value is applied) is used so as to allow the list default to be used if needed $vs_element = ca_lists::getListAsHTMLFormElement($va_attr['LIST'], $pa_options["name"].$vs_multiple_name_extension, array('class' => $pa_options['classname'], 'id' => $pa_options['id']), array('key' => 'item_value', 'value' => $vm_raw_field_value, 'nullOption' => $pa_options['nullOption'], 'readonly' => $pa_options['readonly'])); } if (!$vs_element && (isset($va_attr["BOUNDS_CHOICE_LIST"]) && is_array($va_attr["BOUNDS_CHOICE_LIST"]))) { if (sizeof($va_attr["BOUNDS_CHOICE_LIST"]) == 0) { $vs_element = isset($pa_options['empty_message']) ? $pa_options['empty_message'] : 'No options available'; } else { $vs_element = "<select name='".$pa_options["name"].$vs_multiple_name_extension."' ".$vs_js." ".$vs_is_multiple." ".$ps_size." id='".$pa_options['id'].$vs_multiple_name_extension."' {$vs_css_class_attr} style='{$vs_dim_style}'".($pa_options['readonly'] ? ' disabled="disabled" ' : '').">\n"; if ($pa_options["select_item_text"]) { $vs_element.= "<option value=''>".$this->escapeHTML($pa_options["select_item_text"])."</option>\n"; } if (!$pa_options["nullOption"] && $vb_is_null) { $vs_element .= "<option value=''>- NONE -</option>\n"; } else { if ($pa_options["nullOption"]) { $vs_element .= "<option value=''>".$pa_options["nullOption"]."</option>\n"; } } foreach($va_attr["BOUNDS_CHOICE_LIST"] as $vs_option => $vs_value) { $vs_selected = ((strval($vs_value) === strval($vm_field_value)) || in_array($vs_value, $va_selection)) ? "selected='selected'" : ""; if (($pa_options["maxOptionLength"]) && (strlen($vs_option) > $pa_options["maxOptionLength"])) { $vs_option = unicode_substr($vs_option, 0, $pa_options["maxOptionLength"] - 3)."..."; } $vs_element.= "<option value='$vs_value' $vs_selected>".$this->escapeHTML($vs_option)."</option>\n"; } $vs_element .= "</select>\n"; } } } } } else { if ($va_attr["DISPLAY_TYPE"] === DT_COLORPICKER) { // COLORPICKER $vs_element = '<input name="'.$pa_options["name"].'" type="hidden" size="'.($pa_options['size'] ? $pa_options['size'] : $vn_display_width).'" value="'.$this->escapeHTML($vm_field_value).'" '.$vs_js.' id=\''.$pa_options["id"]."' style='{$vs_dim_style}'/>\n"; $vs_element .= '<div id="'.$pa_options["id"].'_colorchip" class="colorpicker_chip" style="background-color: #'.$vm_field_value.'"><!-- empty --></div>'; $vs_element .= "<script type='text/javascript'>jQuery(document).ready(function() { jQuery('#".$pa_options["name"]."_colorchip').ColorPicker({ onShow: function (colpkr) { jQuery(colpkr).fadeIn(500); return false; }, onHide: function (colpkr) { jQuery(colpkr).fadeOut(500); return false; }, onChange: function (hsb, hex, rgb) { jQuery('#".$pa_options["name"]."').val(hex); jQuery('#".$pa_options["name"]."_colorchip').css('backgroundColor', '#' + hex); }, color: jQuery('#".$pa_options["name"]."').val() })}); </script>\n"; if (method_exists('JavascriptLoadManager', 'register')) { JavascriptLoadManager::register('jquery', 'colorpicker'); } } else { # normal controls: all non-DT_SELECT display types are returned as DT_FIELD's. We could generate # radio-button controls for foreign key and choice lists, but we don't bother because it's never # really necessary. if ($vn_display_height > 1) { $vs_element = '<'.$vs_text_area_tag_name.' name="'.$pa_options["name"].'" rows="'.$vn_display_height.'" cols="'.$vn_display_width.'"'.($pa_options['readonly'] ? ' readonly="readonly" ' : '').' wrap="soft" '.$vs_js.' id=\''.$pa_options["id"]."' style='{$vs_dim_style}' ".$vs_css_class_attr.">".$this->escapeHTML($vm_field_value).'</'.$vs_text_area_tag_name.'>'."\n"; } else { $vs_element = '<input name="'.$pa_options["name"].'" type="text" size="'.($pa_options['size'] ? $pa_options['size'] : $vn_display_width).'"'.($pa_options['readonly'] ? ' readonly="readonly" ' : '').' value="'.$this->escapeHTML($vm_field_value).'" '.$vs_js.' id=\''.$pa_options["id"]."' {$vs_css_class_attr} style='{$vs_dim_style}'/>\n"; } if (isset($va_attr['UNIQUE_WITHIN']) && is_array($va_attr['UNIQUE_WITHIN'])) { $va_within_fields = array(); foreach($va_attr['UNIQUE_WITHIN'] as $vs_within_field) { $va_within_fields[$vs_within_field] = $this->get($vs_within_field); } $vs_element .= "<span id='".$pa_options["id"].'_uniqueness_status'."'></span>"; $vs_element .= "<script type='text/javascript'> caUI.initUniquenessChecker({ errorIcon: '".$pa_options['error_icon']."', processIndicator: '".$pa_options['progress_indicator']."', statusID: '".$pa_options["id"]."_uniqueness_status', lookupUrl: '".$pa_options['lookup_url']."', formElementID: '".$pa_options["id"]."', row_id: ".intval($this->getPrimaryKey()).", table_num: ".$this->tableNum().", field: '".$ps_field."', withinFields: ".json_encode($va_within_fields).", alreadyInUseMessage: '".addslashes(_t('Value must be unique. Please try another.'))."' }); </script>"; } } } break; # ---------------------------- case (FT_TIMESTAMP): if ($this->get($ps_field)) { # is timestamp set? $vs_element = $this->escapeHTML($vm_field_value); # return printed date } else { $vs_element = "[Not set]"; # return text instead of 1969 date } break; # ---------------------------- case (FT_DATETIME): case (FT_HISTORIC_DATETIME): case (FT_DATE): case (FT_HISTORIC_DATE): if (!$vm_field_value) { $vm_field_value = $pa_options['value']; } switch($va_attr["DISPLAY_TYPE"]) { case DT_TEXT: $vs_element = $vm_field_value ? $vm_field_value : "[Not set]"; break; default: $vn_max_length = $va_attr["BOUNDS_LENGTH"][1]; $vs_max_length = ''; if ($vn_max_length > 0) $vs_max_length = 'maxlength="'.$vn_max_length.'"'; if ($vn_display_height > 1) { $vs_element = '<'.$vs_text_area_tag_name.' name="'.$pa_options["name"].'" rows="'.$vn_display_height.'" cols="'.$vn_display_width.'" wrap="soft" '.$vs_js.' '.$vs_css_class_attr." style='{$vs_dim_style}'".($pa_options['readonly'] ? ' readonly="readonly" ' : '').">".$this->escapeHTML($vm_field_value).'</'.$vs_text_area_tag_name.'>'; } else { $vs_element = '<input type="text" name="'.$pa_options["name"].'" value="'.$this->escapeHTML($vm_field_value)."\" size='{$vn_display_width}' {$vs_max_length} {$vs_js} {$vs_css_class_attr} style='{$vs_dim_style}'".($pa_options['readonly'] ? ' readonly="readonly" ' : '')."/>"; } break; } break; # ---------------------------- case(FT_TIME): if (!$this->get($ps_field)) { $vm_field_value = ""; } switch($va_attr["DISPLAY_TYPE"]) { case DT_TEXT: $vs_element = $vm_field_value ? $vm_field_value : "[Not set]"; break; default: $vn_max_length = $va_attr["BOUNDS_LENGTH"][1]; $vs_max_length = ''; if ($vn_max_length > 0) $vs_max_length = 'maxlength="'.$vn_max_length.'"'; if ($vn_display_height > 1) { $vs_element = '<'.$vs_text_area_tag_name.' name="'.$pa_options["name"].'" rows="'.$vn_display_height.'" cols="'.$vn_display_width.'" wrap="soft" '.$vs_js.' '.$vs_css_class_attr." style='{$vs_dim_style}'".($pa_options['readonly'] ? ' readonly="readonly" ' : '').">".$this->escapeHTML($vm_field_value).'</'.$vs_text_area_tag_name.'>'; } else { $vs_element = '<input type="text" name="'.$pa_options["name"].'" value="'.$this->escapeHTML($vm_field_value)."\" size='{$vn_display_width}' {$vs_max_length} {$vs_js} {$vs_css_class_attr}' style='{$vs_dim_style}'".($pa_options['readonly'] ? ' readonly="readonly" ' : '')."/>"; } break; } break; # ---------------------------- case(FT_DATERANGE): case(FT_HISTORIC_DATERANGE): switch($va_attr["DISPLAY_TYPE"]) { case DT_TEXT: $vs_element = $vm_field_value ? $vm_field_value : "[Not set]"; break; default: $vn_max_length = $va_attr["BOUNDS_LENGTH"][1]; $vs_max_length = ''; if ($vn_max_length > 0) $vs_max_length = 'maxlength="'.$vn_max_length.'"'; if ($vn_display_height > 1) { $vs_element = '<'.$vs_text_area_tag_name.' name="'.$pa_options["name"].'" rows="'.$vn_display_height.'" cols="'.$vn_display_width.'" wrap="soft" '.$vs_js.' '.$vs_css_class_attr." style='{$vs_dim_style}'".($pa_options['readonly'] ? ' readonly="readonly" ' : '').">".$this->escapeHTML($vm_field_value).'</'.$vs_text_area_tag_name.'>'; } else { $vs_element = '<input type="text" name="'.$pa_options["name"].'" value="'.$this->escapeHTML($vm_field_value)."\" size='{$vn_display_width}' {$vn_max_length} {$vs_js} {$vs_css_class_attr} style='{$vs_dim_style}'".($pa_options['readonly'] ? ' readonly="readonly" ' : '')."/>"; } break; } break; # ---------------------------- case (FT_TIMERANGE): switch($va_attr["DISPLAY_TYPE"]) { case DT_TEXT: $vs_element = $vm_field_value ? $vm_field_value : "[Not set]"; break; default: $vn_max_length = $va_attr["BOUNDS_LENGTH"][1]; $vs_max_length = ''; if ($vn_max_length > 0) $vs_max_length = 'maxlength="'.$vn_max_length.'"'; if ($vn_display_height > 1) { $vs_element = '<'.$vs_text_area_tag_name.' name="'.$pa_options["name"].'" rows="'.$vn_display_height.'" cols="'.$vn_display_width.'" wrap="soft" '.$vs_js.' '.$vs_css_class_attr." style='{$vs_dim_style}'".($pa_options['readonly'] ? ' readonly="readonly" ' : '').">".$this->escapeHTML($vm_field_value).'</'.$vs_text_area_tag_name.'>'; } else { $vs_element = '<input type="text" name="'.$pa_options["name"].'" value="'.$this->escapeHTML($vm_field_value)."\" size='{$vn_display_width}' {$vs_max_length} {$vs_js} {$vs_css_class_attr} style='{$vs_dim_style}'".($pa_options['readonly'] ? ' readonly="readonly" ' : '')."/>"; } break; } break; # ---------------------------- case(FT_TIMECODE): $o_tp = new TimecodeParser(); $o_tp->setParsedValueInSeconds($vm_field_value); $vs_timecode = $o_tp->getText("COLON_DELIMITED", array("BLANK_ON_ZERO" => true)); $vn_max_length = $va_attr["BOUNDS_LENGTH"][1]; $vs_max_length = ''; if ($vn_max_length > 0) $vs_max_length = 'maxlength="'.$vn_max_length.'"'; if ($vn_display_height > 1) { $vs_element = '<'.$vs_text_area_tag_name.' name="'.$pa_options["name"].'" rows="'.$vn_display_height.'" cols="'.$vn_display_width.'" wrap="soft" '.$vs_js.' '.$vs_css_class_attr." style='{$vs_dim_style}'".($pa_options['readonly'] ? ' readonly="readonly" ' : '').">".$this->escapeHTML($vs_timecode).'</'.$vs_text_area_tag_name.'>'; } else { $vs_element = '<input type="text" NAME="'.$pa_options["name"].'" value="'.$this->escapeHTML($vs_timecode)."\" size='{$vn_display_width}' {$vs_max_length} {$vs_js} {$vs_css_class_attr} style='{$vs_dim_style}'".($pa_options['readonly'] ? ' readonly="readonly" ' : '')."/>"; } break; # ---------------------------- case(FT_MEDIA): case(FT_FILE): $vs_element = '<input type="file" name="'.$pa_options["name"].'" '.$vs_js.'/>'; // show current media icon if ($vs_version = (array_key_exists('displayMediaVersion', $pa_options)) ? $pa_options['displayMediaVersion'] : 'icon') { $va_valid_versions = $this->getMediaVersions($ps_field); if (!in_array($vs_version, $va_valid_versions)) { $vs_version = $va_valid_versions[0]; } if ($vs_tag = $this->getMediaTag($ps_field, $vs_version)) { $vs_element .= $vs_tag; } } break; # ---------------------------- case(FT_PASSWORD): $vn_max_length = $va_attr["BOUNDS_LENGTH"][1]; $vs_max_length = ''; if ($vn_max_length > 0) $vs_max_length = 'maxlength="'.$vn_max_length.'"'; $vs_element = '<input type="password" name="'.$pa_options["name"].'" value="'.$this->escapeHTML($vm_field_value).'" size="'.$vn_display_width.'" '.$vs_max_length.' '.$vs_js.' autocomplete="off" '.$vs_css_class_attr." style='{$vs_dim_style}'".($pa_options['readonly'] ? ' readonly="readonly" ' : '')."/>"; break; # ---------------------------- case(FT_BIT): switch($va_attr["DISPLAY_TYPE"]) { case (DT_FIELD): $vs_element = '<input type="text" name="'.$pa_options["name"]."\" value='{$vm_field_value}' maxlength='1' size='2' {$vs_js} style='{$vs_dim_style}'".($pa_options['readonly'] ? ' readonly="readonly" ' : '')."/>"; break; case (DT_SELECT): $vs_element = "<select name='".$pa_options["name"]."' ".$vs_js." id='".$pa_options["id"]."' {$vs_css_class_attr} style='{$vs_dim_style}'".($pa_options['readonly'] ? ' disabled="disabled" ' : '').">\n"; foreach(array("Yes" => 1, "No" => 0) as $vs_option => $vs_value) { $vs_selected = ($vs_value == $vm_field_value) ? "selected='selected'" : ""; $vs_element.= "<option value='$vs_value' {$vs_selected}".($pa_options['readonly'] ? ' disabled="disabled" ' : '').">$vs_option</option>\n"; } $vs_element .= "</select>\n"; break; case (DT_CHECKBOXES): $vs_element = '<input type="checkbox" name="'.$pa_options["name"].'" value="1" '.($vm_field_value ? 'checked="1"' : '').' '.$vs_js.($pa_options['readonly'] ? ' disabled="disabled" ' : '').' id="'.$pa_options["id"].'"/>'; break; case (DT_RADIO_BUTTONS): $vs_element = 'Radio buttons not supported for bit-type fields'; break; } break; # ---------------------------- } # Apply format $vs_formatting = ""; if (isset($pa_options['field_errors']) && is_array($pa_options['field_errors']) && sizeof($pa_options['field_errors'])) { $va_field_errors = array(); foreach($pa_options['field_errors'] as $o_e) { $va_field_errors[] = $o_e->getErrorDescription(); } $vs_errors = join('; ', $va_field_errors); } else { $vs_errors = ''; } if (is_null($ps_format)) { if (isset($pa_options['field_errors']) && is_array($pa_options['field_errors']) && sizeof($pa_options['field_errors'])) { $ps_format = $this->_CONFIG->get('form_element_error_display_format'); } else { $ps_format = $this->_CONFIG->get('form_element_display_format'); } } if ($ps_format != '') { $ps_formatted_element = $ps_format; $ps_formatted_element = str_replace("^ELEMENT", $vs_element, $ps_formatted_element); if ($vs_subelement) { $ps_formatted_element = str_replace("^SUB_ELEMENT", $vs_subelement, $ps_formatted_element); } $vb_fl_display_form_field_tips = false; if ( $pa_options["display_form_field_tips"] || (!isset($pa_options["display_form_field_tips"]) && $va_attr["DISPLAY_DESCRIPTION"]) || (!isset($pa_options["display_form_field_tips"]) && !isset($va_attr["DISPLAY_DESCRIPTION"]) && $vb_fl_display_form_field_tips) ) { if (preg_match("/\^DESCRIPTION/", $ps_formatted_element)) { $ps_formatted_element = str_replace("^LABEL",$vs_field_label, $ps_formatted_element); $ps_formatted_element = str_replace("^DESCRIPTION",$va_attr["DESCRIPTION"], $ps_formatted_element); } else { // no explicit placement of description text, so... $vs_field_id = '_'.$this->tableName().'_'.$this->getPrimaryKey().'_'.$pa_options["name"].'_'.$pa_options['form_name']; $ps_formatted_element = str_replace("^LABEL",'<span id="'.$vs_field_id.'">'.$vs_field_label.'</span>', $ps_formatted_element); if (!isset($pa_options['no_tooltips']) || !$pa_options['no_tooltips']) { TooltipManager::add('#'.$vs_field_id, "<h3>{$vs_field_label}</h3>".$va_attr["DESCRIPTION"], $pa_options['tooltip_namespace']); } } if (!isset($va_attr["SUB_LABEL"])) { $va_attr["SUB_LABEL"] = ''; } if (!isset($va_attr["SUB_DESCRIPTION"])) { $va_attr["SUB_DESCRIPTION"] = ''; } if (preg_match("/\^SUB_DESCRIPTION/", $ps_formatted_element)) { $ps_formatted_element = str_replace("^SUB_LABEL",$va_attr["SUB_LABEL"], $ps_formatted_element); $ps_formatted_element = str_replace("^SUB_DESCRIPTION", $va_attr["SUB_DESCRIPTION"], $ps_formatted_element); } else { // no explicit placement of description text, so... // ... make label text itself rollover for description text because no icon was specified $ps_formatted_element = str_replace("^SUB_LABEL",$va_attr["SUB_LABEL"], $ps_formatted_element); } } else { $ps_formatted_element = str_replace("^LABEL", $vs_field_label, $ps_formatted_element); $ps_formatted_element = str_replace("^DESCRIPTION", "", $ps_formatted_element); if ($vs_subelement) { $ps_formatted_element = str_replace("^SUB_LABEL", $va_attr["SUB_LABEL"], $ps_formatted_element); $ps_formatted_element = str_replace("^SUB_DESCRIPTION", "", $ps_formatted_element); } } $ps_formatted_element = str_replace("^ERRORS", $vs_errors, $ps_formatted_element); $ps_formatted_element = str_replace("^EXTRA", isset($pa_options['extraLabelText']) ? $pa_options['extraLabelText'] : '', $ps_formatted_element); $vs_element = $ps_formatted_element; } else { $vs_element .= "<br/>".$vs_subelement; } return $vs_element; } else { $this->postError(716,_t("'%1' does not exist in this object", $ps_field),"BaseModel->formElement()"); return ""; } return ""; } # -------------------------------------------------------------------------------------------- /** * Get list name * * @access public * @return string */ public function getListName() { if (is_array($va_display_fields = $this->getProperty('LIST_FIELDS'))) { $va_tmp = array(); $vs_delimiter = $this->getProperty('LIST_DELIMITER'); foreach($va_display_fields as $vs_display_field) { $va_tmp[] = $this->get($vs_display_field); } return join($vs_delimiter, $va_tmp); } return null; } # -------------------------------------------------------------------------------------------- /** * Modifies text for HTML use (i.e. passing it through stripslashes and htmlspecialchars) * * @param string $ps_text * @return string */ public function escapeHTML($ps_text) { $opa_php_version = caGetPHPVersion(); if ($opa_php_version['versionInt'] >= 50203) { $ps_text = htmlspecialchars(stripslashes($ps_text), ENT_QUOTES, $this->getCharacterSet(), false); } else { $ps_text = htmlspecialchars(stripslashes($ps_text), ENT_QUOTES, $this->getCharacterSet()); } return str_replace("&amp;#", "&#", $ps_text); } # -------------------------------------------------------------------------------------------- /** * Returns list of names of fields that must be defined */ public function getMandatoryFields() { $va_fields = $this->getFormFields(true); $va_many_to_one_relations = $this->_DATAMODEL->getManyToOneRelations($this->tableName()); $va_mandatory_fields = array(); foreach($va_fields as $vs_field => $va_info) { if (isset($va_info['IDENTITY']) && $va_info['IDENTITY']) { continue;} if ((isset($va_many_to_one_relations[$vs_field]) && $va_many_to_one_relations[$vs_field]) && (!isset($va_info['IS_NULL']) || !$va_info['IS_NULL'])) { $va_mandatory_fields[] = $vs_field; continue; } if (isset($va_info['BOUNDS_LENGTH']) && is_array($va_info['BOUNDS_LENGTH'])) { if ($va_info['BOUNDS_LENGTH'][0] > 0) { $va_mandatory_fields[] = $vs_field; continue; } } } return $va_mandatory_fields; } # -------------------------------------------------------------------------------------------- /** * Returns a list_code for a list in the ca_lists table that is used for the specified field * Return null if the field has no list associated with it */ public function getFieldListCode($ps_field) { $va_field_info = $this->getFieldInfo($ps_field); return ($vs_list_code = $va_field_info['LIST_CODE']) ? $vs_list_code : null; } # -------------------------------------------------------------------------------------------- /** * Return list of items specified for the given field. * * @param string $ps_field The name of the field * @param string $ps_list_code Optional list code or list_id to force return of, overriding the list configured in the model * @return array A list of items, filtered on the current user locale; the format is the same as that returned by ca_lists::getItemsForList() */ public function getFieldList($ps_field, $ps_list_code=null) { $t_list = new ca_lists(); return caExtractValuesByUserLocale($t_list->getItemsForList($ps_list_code ? $ps_list_code : $this->getFieldListCode($ps_field))); } # -------------------------------------------------------------------------------------------- /** * Creates a relationship between the currently loaded row and the specified row. * * @param mixed $pm_rel_table_name_or_num Table name (eg. "ca_entities") or number as defined in datamodel.conf of table containing row to creation relationship to. * @param int $pn_rel_id primary key value of row to creation relationship to. * @param mixed $pm_type_id Relationship type type_code or type_id, as defined in the ca_relationship_types table. This is required for all relationships that use relationship types. This includes all of the most common types of relationships. * @param string $ps_effective_date Optional date expression to qualify relation with. Any expression that the TimeExpressionParser can handle is supported here. * @param string $ps_source_info Text field for storing information about source of relationship. Not currently used. * @param string $ps_direction Optional direction specification for self-relationships (relationships linking two rows in the same table). Valid values are 'ltor' (left-to-right) and 'rtol' (right-to-left); the direction determines which "side" of the relationship the currently loaded row is on: 'ltor' puts the current row on the left side. For many self-relations the direction determines the nature and display text for the relationship. * @return boolean True on success, false on error. */ public function addRelationship($pm_rel_table_name_or_num, $pn_rel_id, $pm_type_id=null, $ps_effective_date=null, $ps_source_info=null, $ps_direction=null, $pn_rank=null) { if(!($va_rel_info = $this->_getRelationshipInfo($pm_rel_table_name_or_num))) { $this->postError(1240, _t('Related table specification "%1" is not valid', $pm_rel_table_name_or_num), 'BaseModel->addRelationship()'); return false; } $t_item_rel = $va_rel_info['t_item_rel']; if ($pm_type_id && !is_numeric($pm_type_id)) { $t_rel_type = new ca_relationship_types(); if ($vs_linking_table = $t_rel_type->getRelationshipTypeTable($this->tableName(), $t_item_rel->tableName())) { $pn_type_id = $t_rel_type->getRelationshipTypeID($vs_linking_table, $pm_type_id); } } else { $pn_type_id = $pm_type_id; } if ($va_rel_info['related_table_name'] == $this->tableName()) { // is self relation $t_item_rel->setMode(ACCESS_WRITE); // is self relationship if ($ps_direction == 'rtol') { $t_item_rel->set($t_item_rel->getRightTableFieldName(), $this->getPrimaryKey()); $t_item_rel->set($t_item_rel->getLeftTableFieldName(), $pn_rel_id); } else { // default is left-to-right $t_item_rel->set($t_item_rel->getLeftTableFieldName(), $this->getPrimaryKey()); $t_item_rel->set($t_item_rel->getRightTableFieldName(), $pn_rel_id); } $t_item_rel->set($t_item_rel->getTypeFieldName(), $pn_type_id); // TODO: verify type_id based upon type_id's of each end of the relationship if(!is_null($ps_effective_date)){ $t_item_rel->set('effective_date', $ps_effective_date); } if(!is_null($ps_source_info)){ $t_item_rel->set("source_info",$ps_source_info); } $t_item_rel->insert(); if ($t_item_rel->numErrors()) { $this->errors = $t_item_rel->errors; return false; } } else { switch(sizeof($va_rel_info['path'])) { case 3: // many-to-many relationship $t_rel = $this->getAppDatamodel()->getTableInstance($va_rel_info['related_table_name']); $t_item_rel->setMode(ACCESS_WRITE); $vs_left_table = $t_item_rel->getLeftTableName(); $vs_right_table = $t_item_rel->getRightTableName(); if ($this->tableName() == $vs_left_table) { // is lefty $t_item_rel->set($t_item_rel->getLeftTableFieldName(), $this->getPrimaryKey()); $t_item_rel->set($t_item_rel->getRightTableFieldName(), $pn_rel_id); } else { // is righty $t_item_rel->set($t_item_rel->getRightTableFieldName(), $this->getPrimaryKey()); $t_item_rel->set($t_item_rel->getLeftTableFieldName(), $pn_rel_id); } $t_item_rel->set('rank', $pn_rank); $t_item_rel->set($t_item_rel->getTypeFieldName(), $pn_type_id); // TODO: verify type_id based upon type_id's of each end of the relationship if(!is_null($ps_effective_date)){ $t_item_rel->set('effective_date', $ps_effective_date); } if(!is_null($ps_source_info)){ $t_item_rel->set("source_info",$ps_source_info); } $t_item_rel->insert(); if ($t_item_rel->numErrors()) { $this->errors = $t_item_rel->errors; return false; } case 2: // many-to-one relationship if ($this->tableName() == $va_rel_info['rel_keys']['one_table']) { if ($t_item_rel->load($pn_rel_id)) { $t_item_rel->setMode(ACCESS_WRITE); $t_item_rel->set($va_rel_info['rel_keys']['many_table_field'], $this->getPrimaryKey()); $t_item_rel->update(); if ($t_item_rel->numErrors()) { $this->errors = $t_item_rel->errors; return false; } } else { $t_item_rel->setMode(ACCESS_WRITE); $t_item_rel->set($t_item_rel->getLeftTableFieldName(), $this->getPrimaryKey()); $t_item_rel->set($t_item_rel->getRightTableFieldName(), $pn_rel_id); $t_item_rel->set($t_item_rel->getTypeFieldName(), $pn_type_id); $t_item_rel->insert(); if ($t_item_rel->numErrors()) { $this->errors = $t_item_rel->errors; return false; } } } else { $this->setMode(ACCESS_WRITE); $this->set($va_rel_info['rel_keys']['many_table_field'], $pn_rel_id); $this->update(); if ($this->numErrors()) { return false; } } break; default: return false; break; } } return true; } # -------------------------------------------------------------------------------------------- /** * Edits the data in an existing relationship between the currently loaded row and the specified row. * * @param mixed $pm_rel_table_name_or_num Table name (eg. "ca_entities") or number as defined in datamodel.conf of table containing row to create relationships to. * @param int $pn_relation_id primary key value of the relation to edit. * @param int $pn_rel_id primary key value of row to creation relationship to. * @param mixed $pm_type_id Relationship type type_code or type_id, as defined in the ca_relationship_types table. This is required for all relationships that use relationship types. This includes all of the most common types of relationships. * @param string $ps_effective_date Optional date expression to qualify relation with. Any expression that the TimeExpressionParser can handle is supported here. * @param string $ps_source_info Text field for storing information about source of relationship. Not currently used. * @param string $ps_direction Optional direction specification for self-relationships (relationships linking two rows in the same table). Valid values are 'ltor' (left-to-right) and 'rtol' (right-to-left); the direction determines which "side" of the relationship the currently loaded row is on: 'ltor' puts the current row on the left side. For many self-relations the direction determines the nature and display text for the relationship. * @return boolean True on success, false on error. */ public function editRelationship($pm_rel_table_name_or_num, $pn_relation_id, $pn_rel_id, $pm_type_id=null, $ps_effective_date=null, $pa_source_info=null, $ps_direction=null, $pn_rank=null) { if(!($va_rel_info = $this->_getRelationshipInfo($pm_rel_table_name_or_num))) { $this->postError(1240, _t('Related table specification "%1" is not valid', $pm_rel_table_name_or_num), 'BaseModel->editRelationship()'); return false; } $t_item_rel = $va_rel_info['t_item_rel']; if ($pm_type_id && !is_numeric($pm_type_id)) { $t_rel_type = new ca_relationship_types(); if ($vs_linking_table = $t_rel_type->getRelationshipTypeTable($this->tableName(), $t_item_rel->tableName())) { $pn_type_id = $t_rel_type->getRelationshipTypeID($vs_linking_table, $pm_type_id); } } else { $pn_type_id = $pm_type_id; } if ($va_rel_info['related_table_name'] == $this->tableName()) { // is self relation if ($t_item_rel->load($pn_relation_id)) { $t_item_rel->setMode(ACCESS_WRITE); if ($ps_direction == 'rtol') { $t_item_rel->set($t_item_rel->getRightTableFieldName(), $this->getPrimaryKey()); $t_item_rel->set($t_item_rel->getLeftTableFieldName(), $pn_rel_id); } else { // default is left-to-right $t_item_rel->set($t_item_rel->getLeftTableFieldName(), $this->getPrimaryKey()); $t_item_rel->set($t_item_rel->getRightTableFieldName(), $pn_rel_id); } $t_item_rel->set('rank', $pn_rank); $t_item_rel->set($t_item_rel->getTypeFieldName(), $pn_type_id); // TODO: verify type_id based upon type_id's of each end of the relationship if(!is_null($ps_effective_date)){ $t_item_rel->set('effective_date', $ps_effective_date); } if(!is_null($ps_source_info)){ $t_item_rel->set("source_info",$ps_source_info); } $t_item_rel->update(); if ($t_item_rel->numErrors()) { $this->errors = $t_item_rel->errors; return false; } } } else { switch(sizeof($va_rel_info['path'])) { case 3: // many-to-many relationship if ($t_item_rel->load($pn_relation_id)) { $t_item_rel->setMode(ACCESS_WRITE); $vs_left_table = $t_item_rel->getLeftTableName(); $vs_right_table = $t_item_rel->getRightTableName(); if ($this->tableName() == $vs_left_table) { // is lefty $t_item_rel->set($t_item_rel->getLeftTableFieldName(), $this->getPrimaryKey()); $t_item_rel->set($t_item_rel->getRightTableFieldName(), $pn_rel_id); } else { // is righty $t_item_rel->set($t_item_rel->getRightTableFieldName(), $this->getPrimaryKey()); $t_item_rel->set($t_item_rel->getLeftTableFieldName(), $pn_rel_id); } $t_item_rel->set('rank', $pn_rank); $t_item_rel->set($t_item_rel->getTypeFieldName(), $pn_type_id); // TODO: verify type_id based upon type_id's of each end of the relationship if(!is_null($ps_effective_date)){ $t_item_rel->set('effective_date', $ps_effective_date); } if(!is_null($ps_source_info)){ $t_item_rel->set("source_info",$ps_source_info); } $t_item_rel->update(); if ($t_item_rel->numErrors()) { $this->errors = $t_item_rel->errors; return false; } return true; } case 2: // many-to-one relations if ($this->tableName() == $va_rel_info['rel_keys']['one_table']) { if ($t_item_rel->load($pn_relation_id)) { $t_item_rel->setMode(ACCESS_WRITE); $t_item_rel->set($va_rel_info['rel_keys']['many_table_field'], null); $t_item_rel->update(); if ($t_item_rel->numErrors()) { $this->errors = $t_item_rel->errors; return false; } } if ($t_item_rel->load($pn_rel_id)) { $t_item_rel->setMode(ACCESS_WRITE); $t_item_rel->set($va_rel_info['rel_keys']['many_table_field'], $this->getPrimaryKey()); $t_item_rel->update(); if ($t_item_rel->numErrors()) { $this->errors = $t_item_rel->errors; return false; } } } else { $this->setMode(ACCESS_WRITE); $this->set($va_rel_info['rel_keys']['many_table_field'], $pn_rel_id); $this->update(); if ($this->numErrors()) { return false; } } break; default: return false; break; } } return false; } # -------------------------------------------------------------------------------------------- /** * Removes the specified relationship * * @param mixed $pm_rel_table_name_or_num Table name (eg. "ca_entities") or number as defined in datamodel.conf of table containing row to edit relationships to. * @param int $pn_relation_id primary key value of the relation to remove. * @return boolean True on success, false on error. */ public function removeRelationship($pm_rel_table_name_or_num, $pn_relation_id) { if(!($va_rel_info = $this->_getRelationshipInfo($pm_rel_table_name_or_num))) { $this->postError(1240, _t('Related table specification "%1" is not valid', $pm_rel_table_name_or_num), 'BaseModel->removeRelationship()'); return false; } $t_item_rel = $va_rel_info['t_item_rel']; if ($va_rel_info['related_table_name'] == $this->tableName()) { if ($t_item_rel->load($pn_relation_id)) { $t_item_rel->setMode(ACCESS_WRITE); $t_item_rel->delete(); if ($t_item_rel->numErrors()) { $this->errors = $t_item_rel->errors; return false; } return true; } } else { switch(sizeof($va_rel_info['path'])) { case 3: // many-to-one relationship if ($t_item_rel->load($pn_relation_id)) { $t_item_rel->setMode(ACCESS_WRITE); $t_item_rel->delete(); if ($t_item_rel->numErrors()) { $this->errors = $t_item_rel->errors; return false; } return true; } case 2: if ($this->tableName() == $va_rel_info['rel_keys']['one_table']) { if ($t_item_rel->load($pn_relation_id)) { $t_item_rel->setMode(ACCESS_WRITE); $t_item_rel->set($va_rel_info['rel_keys']['many_table_field'], null); $t_item_rel->update(); if ($t_item_rel->numErrors()) { $this->errors = $t_item_rel->errors; return false; } } } else { $this->setMode(ACCESS_WRITE); $this->set($va_rel_info['rel_keys']['many_table_field'], null); $this->update(); if ($this->numErrors()) { return false; } } break; default: return false; break; } } return false; } # -------------------------------------------------------------------------------------------- /** * Remove all relations with the specified table from the currently loaded row * * @param mixed $pm_rel_table_name_or_num Table name (eg. "ca_entities") or number as defined in datamodel.conf of table containing row to removes relationships to. * @return boolean True on success, false on error */ public function removeRelationships($pm_rel_table_name_or_num) { if (!($vn_row_id = $this->getPrimaryKey())) { return null; } if(!($va_rel_info = $this->_getRelationshipInfo($pm_rel_table_name_or_num))) { return null; } $t_item_rel = $va_rel_info['t_item_rel']; $o_db = $this->getDb(); if ($t_item_rel->tableName() == $this->getSelfRelationTableName()) { $qr_res = $o_db->query(" SELECT relation_id FROM ".$t_item_rel->tableName()." WHERE ".$t_item_rel->getLeftTableFieldName()." = ? OR ".$t_item_rel->getRightTableFieldName()." = ? ", (int)$vn_row_id, (int)$vn_row_id); while($qr_res->nextRow()) { if (!$this->removeRelationship($pm_rel_table_name_or_num, $qr_res->get('relation_id'))) { return false; } } } else { $qr_res = $o_db->query(" SELECT relation_id FROM ".$t_item_rel->tableName()." WHERE ".$this->primaryKey()." = ? ", (int)$vn_row_id); while($qr_res->nextRow()) { if (!$this->removeRelationship($pm_rel_table_name_or_num, $qr_res->get('relation_id'))) { return false; } } } return true; } # -------------------------------------------------------------------------------------------- /** * */ public function getRelationshipInstance($pm_rel_table_name_or_num) { if ($va_rel_info = $this->_getRelationshipInfo($pm_rel_table_name_or_num)) { return $va_rel_info['t_item_rel']; } return null; } # -------------------------------------------------------------------------------------------- /** * Moves relationships from currently loaded row to another row specified by $pn_row_id. The existing relationship * rows are simply re-pointed to the new row, so this is a relatively fast operation. Note that this method does not copy * relationships, it moves them. After the operation completes no relationships to the specified related table will exist for the current row. * * @param mixed $pm_rel_table_name_or_num The table name or number of the related table. Only relationships pointing to this table will be moved. * @param int $pn_to_id The primary key value of the row to move the relationships to. * @param array $pa_options Array of options. No options are currently supported. * * @return int Number of relationships moved, or null on error. Note that you should carefully test the return value for null-ness rather than false-ness, since zero is a valid return value in cases where no relationships need to be moved. */ public function moveRelationships($pm_rel_table_name_or_num, $pn_to_id, $pa_options=null) { if (!($vn_row_id = $this->getPrimaryKey())) { return null; } if(!($va_rel_info = $this->_getRelationshipInfo($pm_rel_table_name_or_num))) { return null; } $t_item_rel = $va_rel_info['t_item_rel']; // linking table $o_db = $this->getDb(); $vs_item_pk = $this->primaryKey(); if (!($t_rel_item = $this->getAppDatamodel()->getTableInstance($va_rel_info['related_table_name']))) { // related item return null; } $va_to_reindex_relations = array(); if ($t_item_rel->tableName() == $this->getSelfRelationTableName()) { $qr_res = $o_db->query(" SELECT * FROM ".$t_item_rel->tableName()." WHERE ".$t_item_rel->getLeftTableFieldName()." = ? OR ".$t_item_rel->getRightTableFieldName()." = ? ", (int)$vn_row_id, (int)$vn_row_id); if ($o_db->numErrors()) { $this->errors = $o_db->errors; return null; } while($qr_res->nextRow()) { $va_to_reindex_relations[(int)$qr_res->get('relation_id')] = $qr_res->getRow(); } if (!sizeof($va_to_reindex_relations)) { return 0; } $o_db->query(" UPDATE ".$t_item_rel->tableName()." SET ".$t_item_rel->getLeftTableFieldName()." = ? WHERE ".$t_item_rel->getLeftTableFieldName()." = ? ", (int)$pn_to_id, (int)$vn_row_id); if ($o_db->numErrors()) { $this->errors = $o_db->errors; return null; } $o_db->query(" UPDATE ".$t_item_rel->tableName()." SET ".$t_item_rel->getRightTableFieldName()." = ? WHERE ".$t_item_rel->getRightTableFieldName()." = ? ", (int)$pn_to_id, (int)$vn_row_id); if ($o_db->numErrors()) { $this->errors = $o_db->errors; return null; } } else { $qr_res = $o_db->query(" SELECT * FROM ".$t_item_rel->tableName()." WHERE {$vs_item_pk} = ? ", (int)$vn_row_id); if ($o_db->numErrors()) { $this->errors = $o_db->errors; return null; } while($qr_res->nextRow()) { $va_to_reindex_relations[(int)$qr_res->get('relation_id')] = $qr_res->getRow(); } if (!sizeof($va_to_reindex_relations)) { return 0; } $o_db->query(" UPDATE ".$t_item_rel->tableName()." SET {$vs_item_pk} = ? WHERE {$vs_item_pk} = ? ", (int)$pn_to_id, (int)$vn_row_id); if ($o_db->numErrors()) { $this->errors = $o_db->errors; return null; } } $vn_rel_table_num = $t_item_rel->tableNum(); // Reindex modified relationships if (!BaseModel::$search_indexer) { BaseModel::$search_indexer = new SearchIndexer($this->getDb()); } foreach($va_to_reindex_relations as $vn_relation_id => $va_row) { BaseModel::$search_indexer->indexRow($vn_rel_table_num, $vn_relation_id, $va_row, false, null, array($vs_item_pk => true)); } return sizeof($va_to_reindex_relations); } # -------------------------------------------------------------------------------------------- /** * Copies relationships from currently loaded row to another row specified by $pn_row_id. If you want to transfer relationships * from one row to another use moveRelationships() which is much faster than copying and then deleting relationships. * * @see moveRelationships() * * @param mixed $pm_rel_table_name_or_num The table name or number of the related table. Only relationships pointing to this table will be moved. * @param int $pn_to_id The primary key value of the row to move the relationships to. * @param array $pa_options Array of options. No options are currently supported. * * @return int Number of relationships copied, or null on error. Note that you should carefully test the return value for null-ness rather than false-ness, since zero is a valid return value in cases where no relationships were available to be copied. */ public function copyRelationships($pm_rel_table_name_or_num, $pn_to_id, $pa_options=null) { if (!($vn_row_id = $this->getPrimaryKey())) { return null; } if(!($va_rel_info = $this->_getRelationshipInfo($pm_rel_table_name_or_num))) { return null; } $t_item_rel = $va_rel_info['t_item_rel']; // linking table if ($this->inTransaction()) { $t_item_rel->setTransaction($this->getTransaction()); } $o_db = $this->getDb(); $vs_item_pk = $this->primaryKey(); if (!($t_rel_item = $this->getAppDatamodel()->getTableInstance($va_rel_info['related_table_name']))) { // related item return null; } $va_to_reindex_relations = array(); if ($t_item_rel->tableName() == $this->getSelfRelationTableName()) { $vs_left_field_name = $t_item_rel->getLeftTableFieldName(); $vs_right_field_name = $t_item_rel->getRightTableFieldName(); $qr_res = $o_db->query(" SELECT * FROM ".$t_item_rel->tableName()." WHERE {$vs_left_field_name} = ? OR {$vs_right_field_name} = ? ", (int)$vn_row_id, (int)$vn_row_id); if ($o_db->numErrors()) { $this->errors = $o_db->errors; return null; } while($qr_res->nextRow()) { $va_to_reindex_relations[(int)$qr_res->get('relation_id')] = $qr_res->getRow(); } if (!sizeof($va_to_reindex_relations)) { return 0; } $va_new_relations = array(); foreach($va_to_reindex_relations as $vn_relation_id => $va_row) { $t_item_rel->setMode(ACCESS_WRITE); unset($va_row[$vs_rel_pk]); if ($va_row[$vs_left_field_name] == $vn_row_id) { $va_row[$vs_left_field_name] = $pn_to_id; } else { $va_row[$vs_right_field_name] = $pn_to_id; } $t_item_rel->set($va_row); $t_item_rel->insert(); if ($t_item_rel->numErrors()) { $this->errors = $t_item_rel->errors; return null; } $va_new_relations[$t_item_rel->getPrimaryKey()] = $va_row; } } else { $qr_res = $o_db->query(" SELECT * FROM ".$t_item_rel->tableName()." WHERE {$vs_item_pk} = ? ", (int)$vn_row_id); if ($o_db->numErrors()) { $this->errors = $o_db->errors; return null; } while($qr_res->nextRow()) { $va_to_reindex_relations[(int)$qr_res->get('relation_id')] = $qr_res->getRow(); } if (!sizeof($va_to_reindex_relations)) { return 0; } $vs_pk = $this->primaryKey(); $vs_rel_pk = $t_item_rel->primaryKey(); $va_new_relations = array(); foreach($va_to_reindex_relations as $vn_relation_id => $va_row) { $t_item_rel->setMode(ACCESS_WRITE); unset($va_row[$vs_rel_pk]); $va_row[$vs_item_pk] = $pn_to_id; $t_item_rel->set($va_row); $t_item_rel->insert(); if ($t_item_rel->numErrors()) { $this->errors = $t_item_rel->errors; return null; } $va_new_relations[$t_item_rel->getPrimaryKey()] = $va_row; } } $vn_rel_table_num = $t_item_rel->tableNum(); // Reindex modified relationships if (!BaseModel::$search_indexer) { BaseModel::$search_indexer = new SearchIndexer($this->getDb()); } foreach($va_new_relations as $vn_relation_id => $va_row) { BaseModel::$search_indexer->indexRow($vn_rel_table_num, $vn_relation_id, $va_row, false, null, array($vs_item_pk => true)); } return sizeof($va_new_relations); } # -------------------------------------------------------------------------------------------- /** * */ private function _getRelationshipInfo($pm_rel_table_name_or_num) { if (is_numeric($pm_rel_table_name_or_num)) { $vs_related_table_name = $this->getAppDataModel()->getTableName($pm_rel_table_name_or_num); } else { $vs_related_table_name = $pm_rel_table_name_or_num; } $va_rel_keys = array(); if ($this->tableName() == $vs_related_table_name) { // self relations if ($vs_self_relation_table = $this->getSelfRelationTableName()) { $t_item_rel = $this->getAppDatamodel()->getTableInstance($vs_self_relation_table); } else { return null; } } else { $va_path = array_keys($this->getAppDatamodel()->getPath($this->tableName(), $vs_related_table_name)); switch(sizeof($va_path)) { case 3: $t_item_rel = $this->getAppDatamodel()->getTableInstance($va_path[1]); break; case 2: $t_item_rel = $this->getAppDatamodel()->getTableInstance($va_path[1]); if (!sizeof($va_rel_keys = $this->_DATAMODEL->getOneToManyRelations($this->tableName(), $va_path[1]))) { $va_rel_keys = $this->_DATAMODEL->getOneToManyRelations($va_path[1], $this->tableName()); } break; default: // bad related table return null; break; } } return array( 'related_table_name' => $vs_related_table_name, 'path' => $va_path, 'rel_keys' => $va_rel_keys, 't_item_rel' => $t_item_rel ); } # -------------------------------------------------------------------------------------------- /** * */ public function getDefaultLocaleList() { global $g_ui_locale_id; $va_locale_dedup = array(); if ($g_ui_locale_id) { $va_locale_dedup[$g_ui_locale_id] = true; } $t_locale = new ca_locales(); $va_locales = $t_locale->getLocaleList(); if (is_array($va_locale_defaults = $this->getAppConfig()->getList('locale_defaults'))) { foreach($va_locale_defaults as $vs_locale_default) { $va_locale_dedup[$va_locales[$vs_locale_default]] = true; } } foreach($va_locales as $vn_locale_id => $vs_locale_code) { $va_locale_dedup[$vn_locale_id] = true; } return array_keys($va_locale_dedup); } # -------------------------------------------------------------------------------------------- /** * Returns name of self relation table (table that links two rows in this table) or NULL if no table exists * * @return string Name of table or null if no table is defined. */ public function getSelfRelationTableName() { if (isset($this->SELF_RELATION_TABLE_NAME)) { return $this->SELF_RELATION_TABLE_NAME; } return null; } # -------------------------------------------------------------------------------------------- # User tagging # -------------------------------------------------------------------------------------------- /** * Adds a tag to currently loaded row. Returns null if no row is loaded. Otherwise returns true * if tag was successfully added, false if an error occurred in which case the errors will be available * via the model's standard error methods (getErrors() and friends. * * Most of the parameters are optional with the exception of $ps_tag - the text of the tag. Note that * tag text is monolingual; if you want to do multilingual tags then you must add multiple tags. * * The parameters are: * * @param $ps_tag [string] Text of the tag (mandatory) * @param $pn_user_id [integer] A valid ca_users.user_id indicating the user who added the tag; is null for tags from non-logged-in users (optional - default is null) * @param $pn_locale_id [integer] A valid ca_locales.locale_id indicating the language of the comment. If omitted or left null then the value in the global $g_ui_locale_id variable is used. If $g_ui_locale_id is not set and $pn_locale_id is not set then an error will occur (optional - default is to use $g_ui_locale_id) * @param $pn_access [integer] Determines public visibility of tag; if set to 0 then tag is not visible to public; if set to 1 tag is visible (optional - default is 0) * @param $pn_moderator [integer] A valid ca_users.user_id value indicating who moderated the tag; if omitted or set to null then moderation status will not be set unless app.conf setting dont_moderate_comments = 1 (optional - default is null) * @param array $pa_options Array of options. Supported options are: * purify = if true, comment, name and email are run through HTMLPurifier before being stored in the database. Default is true. */ public function addTag($ps_tag, $pn_user_id=null, $pn_locale_id=null, $pn_access=0, $pn_moderator=null, $pa_options=null) { global $g_ui_locale_id; if (!($vn_row_id = $this->getPrimaryKey())) { return null; } if (!$pn_locale_id) { $pn_locale_id = $g_ui_locale_id; } if (!$pn_locale_id) { $this->postErrors(2830, _t('No locale was set for tag'), 'BaseModel->addTag()'); return false; } if(!isset($pa_options['purify'])) { $pa_options['purify'] = true; } if ((bool)$pa_options['purify']) { $o_purifier = new HTMLPurifier(); $ps_tag = $o_purifier->purify($ps_tag); } $t_tag = new ca_item_tags(); if (!$t_tag->load(array('tag' => $ps_tag, 'locale_id' => $pn_locale_id))) { // create new new $t_tag->setMode(ACCESS_WRITE); $t_tag->set('tag', $ps_tag); $t_tag->set('locale_id', $pn_locale_id); $vn_tag_id = $t_tag->insert(); if ($t_tag->numErrors()) { $this->errors = $t_tag->errors; return false; } } else { $vn_tag_id = $t_tag->getPrimaryKey(); } $t_ixt = new ca_items_x_tags(); $t_ixt->setMode(ACCESS_WRITE); $t_ixt->set('table_num', $this->tableNum()); $t_ixt->set('row_id', $this->getPrimaryKey()); $t_ixt->set('user_id', $pn_user_id); $t_ixt->set('tag_id', $vn_tag_id); $t_ixt->set('access', $pn_access); if (!is_null($pn_moderator)) { $t_ixt->set('moderated_by_user_id', $pn_moderator); $t_ixt->set('moderated_on', 'now'); }elseif($this->_CONFIG->get("dont_moderate_comments")){ $t_ixt->set('moderated_on', 'now'); } $t_ixt->insert(); if ($t_ixt->numErrors()) { $this->errors = $t_ixt->errors; return false; } return true; } # -------------------------------------------------------------------------------------------- /** * Changed the access value for an existing tag. Returns null if no row is loaded. Otherwise returns true * if tag access setting was successfully changed, false if an error occurred in which case the errors will be available * via the model's standard error methods (getErrors() and friends. * * If $pn_user_id is set then only tag relations created by the specified user can be modified. Attempts to modify * tags created by users other than the one specified in $pn_user_id will return false and post an error. * * Most of the parameters are optional with the exception of $ps_tag - the text of the tag. Note that * tag text is monolingual; if you want to do multilingual tags then you must add multiple tags. * * The parameters are: * * @param $pn_relation_id [integer] A valid ca_items_x_tags.relation_id value specifying the tag relation to modify (mandatory) * @param $pn_access [integer] Determines public visibility of tag; if set to 0 then tag is not visible to public; if set to 1 tag is visible (optional - default is 0) * @param $pn_moderator [integer] A valid ca_users.user_id value indicating who moderated the tag; if omitted or set to null then moderation status will not be set (optional - default is null) * @param $pn_user_id [integer] A valid ca_users.user_id valid; if set only tag relations created by the specified user will be modifed (optional - default is null) */ public function changeTagAccess($pn_relation_id, $pn_access=0, $pn_moderator=null, $pn_user_id=null) { if (!($vn_row_id = $this->getPrimaryKey())) { return null; } $t_ixt = new ca_items_x_tags($pn_relation_id); if (!$t_ixt->getPrimaryKey()) { $this->postError(2800, _t('Tag relation id is invalid'), 'BaseModel->changeTagAccess()'); return false; } if ( ($t_ixt->get('table_num') != $this->tableNum()) || ($t_ixt->get('row_id') != $vn_row_id) ) { $this->postError(2810, _t('Tag is not part of the current row'), 'BaseModel->changeTagAccess()'); return false; } if ($pn_user_id) { if ($t_ixt->get('user_id') != $pn_user_id) { $this->postError(2820, _t('Tag was not created by specified user'), 'BaseModel->changeTagAccess()'); return false; } } $t_ixt->setMode(ACCESS_WRITE); $t_ixt->set('access', $pn_access); if (!is_null($pn_moderator)) { $t_ixt->set('moderated_by_user_id', $pn_moderator); $t_ixt->set('moderated_on', 'now'); } $t_ixt->update(); if ($t_ixt->numErrors()) { $this->errors = $t_ixt->errors; return false; } return true; } # -------------------------------------------------------------------------------------------- /** * Deletes the tag relation specified by $pn_relation_id (a ca_items_x_tags.relation_id value) from the currently loaded row. Will only delete * tags attached to the currently loaded row. If you attempt to delete a ca_items_x_tags.relation_id not attached to the current row * removeTag() will return false and post an error. If you attempt to call removeTag() with no row loaded null will be returned. * If $pn_user_id is specified then only tags created by the specified user will be deleted; if the tag being * deleted is not created by the user then false is returned and an error posted. * * @param $pn_relation_id [integer] a valid ca_items_x_tags.relation_id to be removed; must be related to the currently loaded row (mandatory) * @param $pn_user_id [integer] a valid ca_users.user_id value; if specified then only tag relations added by the specified user will be deleted (optional - default is null) */ public function removeTag($pn_relation_id, $pn_user_id=null) { if (!($vn_row_id = $this->getPrimaryKey())) { return null; } $t_ixt = new ca_items_x_tags($pn_relation_id); if (!$t_ixt->getPrimaryKey()) { $this->postError(2800, _t('Tag relation id is invalid'), 'BaseModel->removeTag()'); return false; } if ( ($t_ixt->get('table_num') != $this->tableNum()) || ($t_ixt->get('row_id') != $vn_row_id) ) { $this->postError(2810, _t('Tag is not part of the current row'), 'BaseModel->removeTag()'); return false; } if ($pn_user_id) { if ($t_ixt->get('user_id') != $pn_user_id) { $this->postError(2820, _t('Tag was not created by specified user'), 'BaseModel->removeTag()'); return false; } } $t_ixt->setMode(ACCESS_WRITE); $t_ixt->delete(); if ($t_ixt->numErrors()) { $this->errors = $t_ixt->errors; return false; } return true; } # -------------------------------------------------------------------------------------------- /** * Removes all tags associated with the currently loaded row. Will return null if no row is currently loaded. * If the optional $ps_user_id parameter is passed then only tags added by the specified user will be removed. * * @param $pn_user_id [integer] A valid ca_users.user_id value. If specified, only tags added by the specified user will be removed. (optional - default is null) */ public function removeAllTags($pn_user_id=null) { if (!($vn_row_id = $this->getPrimaryKey())) { return null; } $va_tags = $this->getTags($pn_user_id); foreach($va_tags as $va_tag) { if (!$this->removeTag($va_tag['tag_id'], $pn_user_id)) { return false; } } return true; } # -------------------------------------------------------------------------------------------- /** * Returns all tags associated with the currently loaded row. Will return null if not row is currently loaded. * If the optional $ps_user_id parameter is passed then only tags created by the specified user will be returned. * If the optional $pb_moderation_status parameter is passed then only tags matching the criteria will be returned: * Passing $pb_moderation_status = TRUE will cause only moderated tags to be returned * Passing $pb_moderation_status = FALSE will cause only unmoderated tags to be returned * If you want both moderated and unmoderated tags to be returned then omit the parameter or pass a null value * * @param $pn_user_id [integer] A valid ca_users.user_id value. If specified, only tags added by the specified user will be returned. (optional - default is null) * @param $pn_moderation_status [boolean] To return only unmoderated tags set to FALSE; to return only moderated tags set to TRUE; to return all tags set to null or omit */ public function getTags($pn_user_id=null, $pb_moderation_status=null, $pn_row_id=null) { if (!($vn_row_id = $pn_row_id)) { if (!($vn_row_id = $this->getPrimaryKey())) { return null; } } $o_db = $this->getDb(); $vs_user_sql = ($pn_user_id) ? ' AND (cixt.user_id = '.intval($pn_user_id).')' : ''; $vs_moderation_sql = ''; if (!is_null($pb_moderation_status)) { $vs_moderation_sql = ($pb_moderation_status) ? ' AND (cixt.moderated_on IS NOT NULL)' : ' AND (cixt.moderated_on IS NULL)'; } $qr_comments = $o_db->query(" SELECT * FROM ca_item_tags cit INNER JOIN ca_items_x_tags AS cixt ON cit.tag_id = cixt.tag_id WHERE (cixt.table_num = ?) AND (cixt.row_id = ?) {$vs_user_sql} {$vs_moderation_sql} ", $this->tableNum(), $vn_row_id); return $qr_comments->getAllRows(); } # -------------------------------------------------------------------------------------------- # User commenting # -------------------------------------------------------------------------------------------- /** * Adds a comment to currently loaded row. Returns null if no row is loaded. Otherwise returns true * if comment was successfully added, false if an error occurred in which case the errors will be available * via the model's standard error methods (getErrors() and friends. * * Most of the parameters are optional with the exception of $ps_comment - the text of the comment. Note that * comment text is monolingual; if you want to do multilingual comments (which aren't really comments then, are they?) then * you should add multiple comments. * * @param $ps_comment [string] Text of the comment (mandatory) * @param $pn_rating [integer] A number between 1 and 5 indicating the user's rating of the row; larger is better (optional - default is null) * @param $pn_user_id [integer] A valid ca_users.user_id indicating the user who posted the comment; is null for comments from non-logged-in users (optional - default is null) * @param $pn_locale_id [integer] A valid ca_locales.locale_id indicating the language of the comment. If omitted or left null then the value in the global $g_ui_locale_id variable is used. If $g_ui_locale_id is not set and $pn_locale_id is not set then an error will occur (optional - default is to use $g_ui_locale_id) * @param $ps_name [string] Name of user posting comment. Only needs to be set if $pn_user_id is *not* set; used to identify comments posted by non-logged-in users (optional - default is null) * @param $ps_email [string] E-mail address of user posting comment. Only needs to be set if $pn_user_id is *not* set; used to identify comments posted by non-logged-in users (optional - default is null) * @param $pn_access [integer] Determines public visibility of comments; if set to 0 then comment is not visible to public; if set to 1 comment is visible (optional - default is 0) * @param $pn_moderator [integer] A valid ca_users.user_id value indicating who moderated the comment; if omitted or set to null then moderation status will not be set unless app.conf setting dont_moderate_comments = 1 (optional - default is null) * @param array $pa_options Array of options. Supported options are: * purify = if true, comment, name and email are run through HTMLPurifier before being stored in the database. Default is true. * media1_original_filename = original file name to set for comment "media1" * media2_original_filename = original file name to set for comment "media2" * media3_original_filename = original file name to set for comment "media3" * media4_original_filename = original file name to set for comment "media4" */ public function addComment($ps_comment, $pn_rating=null, $pn_user_id=null, $pn_locale_id=null, $ps_name=null, $ps_email=null, $pn_access=0, $pn_moderator=null, $pa_options=null, $ps_media1=null, $ps_media2=null, $ps_media3=null, $ps_media4=null) { global $g_ui_locale_id; if (!($vn_row_id = $this->getPrimaryKey())) { return null; } if (!$pn_locale_id) { $pn_locale_id = $g_ui_locale_id; } if(!isset($pa_options['purify'])) { $pa_options['purify'] = true; } if ((bool)$pa_options['purify']) { $o_purifier = new HTMLPurifier(); $ps_comment = $o_purifier->purify($ps_comment); $ps_name = $o_purifier->purify($ps_name); $ps_email = $o_purifier->purify($ps_email); } $t_comment = new ca_item_comments(); $t_comment->setMode(ACCESS_WRITE); $t_comment->set('table_num', $this->tableNum()); $t_comment->set('row_id', $vn_row_id); $t_comment->set('user_id', $pn_user_id); $t_comment->set('locale_id', $pn_locale_id); $t_comment->set('comment', $ps_comment); $t_comment->set('rating', $pn_rating); $t_comment->set('email', $ps_email); $t_comment->set('name', $ps_name); $t_comment->set('access', $pn_access); $t_comment->set('media1', $ps_media1, array('original_filename' => $pa_options['media1_original_filename'])); $t_comment->set('media2', $ps_media2, array('original_filename' => $pa_options['media2_original_filename'])); $t_comment->set('media3', $ps_media3, array('original_filename' => $pa_options['media3_original_filename'])); $t_comment->set('media4', $ps_media4, array('original_filename' => $pa_options['media4_original_filename'])); if (!is_null($pn_moderator)) { $t_comment->set('moderated_by_user_id', $pn_moderator); $t_comment->set('moderated_on', 'now'); }elseif($this->_CONFIG->get("dont_moderate_comments")){ $t_comment->set('moderated_on', 'now'); } $t_comment->insert(); if ($t_comment->numErrors()) { $this->errors = $t_comment->errors; return false; } return true; } # -------------------------------------------------------------------------------------------- /** * Edits an existing comment as specified by $pn_comment_id. Will only edit comments that are attached to the * currently loaded row. If called with no row loaded editComment() will return null. If you attempt to modify * a comment not associated with the currently loaded row editComment() will return false and post an error. * Note that all parameters are mandatory in the sense that the value passed (or the default value if not passed) * will be written into the comment. For example, if you don't bother passing $ps_name then it will be set to null, even * if there's an existing name value in the field. The only exception is $pn_locale_id; if set to null or omitted then * editComment() will attempt to use the locale value in the global $g_ui_locale_id variable. If this is not set then * an error will be posted and editComment() will return false. * * @param $pn_comment_id [integer] a valid comment_id to be edited; must be related to the currently loaded row (mandatory) * @param $ps_comment [string] the text of the comment (mandatory) * @param $pn_rating [integer] a number between 1 and 5 indicating the user's rating of the row; higher is better (optional - default is null) * @param $pn_user_id [integer] A valid ca_users.user_id indicating the user who posted the comment; is null for comments from non-logged-in users (optional - default is null) * @param $pn_locale_id [integer] A valid ca_locales.locale_id indicating the language of the comment. If omitted or left null then the value in the global $g_ui_locale_id variable is used. If $g_ui_locale_id is not set and $pn_locale_id is not set then an error will occur (optional - default is to use $g_ui_locale_id) * @param $ps_name [string] Name of user posting comment. Only needs to be set if $pn_user_id is *not* set; used to identify comments posted by non-logged-in users (optional - default is null) * @param $ps_email [string] E-mail address of user posting comment. Only needs to be set if $pn_user_id is *not* set; used to identify comments posted by non-logged-in users (optional - default is null) * @param $pn_access [integer] Determines public visibility of comments; if set to 0 then comment is not visible to public; if set to 1 comment is visible (optional - default is 0) * @param $pn_moderator [integer] A valid ca_users.user_id value indicating who moderated the comment; if omitted or set to null then moderation status will not be set (optional - default is null) * @param array $pa_options Array of options. Supported options are: * purify = if true, comment, name and email are run through HTMLPurifier before being stored in the database. Default is true. * media1_original_filename = original file name to set for comment "media1" * media2_original_filename = original file name to set for comment "media2" * media3_original_filename = original file name to set for comment "media3" * media4_original_filename = original file name to set for comment "media4" */ public function editComment($pn_comment_id, $ps_comment, $pn_rating=null, $pn_user_id=null, $pn_locale_id=null, $ps_name=null, $ps_email=null, $pn_access=null, $pn_moderator=null, $pa_options=null, $ps_media1=null, $ps_media2=null, $ps_media3=null, $ps_media4=null) { global $g_ui_locale_id; if (!($vn_row_id = $this->getPrimaryKey())) { return null; } if (!$pn_locale_id) { $pn_locale_id = $g_ui_locale_id; } $t_comment = new ca_item_comments($pn_comment_id); if (!$t_comment->getPrimaryKey()) { $this->postError(2800, _t('Comment id is invalid'), 'BaseModel->editComment()'); return false; } if ( ($t_comment->get('table_num') != $this->tableNum()) || ($t_comment->get('row_id') != $vn_row_id) ) { $this->postError(2810, _t('Comment is not part of the current row'), 'BaseModel->editComment()'); return false; } if(!isset($pa_options['purify'])) { $pa_options['purify'] = true; } if ((bool)$pa_options['purify']) { $o_purifier = new HTMLPurifier(); $ps_comment = $o_purifier->purify($ps_comment); $ps_name = $o_purifier->purify($ps_name); $ps_email = $o_purifier->purify($ps_email); } $t_comment->setMode(ACCESS_WRITE); $t_comment->set('comment', $ps_comment); $t_comment->set('rating', $pn_rating); $t_comment->set('user_id', $pn_user_id); $t_comment->set('name', $ps_name); $t_comment->set('email', $ps_email); $t_comment->set('media1', $ps_media1, array('original_filename' => $pa_options['media1_original_filename'])); $t_comment->set('media2', $ps_media2, array('original_filename' => $pa_options['media2_original_filename'])); $t_comment->set('media3', $ps_media3, array('original_filename' => $pa_options['media3_original_filename'])); $t_comment->set('media4', $ps_media4, array('original_filename' => $pa_options['media4_original_filename'])); if (!is_null($pn_moderator)) { $t_comment->set('moderated_by_user_id', $pn_moderator); $t_comment->set('moderated_on', 'now'); } if (!is_null($pn_locale_id)) { $t_comment->set('locale_id', $pn_locale_id); } $t_comment->update(); if ($t_comment->numErrors()) { $this->errors = $t_comment->errors; return false; } return true; } # -------------------------------------------------------------------------------------------- /** * Permanently deletes the comment specified by $pn_comment_id. Will only delete comments attached to the * currently loaded row. If you attempt to delete a comment_id not attached to the current row removeComment() * will return false and post an error. If you attempt to call removeComment() with no row loaded null will be returned. * If $pn_user_id is specified then only comments created by the specified user will be deleted; if the comment being * deleted is not created by the user then false is returned and an error posted. * * @param $pn_comment_id [integer] a valid comment_id to be removed; must be related to the currently loaded row (mandatory) * @param $pn_user_id [integer] a valid ca_users.user_id value; if specified then only comments by the specified user will be deleted (optional - default is null) */ public function removeComment($pn_comment_id, $pn_user_id=null) { if (!($vn_row_id = $this->getPrimaryKey())) { return null; } $t_comment = new ca_item_comments($pn_comment_id); if (!$t_comment->getPrimaryKey()) { $this->postError(2800, _t('Comment id is invalid'), 'BaseModel->removeComment()'); return false; } if ( ($t_comment->get('table_num') != $this->tableNum()) || ($t_comment->get('row_id') != $vn_row_id) ) { $this->postError(2810, _t('Comment is not part of the current row'), 'BaseModel->removeComment()'); return false; } if ($pn_user_id) { if ($t_comment->get('user_id') != $pn_user_id) { $this->postError(2820, _t('Comment was not created by specified user'), 'BaseModel->removeComment()'); return false; } } $t_comment->setMode(ACCESS_WRITE); $t_comment->delete(); if ($t_comment->numErrors()) { $this->errors = $t_comment->errors; return false; } return true; } # -------------------------------------------------------------------------------------------- /** * Removes all comments associated with the currently loaded row. Will return null if no row is currently loaded. * If the optional $ps_user_id parameter is passed then only comments created by the specified user will be removed. * * @param $pn_user_id [integer] A valid ca_users.user_id value. If specified, only comments by the specified user will be removed. (optional - default is null) */ public function removeAllComments($pn_user_id=null) { if (!($vn_row_id = $this->getPrimaryKey())) { return null; } $va_comments = $this->getComments($pn_user_id); foreach($va_comments as $va_comment) { if (!$this->removeComment($va_comment['comment_id'], $pn_user_id)) { return false; } } return true; } # -------------------------------------------------------------------------------------------- /** * Returns all comments associated with the currently loaded row. Will return null if not row is currently loaded. * If the optional $ps_user_id parameter is passed then only comments created by the specified user will be returned. * If the optional $pb_moderation_status parameter is passed then only comments matching the criteria will be returned: * Passing $pb_moderation_status = TRUE will cause only moderated comments to be returned * Passing $pb_moderation_status = FALSE will cause only unmoderated comments to be returned * If you want both moderated and unmoderated comments to be returned then omit the parameter or pass a null value * * @param $pn_user_id [integer] A valid ca_users.user_id value. If specified, only comments by the specified user will be returned. (optional - default is null) * @param $pn_moderation_status [boolean] To return only unmoderated comments set to FALSE; to return only moderated comments set to TRUE; to return all comments set to null or omit */ public function getComments($pn_user_id=null, $pb_moderation_status=null) { if (!($vn_row_id = $this->getPrimaryKey())) { return null; } $o_db = $this->getDb(); $vs_user_sql = ($pn_user_id) ? ' AND (user_id = '.intval($pn_user_id).')' : ''; $vs_moderation_sql = ''; if (!is_null($pb_moderation_status)) { $vs_moderation_sql = ($pb_moderation_status) ? ' AND (ca_item_comments.moderated_on IS NOT NULL)' : ' AND (ca_item_comments.moderated_on IS NULL)'; } $qr_comments = $o_db->query(" SELECT * FROM ca_item_comments WHERE (table_num = ?) AND (row_id = ?) {$vs_user_sql} {$vs_moderation_sql} ", $this->tableNum(), $vn_row_id); $va_comments = array(); while($qr_comments->nextRow()){ $va_comments[$qr_comments->get("comment_id")] = $qr_comments->getRow(); foreach(array("media1", "media2", "media3", "media4") as $vs_media_field){ $va_media_versions = array(); $va_media_versions = $qr_comments->getMediaVersions($vs_media_field); $va_media = array(); if(is_array($va_media_versions) && (sizeof($va_media_versions) > 0)){ foreach($va_media_versions as $vs_version){ $va_image_info = array(); $va_image_info = $qr_comments->getMediaInfo($vs_media_field, $vs_version); $va_image_info["TAG"] = $qr_comments->getMediaTag($vs_media_field, $vs_version); $va_image_info["URL"] = $qr_comments->getMediaUrl($vs_media_field, $vs_version); $va_media[$vs_version] = $va_image_info; } $va_comments[$qr_comments->get("comment_id")][$vs_media_field] = $va_media; } } } return $va_comments; } # -------------------------------------------------------------------------------------------- /** * Returns average user rating of item */ public function getAverageRating($pb_moderation_status=true) { if (!($vn_row_id = $this->getPrimaryKey())) { return null; } $vs_moderation_sql = ''; if (!is_null($pb_moderation_status)) { $vs_moderation_sql = ($pb_moderation_status) ? ' AND (ca_item_comments.moderated_on IS NOT NULL)' : ' AND (ca_item_comments.moderated_on IS NULL)'; } $o_db = $this->getDb(); $qr_comments = $o_db->query(" SELECT avg(rating) r FROM ca_item_comments WHERE (table_num = ?) AND (row_id = ?) {$vs_moderation_sql} ", $this->tableNum(), $vn_row_id); if ($qr_comments->nextRow()) { return round($qr_comments->get('r')); } else { return null; } } # -------------------------------------------------------------------------------------------- /** * Returns number of user ratings for item */ public function getNumRatings($pb_moderation_status=true) { if (!($vn_row_id = $this->getPrimaryKey())) { return null; } $vs_moderation_sql = ''; if (!is_null($pb_moderation_status)) { $vs_moderation_sql = ($pb_moderation_status) ? ' AND (ca_item_comments.moderated_on IS NOT NULL)' : ' AND (ca_item_comments.moderated_on IS NULL)'; } $o_db = $this->getDb(); $qr_ratings = $o_db->query(" SELECT count(*) c FROM ca_item_comments WHERE (rating > 0) AND (table_num = ?) AND (row_id = ?) {$vs_moderation_sql} ", $this->tableNum(), $vn_row_id); if ($qr_ratings->nextRow()) { return round($qr_ratings->get('c')); } else { return null; } } # -------------------------------------------------------------------------------------------- /** * Return the highest rated item(s) * Return an array of primary key values */ public function getHighestRated($pb_moderation_status=true, $pn_num_to_return=1, $va_access_values = array()) { $vs_moderation_sql = ''; if (!is_null($pb_moderation_status)) { $vs_moderation_sql = ($pb_moderation_status) ? ' AND (ca_item_comments.moderated_on IS NOT NULL)' : ' AND (ca_item_comments.moderated_on IS NULL)'; } $vs_access_join = ""; $vs_access_where = ""; $vs_table_name = $this->tableName(); $vs_primary_key = $this->primaryKey(); if (isset($va_access_values) && is_array($va_access_values) && sizeof($va_access_values) && $this->hasField('access')) { if ($vs_table_name && $vs_primary_key) { $vs_access_join = 'INNER JOIN '.$vs_table_name.' as rel ON rel.'.$vs_primary_key." = ca_item_comments.row_id "; $vs_access_where = ' AND rel.access IN ('.join(',', $va_access_values).')'; } } $vs_deleted_sql = ''; if ($this->hasField('deleted')) { $vs_deleted_sql = " AND (rel.deleted = 0) "; } if ($vs_deleted_sql || $vs_access_where) { $vs_access_join = 'INNER JOIN '.$vs_table_name.' as rel ON rel.'.$vs_primary_key." = ca_item_comments.row_id "; } $o_db = $this->getDb(); $qr_comments = $o_db->query($x=" SELECT ca_item_comments.row_id FROM ca_item_comments {$vs_access_join} WHERE (ca_item_comments.table_num = ?) {$vs_moderation_sql} {$vs_access_where} {$vs_deleted_sql} GROUP BY ca_item_comments.row_id ORDER BY avg(ca_item_comments.rating) DESC, MAX(ca_item_comments.created_on) DESC LIMIT {$pn_num_to_return} ", $this->tableNum()); $va_row_ids = array(); while ($qr_comments->nextRow()) { $va_row_ids[] = $qr_comments->get('row_id'); } return $va_row_ids; } # -------------------------------------------------------------------------------------------- /** * Return the number of ratings * Return an integer count */ public function getRatingsCount($pb_moderation_status=true) { if (!($vn_row_id = $this->getPrimaryKey())) { return null; } $vs_moderation_sql = ''; if (!is_null($pb_moderation_status)) { $vs_moderation_sql = ($pb_moderation_status) ? ' AND (ca_item_comments.moderated_on IS NOT NULL)' : ' AND (ca_item_comments.moderated_on IS NULL)'; } $o_db = $this->getDb(); $qr_comments = $o_db->query(" SELECT count(*) c FROM ca_item_comments WHERE (ca_item_comments.table_num = ?) AND (ca_item_comments.row_id = ?) {$vs_moderation_sql} ", $this->tableNum(), $vn_row_id); if ($qr_comments->nextRow()) { return $qr_comments->get('c'); } return 0; } # -------------------------------------------------------------------------------------------- /** * Increments the view count for this item * * @param int $pn_user_id User_id of user viewing item. Omit of set null if user is not logged in. * * @return bool True on success, false on error. */ public function registerItemView($pn_user_id=null) { global $g_ui_locale_id; if (!($vn_row_id = $this->getPrimaryKey())) { return null; } if (!$pn_locale_id) { $pn_locale_id = $g_ui_locale_id; } $vn_table_num = $this->tableNum(); $t_view = new ca_item_views(); $t_view->setMode(ACCESS_WRITE); $t_view->set('table_num', $vn_table_num); $t_view->set('row_id', $vn_row_id); $t_view->set('user_id', $pn_user_id); $t_view->set('locale_id', $pn_locale_id); $t_view->insert(); if ($t_view->numErrors()) { $this->errors = $t_view->errors; return false; } $o_db = $this->getDb(); // increment count $qr_res = $o_db->query(" SELECT * FROM ca_item_view_counts WHERE table_num = ? AND row_id = ? ", $vn_table_num, $vn_row_id); if ($qr_res->nextRow()) { $o_db->query(" UPDATE ca_item_view_counts SET view_count = view_count + 1 WHERE table_num = ? AND row_id = ? ", $vn_table_num, $vn_row_id); } else { $o_db->query(" INSERT INTO ca_item_view_counts (table_num, row_id, view_count) VALUES (?, ?, 1) ", $vn_table_num, $vn_row_id); } $o_cache = caGetCacheObject("caRecentlyViewedCache"); if (!is_array($va_recently_viewed_list = $o_cache->load('recentlyViewed'))) { $va_recently_viewed_list = array(); } if (!is_array($va_recently_viewed_list[$vn_table_num])) { $va_recently_viewed_list[$vn_table_num] = array(); } while(sizeof($va_recently_viewed_list[$vn_table_num]) > 100) { array_pop($va_recently_viewed_list[$vn_table_num]); } if (!in_array($vn_row_id, $va_recently_viewed_list[$vn_table_num])) { array_unshift($va_recently_viewed_list[$vn_table_num], $vn_row_id); } $o_cache->save($va_recently_viewed_list, 'recentlyViewed'); return true; } # -------------------------------------------------------------------------------------------- /** * Clears view count for the currently loaded row * * @param int $pn_user_id If set, only views from the specified user are cleared * @return bool True on success, false on error */ public function clearItemViewCount($pn_user_id=null) { if (!($vn_row_id = $this->getPrimaryKey())) { return null; } $o_db = $this->getDb(); $vs_user_sql = ''; if ($pn_user_id) { $vs_user_sql = " AND user_id = ".intval($pn_user_id); } $qr_res = $o_db->query(" DELETE FROM ca_item_views WHERE table_num = ? AND row_id = ? {$vs_user_sql} ", $this->tableNum(), $vn_row_id); $qr_res = $o_db->query(" UPDATE ca_item_view_counts SET view_count = 0 WHERE table_num = ? AND row_id = ? {$vs_user_sql} ", $this->tableNum(), $vn_row_id); return $o_db->numErrors() ? false : true; } # -------------------------------------------------------------------------------------------- /** * Get view list for currently loaded row. * * @param int $pn_user_id If set, only views from the specified user are returned * @param array $pa_options Supported options are: * restrictToTypes = array of type names or type_ids to restrict to * hasRepresentations = if set when model is for ca_objects views are only returned when the object has at least one representation * checkAccess = an array of access values to filter only. Views will only be returned if the item's access setting is in the array. * @return bool True on success, false on error */ public function getViewList($pn_user_id=null, $pa_options=null) { if (!($vn_row_id = $this->getPrimaryKey())) { return null; } $o_db = $this->getDb(); $vs_limit_sql = ''; if ($pn_limit > 0) { $vs_limit_sql = "LIMIT ".intval($pn_limit); } $va_wheres = array('(civc.table_num = ?)'); if (is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && ($this->hasField('access'))) { $va_wheres[] = 't.access IN ('.join(',', $pa_options['checkAccess']).')'; } if (method_exists($this, 'getTypeFieldName') && ($vs_type_field_name = $this->getTypeFieldName())) { $va_types = caMergeTypeRestrictionLists($this, $pa_options); if (is_array($va_types) && sizeof($va_types)) { $va_wheres[] = 't.'.$vs_type_field_name.' IN ('.join(',', $va_types).')'; } } $vs_join_sql = ''; if (isset($pa_options['hasRepresentations']) && $pa_options['hasRepresentations'] && ($this->tableName() == 'ca_objects')) { $vs_join_sql = ' INNER JOIN ca_objects_x_object_representations ON ca_objects_x_object_representations.object_id = t.object_id'; $va_wheres[] = 'ca_objects_x_object_representations.is_primary = 1'; } if ($pn_user_id) { $va_wheres[] = "civ.user_id = ".intval($pn_user_id); } if ($vs_where_sql = join(' AND ', $va_wheres)) { $vs_where_sql = ' WHERE '.$vs_where_sql; } $qr_res = $o_db->query(" SELECT t.*, count(*) cnt FROM ".$this->tableName()." t INNER JOIN ca_item_views AS civ ON civ.row_id = t.".$this->primaryKey()." WHERE civ.table_num = ? AND row_id = ? {$vs_user_sql} {$vs_access_sql} GROUP BY civ.row_id ORDER BY cnt DESC {$vs_limit_sql} ", $this->tableNum(), $vn_row_id); $va_items = array(); while($qr_res->nextRow()) { $va_items[] = $qr_res->getRow(); } return $va_items; } # -------------------------------------------------------------------------------------------- /** * Returns a list of the items with the most views. * * @param int $pn_limit Limit list to the specified number of items. Defaults to 10 if not specified. * @param array $pa_options Supported options are: * restrictToTypes = array of type names or type_ids to restrict to. Only items with a type_id in the list will be returned. * hasRepresentations = if set when model is for ca_objects views are only returned when the object has at least one representation. * checkAccess = an array of access values to filter only. Items will only be returned if the item's access setting is in the array. * @return bool True on success, false on error */ public function getMostViewedItems($pn_limit=10, $pa_options=null) { $o_db = $this->getDb(); $vs_limit_sql = ''; if ($pn_limit > 0) { $vs_limit_sql = "LIMIT ".intval($pn_limit); } $va_wheres = array('(civc.table_num = '.intval($this->tableNum()).')'); if (is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && ($this->hasField('access'))) { $va_wheres[] = 't.access IN ('.join(',', $pa_options['checkAccess']).')'; } if (method_exists($this, 'getTypeFieldName') && ($vs_type_field_name = $this->getTypeFieldName())) { $va_types = caMergeTypeRestrictionLists($this, $pa_options); if (is_array($va_types) && sizeof($va_types)) { $va_wheres[] = 't.'.$vs_type_field_name.' IN ('.join(',', $va_types).')'; } } $vs_join_sql = ''; if (isset($pa_options['hasRepresentations']) && $pa_options['hasRepresentations'] && ($this->tableName() == 'ca_objects')) { $vs_join_sql = ' INNER JOIN ca_objects_x_object_representations ON ca_objects_x_object_representations.object_id = t.object_id'; $va_wheres[] = 'ca_objects_x_object_representations.is_primary = 1'; } if ($this->hasField('deleted')) { $va_wheres[] = "(t.deleted = 0)"; } if ($vs_where_sql = join(' AND ', $va_wheres)) { $vs_where_sql = ' WHERE '.$vs_where_sql; } $qr_res = $o_db->query(" SELECT t.*, civc.view_count cnt FROM ".$this->tableName()." t INNER JOIN ca_item_view_counts AS civc ON civc.row_id = t.".$this->primaryKey()." {$vs_join_sql} {$vs_where_sql} ORDER BY civc.view_count DESC {$vs_limit_sql} "); $va_most_viewed_items = array(); while($qr_res->nextRow()) { $va_most_viewed_items[$qr_res->get($this->primaryKey())] = $qr_res->getRow(); } return $va_most_viewed_items; } # -------------------------------------------------------------------------------------------- /** * Returns the most recently viewed items, up to a maximum of $pn_limit (default is 10) * Note that the limit is just that – a limit. getRecentlyViewedItems() may return fewer * than the limit either because there fewer viewed items than your limit or because fetching * additional views would take too long. (To ensure adequate performance getRecentlyViewedItems() uses a cache of * recent views. If there is no cache available it will query the database to look at the most recent (4 x your limit) viewings. * If there are many views of the same item in that group then it is possible that fewer items than your limit will be returned) * * @param int $pn_limit The maximum number of items to return. Default is 10. * @param array $pa_options Supported options are: * restrictToTypes = array of type names or type_ids to restrict to. Only items with a type_id in the list will be returned. * checkAccess = array of access values to filter results by; if defined only items with the specified access code(s) are returned * hasRepresentations = if set to a non-zero (boolean true) value only items with representations will be returned * dontUseCache = if set to true, forces list to be generated from database; default is false. * @return array List of primary key values for recently viewed items. */ public function getRecentlyViewedItems($pn_limit=10, $pa_options=null) { if (!isset($pa_options['dontUseCache']) || !$pa_options['dontUseCache']) { $o_cache = caGetCacheObject("caRecentlyViewedCache"); $va_recently_viewed_items = $o_cache->load('recentlyViewed'); $vn_table_num = $this->tableNum(); if(is_array($va_recently_viewed_items) && is_array($va_recently_viewed_items[$vn_table_num])) { if(sizeof($va_recently_viewed_items[$vn_table_num]) > $pn_limit) { $va_recently_viewed_items[$vn_table_num] = array_slice($va_recently_viewed_items[$vn_table_num], 0, $pn_limit); } return $va_recently_viewed_items[$vn_table_num]; } } $o_db = $this->getDb(); $vs_limit_sql = ''; if ($pn_limit > 0) { $vs_limit_sql = "LIMIT ".(intval($pn_limit) * 4); } $va_wheres = array('(civ.table_num = '.intval($this->tableNum()).')'); if (is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && ($this->hasField('access'))) { $va_wheres[] = 't.access IN ('.join(',', $pa_options['checkAccess']).')'; } if (method_exists($this, 'getTypeFieldName') && ($vs_type_field_name = $this->getTypeFieldName())) { $va_types = caMergeTypeRestrictionLists($this, $pa_options); if (is_array($va_types) && sizeof($va_types)) { $va_wheres[] = 't.'.$vs_type_field_name.' IN ('.join(',', $va_types).')'; } } $vs_join_sql = ''; if (isset($pa_options['hasRepresentations']) && $pa_options['hasRepresentations'] && ($this->tableName() == 'ca_objects')) { $vs_join_sql = ' INNER JOIN ca_objects_x_object_representations ON ca_objects_x_object_representations.object_id = t.object_id'; $va_wheres[] = 'ca_objects_x_object_representations.is_primary = 1'; } if ($this->hasField('deleted')) { $va_wheres[] = "(t.deleted = 0)"; } if ($vs_where_sql = join(' AND ', $va_wheres)) { $vs_where_sql = ' WHERE '.$vs_where_sql; } $qr_res = $o_db->query($vs_sql = " SELECT t.".$this->primaryKey()." FROM ".$this->tableName()." t INNER JOIN ca_item_views AS civ ON civ.row_id = t.".$this->primaryKey()." {$vs_join_sql} {$vs_where_sql} ORDER BY civ.view_id DESC {$vs_limit_sql} "); $va_recently_viewed_items = array(); $vn_c = 0; while($qr_res->nextRow() && ($vn_c < $pn_limit)) { if (!isset($va_recently_viewed_items[$vn_id = $qr_res->get($this->primaryKey())])) { $va_recently_viewed_items[$vn_id] = true; $vn_c++; } } return array_keys($va_recently_viewed_items); } # -------------------------------------------------------------------------------------------- /** * Returns a list of items recently added to the database. * * @param int $pn_limit Limit list to the specified number of items. Defaults to 10 if not specified. * @param array $pa_options Supported options are: * restrictToTypes = array of type names or type_ids to restrict to. Only items with a type_id in the list will be returned. * hasRepresentations = if set when model is for ca_objects views are only returned when the object has at least one representation. * checkAccess = an array of access values to filter only. Items will only be returned if the item's access setting is in the array. * @return bool True on success, false on error */ public function getRecentlyAddedItems($pn_limit=10, $pa_options=null) { $o_db = $this->getDb(); $vs_limit_sql = ''; if ($pn_limit > 0) { $vs_limit_sql = "LIMIT ".intval($pn_limit); } $va_wheres = array(); if (is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && ($this->hasField('access'))) { $va_wheres[] = 't.access IN ('.join(',', $pa_options['checkAccess']).')'; } if (method_exists($this, 'getTypeFieldName') && ($vs_type_field_name = $this->getTypeFieldName())) { $va_types = caMergeTypeRestrictionLists($this, $pa_options); if (is_array($va_types) && sizeof($va_types)) { $va_wheres[] = 't.'.$vs_type_field_name.' IN ('.join(',', $va_types).')'; } } $vs_join_sql = ''; if (isset($pa_options['hasRepresentations']) && $pa_options['hasRepresentations'] && ($this->tableName() == 'ca_objects')) { $vs_join_sql = ' INNER JOIN ca_objects_x_object_representations ON ca_objects_x_object_representations.object_id = t.object_id'; $va_wheres[] = 'ca_objects_x_object_representations.is_primary = 1'; if (is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess'])) { $vs_join_sql .= ' INNER JOIN ca_object_representations ON ca_object_representations.representation_id = ca_objects_x_object_representations.representation_id'; $va_wheres[] = 'ca_object_representations.access IN ('.join(',', $pa_options['checkAccess']).')'; } } $vs_deleted_sql = ''; if ($this->hasField('deleted')) { $va_wheres[] = "(t.deleted = 0)"; } if ($vs_where_sql = join(' AND ', $va_wheres)) { $vs_where_sql = " WHERE {$vs_where_sql}"; } $vs_primary_key = $this->primaryKey(); $qr_res = $o_db->query(" SELECT t.* FROM ".$this->tableName()." t {$vs_join_sql} {$vs_where_sql} ORDER BY t.".$vs_primary_key." DESC {$vs_limit_sql} "); $va_recently_added_items = array(); while($qr_res->nextRow()) { $va_recently_added_items[$qr_res->get($this->primaryKey())] = $qr_res->getRow(); } return $va_recently_added_items; } # -------------------------------------------------------------------------------------------- /** * Return set of random rows (up to $pn_limit) subject to access restriction in $pn_access * Set $pn_access to null or omit to return items regardless of access control status * * @param int $pn_limit Limit list to the specified number of items. Defaults to 10 if not specified. * @param array $pa_options Supported options are: * restrictToTypes = array of type names or type_ids to restrict to. Only items with a type_id in the list will be returned. * hasRepresentations = if set when model is for ca_objects views are only returned when the object has at least one representation. * checkAccess = an array of access values to filter only. Items will only be returned if the item's access setting is in the array. * @return bool True on success, false on error */ public function getRandomItems($pn_limit=10, $pa_options=null) { $o_db = $this->getDb(); $vs_limit_sql = ''; if ($pn_limit > 0) { $vs_limit_sql = "LIMIT ".intval($pn_limit); } $vs_primary_key = $this->primaryKey(); $vs_table_name = $this->tableName(); $va_wheres = array(); if (is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && ($this->hasField('access'))) { $va_wheres[] = $vs_table_name.'.access IN ('.join(',', $pa_options['checkAccess']).')'; } if (method_exists($this, 'getTypeFieldName') && ($vs_type_field_name = $this->getTypeFieldName())) { $va_types = caMergeTypeRestrictionLists($this, $pa_options); if (is_array($va_types) && sizeof($va_types)) { $va_wheres[] = $vs_table_name.'.'.$vs_type_field_name.' IN ('.join(',', $va_types).')'; } } $vs_join_sql = ''; if (isset($pa_options['hasRepresentations']) && $pa_options['hasRepresentations'] && ($this->tableName() == 'ca_objects')) { $vs_join_sql = ' INNER JOIN ca_objects_x_object_representations ON ca_objects_x_object_representations.object_id = '.$vs_table_name.'.object_id'; } if ($this->hasField('deleted')) { $va_wheres[] = "{$vs_table_name}.deleted = 0"; } $vs_sql = " SELECT {$vs_table_name}.* FROM ( SELECT {$vs_table_name}.{$vs_primary_key} FROM {$vs_table_name} {$vs_join_sql} ".(sizeof($va_wheres) ? " WHERE " : "").join(" AND ", $va_wheres)." ORDER BY RAND() {$vs_limit_sql} ) AS random_items INNER JOIN {$vs_table_name} ON {$vs_table_name}.{$vs_primary_key} = random_items.{$vs_primary_key} {$vs_deleted_sql} "; $qr_res = $o_db->query($vs_sql); $va_random_items = array(); while($qr_res->nextRow()) { $va_random_items[$qr_res->get($this->primaryKey())] = $qr_res->getRow(); } return $va_random_items; } # -------------------------------------------------------------------------------------------- # Change log display # -------------------------------------------------------------------------------------------- /** * Returns change log for currently loaded row in displayable HTML format */ public function getChangeLogForDisplay($ps_css_id=null) { $o_log = new ApplicationChangeLog(); return $o_log->getChangeLogForRowForDisplay($this, $ps_css_id); } # -------------------------------------------------------------------------------------------- # # -------------------------------------------------------------------------------------------- /** * */ static public function getLoggingUnitID() { return md5(getmypid().microtime()); } # -------------------------------------------------------------------------------------------- /** * */ static public function getCurrentLoggingUnitID() { global $g_change_log_unit_id; return $g_change_log_unit_id; } # -------------------------------------------------------------------------------------------- /** * */ static public function setChangeLogUnitID() { global $g_change_log_unit_id; if (!$g_change_log_unit_id) { $g_change_log_unit_id = BaseModel::getLoggingUnitID(); return true; } return false; } # -------------------------------------------------------------------------------------------- /** * */ static public function unsetChangeLogUnitID() { global $g_change_log_unit_id; $g_change_log_unit_id = null; return true; } # -------------------------------------------------------------------------------------------- /** * Returns number of records in table, filtering out those marked as deleted or those not meeting the specific access critera * * @param array $pa_access An option array of record-level access values to filter on. If omitted no filtering on access values is done. * @return int Number of records, or null if an error occurred. */ public function getCount($pa_access=null) { $o_db = new Db(); $va_wheres = array(); if (is_array($pa_access) && sizeof($pa_access) && $this->hasField('access')) { $va_wheres[] = "(access IN (".join(',', $pa_access)."))"; } if($this->hasField('deleted')) { $va_wheres[] = '(deleted = 0)'; } $vs_where_sql = join(" AND ", $va_wheres); $qr_res = $o_db->query(" SELECT count(*) c FROM ".$this->tableName()." ".(sizeof($va_wheres) ? ' WHERE ' : '')." {$vs_where_sql} "); if ($qr_res->nextRow()) { return (int)$qr_res->get('c'); } return null; } # -------------------------------------------------------------------------------------------- /** * Sets selected attribute of field in model to new value, overriding the value coded into the model for ** the duration of the current request** * This is useful in some unusual situations where you need to have a field behave differently than normal * without making permanent changes to the model. Don't use this unless you know what you're doing. * * @param string $ps_field The field * @param string $ps_attribute The attribute of the field * @param string $ps_value The value to set the attribute to * @return bool True if attribute was set, false if set failed because the field or attribute don't exist. */ public function setFieldAttribute($ps_field, $ps_attribute, $ps_value) { if(isset($this->FIELDS[$ps_field][$ps_attribute])) { $this->FIELDS[$ps_field][$ps_attribute] = $ps_value; return true; } return false; } # -------------------------------------------------------------------------------------------- /** * Destructor */ public function __destruct() { //print "Destruct ".$this->tableName()."\n"; //print (memory_get_usage()/1024)." used in ".$this->tableName()." destructor\n"; unset($this->o_db); unset($this->_CONFIG); unset($this->_DATAMODEL); unset($this->_MEDIA_VOLUMES); unset($this->_FILE_VOLUMES); unset($this->opo_app_plugin_manager); unset($this->_TRANSACTION); parent::__destruct(); } # -------------------------------------------------------------------------------------------- } // includes for which BaseModel must already be defined require_once(__CA_LIB_DIR__."/core/TaskQueue.php"); require_once(__CA_APP_DIR__.'/models/ca_lists.php'); require_once(__CA_APP_DIR__.'/models/ca_locales.php'); require_once(__CA_APP_DIR__.'/models/ca_item_tags.php'); require_once(__CA_APP_DIR__.'/models/ca_items_x_tags.php'); require_once(__CA_APP_DIR__.'/models/ca_item_comments.php'); require_once(__CA_APP_DIR__.'/models/ca_item_views.php'); ?>
avpreserve/nfai
admin/app/lib/core/BaseModel.php
PHP
gpl-2.0
355,871
/* This file is part of calliope. * * calliope 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. * * calliope 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 calliope. If not, see <http://www.gnu.org/licenses/>. */ package calliope.handler.post; import calliope.Connector; import calliope.exception.AeseException; import calliope.handler.post.importer.*; import calliope.constants.Formats; import calliope.importer.Archive; import calliope.constants.Config; import calliope.json.JSONDocument; import calliope.constants.Database; import calliope.constants.Params; import calliope.constants.JSONKeys; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.servlet.ServletFileUpload; /** * Handle import of a set of XML files from a tool like mmpupload. * @author desmond 23-7-2012 */ public class AeseXMLImportHandler extends AeseImportHandler { public void handle( HttpServletRequest request, HttpServletResponse response, String urn ) throws AeseException { try { if (ServletFileUpload.isMultipartContent(request) ) { parseImportParams( request ); Archive cortex = new Archive(docID.getWork(), docID.getAuthor(),Formats.MVD_TEXT,encoding); Archive corcode = new Archive(docID.getWork(), docID.getAuthor(),Formats.MVD_STIL,encoding); cortex.setStyle( style ); corcode.setStyle( style ); StageOne stage1 = new StageOne( files ); log.append( stage1.process(cortex,corcode) ); if ( stage1.hasFiles() ) { String suffix = ""; StageTwo stage2 = new StageTwo( stage1, false ); stage2.setEncoding( encoding ); log.append( stage2.process(cortex,corcode) ); StageThreeXML stage3Xml = new StageThreeXML( stage2, style, dict, hhExceptions ); stage3Xml.setStripConfig( getConfig(Config.stripper, stripperName) ); stage3Xml.setSplitConfig( getConfig(Config.splitter, splitterName) ); if ( stage3Xml.hasTEI() ) { ArrayList<File> notes = stage3Xml.getNotes(); if ( notes.size()> 0 ) { Archive nCorTex = new Archive(docID.getWork(), docID.getAuthor(),Formats.MVD_TEXT,encoding); nCorTex.setStyle( style ); Archive nCorCode = new Archive(docID.getWork(), docID.getAuthor(),Formats.MVD_STIL,encoding); StageThreeXML s3notes = new StageThreeXML( style,dict, hhExceptions); s3notes.setStripConfig( getConfig(Config.stripper, stripperName) ); s3notes.setSplitConfig( getConfig(Config.splitter, splitterName) ); for ( int j=0;j<notes.size();j++ ) s3notes.add(notes.get(j)); log.append( s3notes.process(nCorTex,nCorCode) ); addToDBase(nCorTex, "cortex", "notes" ); addToDBase( nCorCode, "corcode", "notes" ); // differentiate base from notes suffix = "base"; } if ( xslt == null ) xslt = Params.XSLT_DEFAULT; String transform = getConfig(Config.xslt,xslt); JSONDocument jDoc = JSONDocument.internalise( transform ); stage3Xml.setTransform( (String) jDoc.get(JSONKeys.BODY) ); } log.append( stage3Xml.process(cortex,corcode) ); addToDBase( cortex, "cortex", suffix ); addToDBase( corcode, "corcode", suffix ); // now get the json docs and add them at the right docid // Connector.getConnection().putToDb( Database.CORTEX, // docID.get(), cortex.toMVD("cortex") ); // log.append( cortex.getLog() ); // String fullAddress = docID.get()+"/"+Formats.DEFAULT; // log.append( Connector.getConnection().putToDb( // Database.CORCODE,fullAddress, corcode.toMVD("corcode")) ); // log.append( corcode.getLog() ); } response.setContentType("text/html;charset=UTF-8"); response.getWriter().println( wrapLog() ); } } catch ( Exception e ) { throw new AeseException( e ); } } }
discoverygarden/calliope
src/calliope/handler/post/AeseXMLImportHandler.java
Java
gpl-2.0
5,684
/* * 13.5.1 Thread Creation Scheduling Parameters, P1003.1c/Draft 10, p. 120 * * COPYRIGHT (c) 1989-1999. * On-Line Applications Research Corporation (OAR). * * The license and distribution terms for this file may be * found in the file LICENSE in this distribution or at * http://www.rtems.com/license/LICENSE. */ #if HAVE_CONFIG_H #include "config.h" #endif #include <pthread.h> #include <errno.h> int pthread_attr_setschedparam( pthread_attr_t *attr, const struct sched_param *param ) { if ( !attr || !attr->is_initialized || !param ) return EINVAL; attr->schedparam = *param; return 0; }
yangxi/omap4m3
cpukit/posix/src/pthreadattrsetschedparam.c
C
gpl-2.0
635
/**************************************************************** * This file is distributed under the following license: * * Copyright (C) 2010, Bernd Stramm * * 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., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. ****************************************************************/ #include <QRegExp> #include <QString> #include <QStringList> #include "shortener.h" #include "network-if.h" namespace chronicon { Shortener::Shortener (QObject *parent) :QObject (parent), network (0) { } void Shortener::SetNetwork (NetworkIF * net) { network = net; connect (network, SIGNAL (ShortenReply (QUuid, QString, QString, bool)), this, SLOT (CatchShortening (QUuid, QString, QString, bool))); } void Shortener::ShortenHttp (QString status, bool & wait) { if (network == 0) { emit DoneShortening (status); return; } QRegExp regular ("(https?://)(\\S*)"); status.append (" "); QStringList linkList; QStringList wholeList; int where (0), offset(0), lenSub(0); QString link, beforeLink; while ((where = regular.indexIn (status,offset)) > 0) { lenSub = regular.matchedLength(); beforeLink = status.mid (offset, where - offset); link = regular.cap(0); if ((!link.contains ("bit.ly")) && (!link.contains ("twitpic.com")) && (link.length() > QString("http://bit.ly/12345678").length())) { linkList << link; } wholeList << beforeLink; wholeList << link; offset = where + lenSub; } wholeList << status.mid (offset, -1); shortenTag = QUuid::createUuid(); if (linkList.isEmpty ()) { wait = false; } else { messageParts[shortenTag] = wholeList; linkParts [shortenTag] = linkList; network->ShortenHttp (shortenTag,linkList); wait = true; } } void Shortener::CatchShortening (QUuid tag, QString shortUrl, QString longUrl, bool good) { /// replace the longUrl with shortUrl in the messageParts[tag] // remove the longUrl from the linkParts[tag] // if the linkParts[tag] is empty, we have replaced all the links // so send append all the messageParts[tag] and finish the message if (messageParts.find(tag) == messageParts.end()) { return; // extra, perhaps duplicates in original, or not for me } if (linkParts.find(tag) == linkParts.end()) { return; } QStringList::iterator chase; for (chase = messageParts[tag].begin(); chase != messageParts[tag].end(); chase++) { if (*chase == longUrl) { *chase = shortUrl; } } linkParts[tag].removeAll (longUrl); if (linkParts[tag].isEmpty()) { QString message = messageParts[tag].join (QString()); emit DoneShortening (message); messageParts.erase (tag); } } } // namespace
berndhs/chronicon
chronicon/src/shortener.cpp
C++
gpl-2.0
3,400
<?php // $Id$ require_once("../../config.php"); require_once("lib.php"); require_once($CFG->libdir.'/gradelib.php'); $id = required_param('id', PARAM_INT); // course if (! $course = get_record("course", "id", $id)) { error("Course ID is incorrect"); } require_course_login($course); add_to_log($course->id, "assignment", "view all", "index.php?id=$course->id", ""); $strassignments = get_string("modulenameplural", "assignment"); $strassignment = get_string("modulename", "assignment"); $strassignmenttype = get_string("assignmenttype", "assignment"); $strweek = get_string("week"); $strtopic = get_string("topic"); $strname = get_string("name"); $strduedate = get_string("duedate", "assignment"); $strsubmitted = get_string("submitted", "assignment"); $strgrade = get_string("grade"); $navlinks = array(); $navlinks[] = array('name' => $strassignments, 'link' => '', 'type' => 'activity'); $navigation = build_navigation($navlinks); print_header_simple($strassignments, "", $navigation, "", "", true, "", navmenu($course)); if (!$cms = get_coursemodules_in_course('assignment', $course->id, 'm.assignmenttype, m.timedue')) { notice(get_string('noassignments', 'assignment'), "../../course/view.php?id=$course->id"); die; } $timenow = time(); $table = new object; if ($course->format == "weeks") { $table->head = array ($strweek, $strname, $strassignmenttype, $strduedate, $strsubmitted, $strgrade); $table->align = array ("center", "left", "left", "left", "right"); } else if ($course->format == "topics") { $table->head = array ($strtopic, $strname, $strassignmenttype, $strduedate, $strsubmitted, $strgrade); $table->align = array ("center", "left", "left", "left", "right"); } else { $table->head = array ($strname, $strassignmenttype, $strduedate, $strsubmitted, $strgrade); $table->align = array ("left", "left", "left", "right"); } $currentsection = ""; $types = assignment_types(); $modinfo = get_fast_modinfo($course); foreach ($modinfo->instances['assignment'] as $cm) { if (!$cm->uservisible) { continue; } $cm->timedue = $cms[$cm->id]->timedue; $cm->assignmenttype = $cms[$cm->id]->assignmenttype; $cm->idnumber = get_field('course_modules', 'idnumber', 'id', $cm->id); //hack //Show dimmed if the mod is hidden $class = $cm->visible ? '' : 'class="dimmed"'; $link = "<a $class href=\"view.php?id=$cm->id\">".format_string($cm->name)."</a>"; $printsection = ""; if ($cm->sectionnum !== $currentsection) { if ($cm->sectionnum) { $printsection = $cm->sectionnum; } if ($currentsection !== "") { $table->data[] = 'hr'; } $currentsection = $cm->sectionnum; } if (!file_exists($CFG->dirroot.'/mod/assignment/type/'.$cm->assignmenttype.'/assignment.class.php')) { continue; } require_once ($CFG->dirroot.'/mod/assignment/type/'.$cm->assignmenttype.'/assignment.class.php'); $assignmentclass = 'assignment_'.$cm->assignmenttype; $assignmentinstance = new $assignmentclass($cm->id, NULL, $cm, $course); $submitted = $assignmentinstance->submittedlink(true); $grading_info = grade_get_grades($course->id, 'mod', 'assignment', $cm->instance, $USER->id); if (isset($grading_info->items[0]) && !$grading_info->items[0]->grades[$USER->id]->hidden ) { $grade = $grading_info->items[0]->grades[$USER->id]->str_grade; } else { $grade = '-'; } $type = $types[$cm->assignmenttype]; $due = $cm->timedue ? userdate($cm->timedue) : '-'; if ($course->format == "weeks" or $course->format == "topics") { $table->data[] = array ($printsection, $link, $type, $due, $submitted, $grade); } else { $table->data[] = array ($link, $type, $due, $submitted, $grade); } } echo "<br />"; print_table($table); print_footer($course); ?>
IOC/moodle19
mod/assignment/index.php
PHP
gpl-2.0
4,258
void RedboxFactory::add (Addr addr, ActionType t) { switch (t) { case ActionType::RD8 : return add_read (addr, 1); case ActionType::RD16 : return add_read (addr, 2); case ActionType::RD32 : return add_read (addr, 4); case ActionType::RD64 : return add_read (addr, 8); case ActionType::WR8 : return add_write (addr, 1); case ActionType::WR16 : return add_write (addr, 2); case ActionType::WR32 : return add_write (addr, 4); case ActionType::WR64 : return add_write (addr, 8); default : SHOW (t, "d"); ASSERT (0); } } void RedboxFactory::add_read (Addr addr, unsigned size) { ASSERT (size); read_regions.emplace_back (addr, size); } void RedboxFactory::add_write (Addr addr, unsigned size) { ASSERT (size); write_regions.emplace_back (addr, size); } void RedboxFactory::clear () { read_regions.clear (); write_regions.clear (); } Redbox *RedboxFactory::create () { Redbox *b; // Special case: we return a null pointer if both memory pools are empty. // In this case the event will continue being labelled by a null pointer // rather than a pointer to a Redbox. This is useful during the data race // detection in DataRaceAnalysis::find_data_races(), because that way we // don't even need to look inside of the red box to see if it has events, the // event will straightfowardly be discarde for DR detection if (read_regions.empty() and write_regions.empty()) return nullptr; // allocate a new Redbox and keep the pointer to it, we are the container b = new Redbox (); boxes.push_back (b); // compress the lists of memory areas compress (read_regions); compress (write_regions); // copy them to the new redbox b->readpool = read_regions; b->writepool = write_regions; #ifdef CONFIG_DEBUG if (verb_debug) b->dump (); // this will assert that the memory pools are a sorted sequence of disjoint // memory areas b->readpool.assertt (); b->writepool.assertt (); #endif // restart the internal arrays read_regions.clear (); write_regions.clear (); ASSERT (empty()); return b; } void RedboxFactory::compress (MemoryPool::Container &regions) { unsigned i, j; size_t s; // nothing to do if we have no regions; code below assumes we have at least 1 if (regions.empty ()) return; // sort the memory regions by increasing value of lower bound struct compare { bool operator() (const MemoryRegion<Addr> &a, const MemoryRegion<Addr> &b) { return a.lower < b.lower; } } cmp; std::sort (regions.begin(), regions.end(), cmp); // compress regions s = regions.size (); breakme (); for (i = 0, j = 1; j < s; ++j) { ASSERT (i < j); ASSERT (regions[i].lower <= regions[j].lower); // if the next region's lower bound is below i's region upper bound, we can // extend i's range if (regions[i].upper >= regions[j].lower) { regions[i].upper = std::max (regions[i].upper, regions[j].upper); } else { // otherwise there is a gap betwen interval i and interval j, so we // need to create a new interval at offset i+1, only if i+1 != j ++i; if (i != j) { // copy j into i regions[i] = regions[j]; } } } DEBUG ("redbox-factory: compressed %zu regions into %u", regions.size(), i+1); regions.resize (i + 1); }
cesaro/dpu
src/redbox-factory.hpp
C++
gpl-2.0
3,512
///** // * ClassName: MainTest.java // * Date: 2017年5月16日 // */ //package com.ojdbc.sql.test; // //import java.sql.Connection; //import java.sql.SQLException; // //import com.ojdbc.sql.ConnectionObject; //import com.ojdbc.sql.DataBase; //import com.ojdbc.sql.DataBaseEnum; //import com.ojdbc.sql.DataBaseManager; //import com.ojdbc.sql.SQLResultSet; //import com.ojdbc.sql.connection.MongoDataBaseConnection; //import com.ojdbc.sql.connection.MySQLDataBaseConnection; //import com.ojdbc.sql.connection.OracleDataBaseConnection; //import com.ojdbc.sql.connection.SQLiteDataBaseConnection; // ///** // * Author: ShaoGaige // * Description: 猪测试类 // * Log: // */ //public class MainTest { // // /** // * @param args // * @throws SQLException // */ // public static void main(String[] args) throws SQLException { // // TODO Auto-generated method stub // ConnectionObject conn; // // SQLiteDataBaseConnection sqlite = new SQLiteDataBaseConnection(); // String dataBaseURL = "jdbc:sqlite://E:/shaogaige/iNote/iNoteRun/data/iNoteData.note"; // String userName = ""; // String passWord = ""; // conn = sqlite.createConnection(dataBaseURL, userName, passWord); // System.out.println(conn.getMetaData().getURL()); // // DataBase database = new DataBase(conn); // SQLResultSet rs =database.exeSQLSelect("select * from noteinfo"); // System.out.println(rs.getRowNum()); // // MongoDataBaseConnection mongo = new MongoDataBaseConnection(); // dataBaseURL = "jdbc:mongo://172.15.103.42:10001/geoglobe"; // userName = "data"; // passWord = "data"; // conn = mongo.createConnection(dataBaseURL, userName, passWord); // System.out.println(conn.getMetaData().getURL()); // // MySQLDataBaseConnection mysql = new MySQLDataBaseConnection(); // dataBaseURL = "jdbc:mysql://172.15.103.42:3306/geoglobe"; // userName = "root"; // passWord = "root"; // conn = mysql.createConnection(dataBaseURL, userName, passWord); // System.out.println(conn.getMetaData().getURL()); // // OracleDataBaseConnection oracle = new OracleDataBaseConnection(); // dataBaseURL = "jdbc:oracle:thin:@172.15.103.43:1521:geoglobe"; // userName = "autotest"; // passWord = "autotest"; // conn = oracle.createConnection(dataBaseURL, userName, passWord); // System.out.println(conn.getMetaData().getURL()); // // DataBaseManager.getDataBase(DataBaseEnum.ORACLE, "", "", ""); // } // //}
shaogaige/iDataBaseConnection
src/com/ojdbc/sql/test/MainTest.java
Java
gpl-2.0
2,468
/* * ===================================================================================== * * Filename: bmp_pixmap_fill.cpp * * Description: Fill the whole bmp with one color. * * Version: 1.0 * Created: 2009年04月11日 16时45分26秒 * Revision: none * Compiler: gcc * * Author: Xu Lijian (ivenvd), [email protected] * Company: CUGB, China * * ===================================================================================== */ #include "bmp_pixmap.h" /* *-------------------------------------------------------------------------------------- * Class: BmpPixmap * Method: fill * Description: Fill the whole bmp with one color. *-------------------------------------------------------------------------------------- */ BmpPixmap & BmpPixmap::fill (const BmpPixel &pixel) { BmpPixmap *temp = new BmpPixmap (*this); for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { *temp->pdata [i][j] = pixel; } } return *temp; } /* ----- end of method BmpPixmap::fill ----- */ BmpPixmap & BmpPixmap::fill (Byte b, Byte g, Byte r) { BmpPixmap *temp = new BmpPixmap (*this); for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { temp->pdata [i][j]->set (b, g, r); } } return *temp; } /* ----- end of method BmpPixmap::fill ----- */
iven/dip
src/bmp_pixmap/bmp_pixmap_fill.cpp
C++
gpl-2.0
1,440
// This file is part of VideoPad. // // VideoPad 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. // // VideoPad 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 VideoPad; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #pragma once #include "CaptureDevice.h" class CAudioCaptureDevice : public CCaptureDevice { public: CAudioCaptureDevice(); // init capture device by given COM object ID // HRESULT Create( CString szID ); const DWORD& GetPreferredSamplesPerSec(); const WORD& GetPreferredBitsPerSample(); const WORD& GetPreferredChannels(); const DWORD& GetSamplesPerSec(); const WORD& GetBitsPerSample(); const WORD& GetChannels(); void SetPreferredAudioSamplesPerSec( DWORD nSamplesPerSec ); void SetPreferredAudioBitsPerSample( WORD wBitsPerSample ); void SetPreferredAudioChannels( WORD nChannels ); // these functions are used by CAudioGraph to set // the current audio format information of the graph // and the device // void SetAudioSamplesPerSec( DWORD nSamplesPerSec ); void SetAudioBitsPerSample( WORD wBitsPerSample ); void SetAudioChannels( WORD nChannels ); private: DWORD m_nPreferredSamplesPerSec; WORD m_wPreferredBitsPerSample; WORD m_nPreferredChannels; DWORD m_nSamplesPerSec; WORD m_wBitsPerSample; WORD m_nChannels; };
nonoo/videopad
DirectShow/AudioCaptureDevice.h
C
gpl-2.0
1,898
'use strict'; angular.module('eshttp') .filter('unixtostr', function() { return function(str){ var dt; dt = Date.create(str * 1000).format('{yyyy}-{MM}-{dd} {HH}:{mm}:{ss}'); if (dt == "Invalid Date") { return 'N/A'; } else { return dt; } }; });
fangli/eshttp
eshttp_webmanager/cloudconfig/static/filters/unixtostr.js
JavaScript
gpl-2.0
323
#include "thanks.h" // // EternityProject Public message START: // - To the "developers" like franciscofranco: Are you able to work on your own? Also, if you want to badly copy my commits, can you at least give credits to the proprietary of the commit you're copying? We're an opensource community, we do this for free... but we also are satisfacted of the TIME WE LOSE on the things we do. We want to work with everyone that wants to. We publish our sources. We give you all everything we do. And you? Instead of copying someone else's work, try to lose time on your own at least sorting the not working commits (yeah, I knew someone was copying my work and I've committed some fakes). You did that badly. The EternityProject Team Manager & Main Developer, --kholk // // EternityProject Public message END //
kozmikkick/eternityprj-kernel-endeavoru-128
arch/arm/mach-tegra/EternityProject.c
C
gpl-2.0
827
<?php /* * This file is part of PHPExifTool. * * (c) 2012 Romain Neutron <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\Microsoft; use PHPExiftool\Driver\AbstractTag; class Duration extends AbstractTag { protected $Id = 'mixed'; protected $Name = 'Duration'; protected $FullName = 'Microsoft::Xtra'; protected $GroupName = 'Microsoft'; protected $g0 = 'QuickTime'; protected $g1 = 'Microsoft'; protected $g2 = 'Video'; protected $Type = '?'; protected $Writable = false; protected $Description = 'Duration'; }
Droces/casabio
vendor/phpexiftool/phpexiftool/lib/PHPExiftool/Driver/Tag/Microsoft/Duration.php
PHP
gpl-2.0
707
#ifndef __STACK_TESTS_H_INCLUDED__ #define __STACK_TESTS_H_INCLUDED__ //------------------------------------- #include "../CppTest/cpptest.h" #include "../Raple/Headers/Stack.h" //------------------------------------- //------------------------------------- #ifdef _MSC_VER #pragma warning (disable: 4290) #endif //------------------------------------- using Raple::Stack; using Raple::StackOverflowException; using Raple::StackUnderflowException; //------------------------------------- namespace RapleTests { class StackTests : public Test::Suite { public: StackTests() { addTest(StackTests::SizeTest); addTest(StackTests::PushAndPopTest); addTest(StackTests::OverflowExceptionTest); addTest(StackTests::UnderflowExceptionTest); } private: void SizeTest() { Stack<int> s; assertEquals(0, s.Size()); s.Push(1); s.Push(2); assertEquals(2, s.Size()); s.Pop(); assertEquals(1, s.Size()); s.Pop(); assertEquals(0, s.Size()); } void PushAndPopTest() { Stack<int> s; s.Push(1); s.Push(2); s.Push(3); assertEquals(3, s.Pop()); assertEquals(2, s.Pop()); assertEquals(1, s.Pop()); } void OverflowExceptionTest() { Stack<int> s(2); s.Push(1); s.Push(2); try { s.Push(3); } catch (StackOverflowException ex) { assert(true); return; } assert(false); } void UnderflowExceptionTest() { Stack<int> s; try { s.Pop(); } catch (StackUnderflowException ex) { assert(true); return; } assert(false); } }; } #endif //__STACK_TESTS_H_INCLUDED__
rodionovstepan/raple
src/Tests/StackTests.h
C
gpl-2.0
1,631
# Install script for directory: /home/hscore # Set the install prefix IF(NOT DEFINED CMAKE_INSTALL_PREFIX) SET(CMAKE_INSTALL_PREFIX "/home/root/hswow") ENDIF(NOT DEFINED CMAKE_INSTALL_PREFIX) STRING(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}") # Set the install configuration name. IF(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME) IF(BUILD_TYPE) STRING(REGEX REPLACE "^[^A-Za-z0-9_]+" "" CMAKE_INSTALL_CONFIG_NAME "${BUILD_TYPE}") ELSE(BUILD_TYPE) SET(CMAKE_INSTALL_CONFIG_NAME "Release") ENDIF(BUILD_TYPE) MESSAGE(STATUS "Install configuration: \"${CMAKE_INSTALL_CONFIG_NAME}\"") ENDIF(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME) # Set the component getting installed. IF(NOT CMAKE_INSTALL_COMPONENT) IF(COMPONENT) MESSAGE(STATUS "Install component: \"${COMPONENT}\"") SET(CMAKE_INSTALL_COMPONENT "${COMPONENT}") ELSE(COMPONENT) SET(CMAKE_INSTALL_COMPONENT) ENDIF(COMPONENT) ENDIF(NOT CMAKE_INSTALL_COMPONENT) # Install shared libraries without execute permission? IF(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE) SET(CMAKE_INSTALL_SO_NO_EXE "1") ENDIF(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE) IF(NOT CMAKE_INSTALL_LOCAL_ONLY) # Include the install script for each subdirectory. INCLUDE("/home/hscore/src/dep/cmake_install.cmake") INCLUDE("/home/hscore/src/src/cmake_install.cmake") ENDIF(NOT CMAKE_INSTALL_LOCAL_ONLY) IF(CMAKE_INSTALL_COMPONENT) SET(CMAKE_INSTALL_MANIFEST "install_manifest_${CMAKE_INSTALL_COMPONENT}.txt") ELSE(CMAKE_INSTALL_COMPONENT) SET(CMAKE_INSTALL_MANIFEST "install_manifest.txt") ENDIF(CMAKE_INSTALL_COMPONENT) FILE(WRITE "/home/hscore/src/${CMAKE_INSTALL_MANIFEST}" "") FOREACH(file ${CMAKE_INSTALL_MANIFEST_FILES}) FILE(APPEND "/home/hscore/src/${CMAKE_INSTALL_MANIFEST}" "${file}\n") ENDFOREACH(file)
Diabloxx/HS-WoW2
src/cmake_install.cmake
CMake
gpl-2.0
1,800
#ifndef CONTROLPANEL_INCLUDED #define CONTROLPANEL_INCLUDED #include <qwidget.h> //Added by qt3to4: #include <Q3GridLayout> #include <list> #include <q3frame.h> #include <qlayout.h> #include <qlabel.h> class Control; class MetaGear; class GearControl; class ControlPanel : public QWidget { public: ControlPanel(QWidget *panelContainerWidget, MetaGear *parentMetagear); ~ControlPanel(); Control *addControl(GearControl* gear); void addControlPanel(ControlPanel* controlPanel); QWidget *mainWidget(){return _mainFrame;} private: std::list<Control*> _controls; std::list<ControlPanel*> _controlPanels; MetaGear *_parentMetaGear; Q3Frame *_mainFrame; Q3GridLayout *_mainLayout; QLabel *_labelName; }; #endif
sofian/drone
src/core/ControlPanel.h
C
gpl-2.0
742
%!TEX root = ../MC_SS17.tex \section{Büchi-Automaten} \label{sec:para5} \nextlecture \cleardoubleoddemptypage
JaMeZ-B/latex-wwu
MC_SS17/content/05.tex
TeX
gpl-2.0
112
/* Copyright (c) 2003-2021, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'colordialog', 'en-gb', { clear: 'Clear', highlight: 'Highlight', options: 'Colour Options', selected: 'Selected Colour', title: 'Select colour' } );
WBCE/WebsiteBaker_CommunityEdition
wbce/modules/ckeditor/ckeditor/plugins/colordialog/lang/en-gb.js
JavaScript
gpl-2.0
344
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>站点列表</title> <link rel="stylesheet" href="../layui/css/layui.css"> <link type="text/css" rel="styleSheet" href="../style/common.css"> </link> <link type="text/css" rel="styleSheet" href="../style/siteList.css"> </link> <script src="https://cdn.bootcss.com/jquery/3.4.0/jquery.min.js"></script> <script src="https://cdn.bootcss.com/echarts/4.2.1-rc.2/echarts.min.js"></script> <script type="text/javascript" src="../theme/purple-passion.js"></script> <script type="text/javascript" src="../js/iconfont.js"></script> <script type="text/javascript" src="../layui/layui.js"></script> <script src="../js/template-web.js"></script> <script type="text/javascript" src="../js/common.js"></script> <script type="text/javascript" src="../js/siteList.js"></script> <script> var whdef = 100 / 1920;// 表示1920的设计图,使用100PX的默认值 var wH = window.innerHeight;// 当前窗口的高度 var wW = window.innerWidth;// 当前窗口的宽度 var rem = wW * whdef;// 以默认比例值乘以当前窗口宽度,得到该宽度下的相应FONT-SIZE值 $('html').css('font-size', rem + "px"); layui.use(['form'], function () { var form = layui.form; }); </script> </head> <body> <div class="nav" id='nav'> <a href="./index.html">运行监控</a> <a href="./management.html">经营监控</a> <a href="./warnMonitor.html">预警监控</a> <svg class="icon navLockIcon" aria-hidden="true" id="lockBtn"> <use xlink:href="#icon-lock-line"></use> </svg> </div> <div class="siderWrap" id="siderWrap" data-visible='false'> <div class="siderBtn" id="siderBtn"> <svg class="icon siderBtnIcon" aria-hidden="true"> <use xlink:href="#icon-zuojiantou"></use> </svg> </div> <div class="sider" id="sider"> <div class="clearfix"> <div class="siderHeader">监控管理气站</div> <div class="siderGeoBtn" id="siderGeoBtn">坐标图</div> </div> <div class="searchBox"> <svg class="baiyanIcon menuIcon" aria-hidden="true"> <use xlink:href="#icon-caidan"></use> </svg> <input class="searchInput" placeholder="输入关键字" /> <svg class="baiyanIcon searchIcon" aria-hidden="true"> <use xlink:href="#icon-xiazai17"></use> </svg> </div> <h5 class="title2 mgt35">全国站点监控总量</h5> <div class="dashLine"></div> <div class="dataStatistics"> <div class="digit_set"></div> <div class="digit_set"></div> <div class="digit_set"></div> <div class="digit_set set_last"></div> </div> <!-- 具体监控描述 --> <div class="siteNumWrapper clearfix"> <div>华东:123</div> <div>东北:123</div> <div>西北:123</div> </div> <h5 class="title2 mgt17">全站今日累计报警(3)</h5> <div class="dashLine"></div> <div class="warningBox clearfix"> <div> <span>运行报警</span> <span>(3)</span> </div> <div> <span>设备超期报警</span> <span>(3)</span> </div> <div> <span>维修超期报警</span> <span>(3)</span> </div> </div> <div class="mgt17"> <h5 class="title2">故障总量</h5> <span class="oneyear">2018年</span> <span class="twoyear">2019年</span> </div> <div class="dashLine"></div> <!-- 柱状图1 --> <div id="barCharts1"></div> <h5 class="title2 mgt17">全年故障处理完成率</h5> <div class="dashLine"></div> <!-- 饼图1 --> <div id="pieCharts1"></div> </div> </div> <!-- LNG按钮 --> <div id="lngBtn" data-show="false"> <div id="lngBtnHidden">LNG</div> <div id="lngBtnShow"> <svg class="icon shouqiIcon" aria-hidden="true"> <use xlink:href="#icon-zuojiantou"></use> </svg> <a class="btn private" href="./siteList.html">站点列表</a> <a class="btn private">设备列表</a> <a class="btn default">定制</a> </div> </div> <!-- 具体页面内容 --> <div class="siteList"> <div class="siteItemBox"> <div class="siteItem"> <div class="imgWrap"> <img src="../images/demo.jpg" /> </div> <div class="clearfix info"> <div class="name">众信源浦村加气站</div> <div class="success"> <img src="../images/chenggong.png"/> <span>80%</span> </div> <div class="error"> <img src="../images/shibai.png"/> <span>80%</span> </div> </div> </div> </div> </div> </body> <script type="text/html" id="tpl1"> {{each list}} <div class="siteItemBox"> <div class="siteItem"> <div class="imgWrap"> <img src="../images/demo.jpg" /> </div> <div class="clearfix info"> <div class="name">众信源浦村加气站</div> <div class="success"> <img src="../images/chenggong.png"/> <span>80%</span> </div> <div class="error"> <img src="../images/shibai.png"/> <span>80%</span> </div> </div> </div> </div> {{/each}} </script> </html>
xiangxik/xiangxik.github.io
html/baiyan_web_pc/html/siteList.html
HTML
gpl-2.0
5,586
{% load i18n %} <ul class="nav nav-tabs"> <li id="tab-basic"> <a href="{% url 'settings:basic-setting' %}" class="text-center"><i class="fa fa-cubes"></i> {% trans 'Basic setting' %}</a> </li> <li id="tab-email" > <a href="{% url 'settings:email-setting' %}" class="text-center"><i class="fa fa-envelope"></i> {% trans 'Email setting' %} </a> </li> <li id="tab-email-content" > <a href="{% url 'settings:email-content-setting' %}" class="text-center"><i class="fa fa-file-text"></i> {% trans 'Email content setting' %} </a> </li> <li id="tab-ldap"> <a href="{% url 'settings:ldap-setting' %}" class="text-center"><i class="fa fa-archive"></i> {% trans 'LDAP setting' %} </a> </li> <li id="tab-terminal"> <a href="{% url 'settings:terminal-setting' %}" class="text-center"><i class="fa fa-hdd-o"></i> {% trans 'Terminal setting' %} </a> </li> <li id="tab-security"> <a href="{% url 'settings:security-setting' %}" class="text-center"><i class="fa fa-lock"></i> {% trans 'Security setting' %} </a> </li> </ul> <script> $(document).ready(function () { var path = location.pathname; if (path.endsWith('/')) { path = path.substring(0, path.length-1) } var pathList = path.split('/'); var tabId = pathList[pathList.length-1]; if (tabId === "settings") { tabId = "basic" } tabId = "#tab-" + tabId; $(tabId).addClass("active") }) </script>
zsjohny/jumpserver
apps/settings/templates/settings/_setting_tabs.html
HTML
gpl-2.0
1,483
<?php if(!defined('kernel_entry') || !kernel_entry) die('Not A Valid Entry Point'); require_once('include/data/cls_table_view_base.php'); class cls_view_drupal_registry_d855ab16_bba7_43de_b448_7e9b9d78edec extends cls_table_view_base { private $p_column_definitions = null; function __construct() { $a = func_get_args(); $i = func_num_args(); if (method_exists($this,$f="__construct".$i)) { call_user_func_array(array($this,$f),$a); } } public function query($search_values,$limit,$offset) { require_once('include/data/table_factory/cls_table_factory.php'); $common_drupal_registry = cls_table_factory::get_common_drupal_registry(); $array_drupal_registry = $common_drupal_registry->get_drupal_registrys($this->get_db_manager(),$this->get_application(),$search_values,$limit,$offset,false); $result_array = array(); foreach($array_drupal_registry as $drupal_registry) { $drupal_registry_id = $drupal_registry->get_id(); $result_array[$drupal_registry_id]['drupal_registry.name'] = $drupal_registry->get_name(); $result_array[$drupal_registry_id]['drupal_registry.type'] = $drupal_registry->get_type(); $result_array[$drupal_registry_id]['drupal_registry.filename'] = $drupal_registry->get_filename(); $result_array[$drupal_registry_id]['drupal_registry.module'] = $drupal_registry->get_module(); $result_array[$drupal_registry_id]['drupal_registry.weight'] = $drupal_registry->get_weight(); $result_array[$drupal_registry_id]['drupal_registry.id'] = $drupal_registry->get_id(); } return $result_array; } public function get_column_definitions() { if (!is_null($this->p_column_definitions)) return $this->p_column_definitions; { $this->p_column_definitions = array(); $this->p_column_definitions['drupal_registry.name']['type'] = 'varchar'; $this->p_column_definitions['drupal_registry.type']['type'] = 'varchar'; $this->p_column_definitions['drupal_registry.filename']['type'] = 'varchar'; $this->p_column_definitions['drupal_registry.module']['type'] = 'varchar'; $this->p_column_definitions['drupal_registry.weight']['type'] = 'int4'; $this->p_column_definitions['drupal_registry.id']['type'] = 'uuid'; } return $this->p_column_definitions; } } ?>
dl4gbe/kernel
include/data/table_views/cls_view_drupal_registry_d855ab16_bba7_43de_b448_7e9b9d78edec.php
PHP
gpl-2.0
2,247
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>CHAI3D: /home/seb/workspace/chai3d-2.0.0/src/scenegraph/CGenericObject.h File Reference</title> <link href="doxygen.css" rel="stylesheet" type="text/css"> <link href="tabs.css" rel="stylesheet" type="text/css"> </head><body> <!-- Generated by Doxygen 1.5.5 --> <div class="navigation" id="top"> <div class="tabs"> <ul> <li><a href="index.html"><span>Main&nbsp;Page</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> </ul> </div> </div> <div class="contents"> <h1>/home/seb/workspace/chai3d-2.0.0/src/scenegraph/CGenericObject.h File Reference</h1><b> Scenegraph </b> <br> Base Class. <a href="#_details">More...</a> <p> <code>#include &quot;<a class="el" href="_c_maths_8h-source.html">math/CMaths.h</a>&quot;</code><br> <code>#include &quot;<a class="el" href="_c_draw3_d_8h-source.html">graphics/CDraw3D.h</a>&quot;</code><br> <code>#include &quot;<a class="el" href="_c_color_8h-source.html">graphics/CColor.h</a>&quot;</code><br> <code>#include &quot;<a class="el" href="_c_macros_g_l_8h-source.html">graphics/CMacrosGL.h</a>&quot;</code><br> <code>#include &quot;<a class="el" href="_c_material_8h-source.html">graphics/CMaterial.h</a>&quot;</code><br> <code>#include &quot;<a class="el" href="_c_texture2_d_8h-source.html">graphics/CTexture2D.h</a>&quot;</code><br> <code>#include &quot;<a class="el" href="_c_collision_basics_8h-source.html">collisions/CCollisionBasics.h</a>&quot;</code><br> <code>#include &quot;<a class="el" href="_c_interaction_basics_8h-source.html">forces/CInteractionBasics.h</a>&quot;</code><br> <code>#include &quot;<a class="el" href="_c_generic_effect_8h-source.html">effects/CGenericEffect.h</a>&quot;</code><br> <code>#include &quot;<a class="el" href="_c_generic_type_8h-source.html">extras/CGenericType.h</a>&quot;</code><br> <code>#include &lt;typeinfo&gt;</code><br> <code>#include &lt;vector&gt;</code><br> <code>#include &lt;list&gt;</code><br> <p> <a href="_c_generic_object_8h-source.html">Go to the source code of this file.</a><table border="0" cellpadding="0" cellspacing="0"> <tr><td></td></tr> <tr><td colspan="2"><br><h2>Classes</h2></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">class &nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classc_generic_object.html">cGenericObject</a></td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">This class is the root of basically every render-able object in CHAI. It defines a reference frame (position and rotation) and virtual methods for rendering, which are overloaded by useful subclasses. <br> . <a href="classc_generic_object.html#_details">More...</a><br></td></tr> <tr><td colspan="2"><br><h2>Enumerations</h2></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">enum &nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="_c_generic_object_8h.html#b7dfc0d18c5e05621dd13575f917fb3d">chai_render_modes</a> { <b>CHAI_RENDER_MODE_RENDER_ALL</b> = 0, <b>CHAI_RENDER_MODE_NON_TRANSPARENT_ONLY</b>, <b>CHAI_RENDER_MODE_TRANSPARENT_BACK_ONLY</b>, <b>CHAI_RENDER_MODE_TRANSPARENT_FRONT_ONLY</b> }</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Constants that define specific rendering passes (see cCamera.cpp). <br></td></tr> </table> <hr><a name="_details"></a><h2>Detailed Description</h2> <b> Scenegraph </b> <br> Base Class. <p> </div> <font size=-2><br><hr><b>CHAI3D 2.0.0 documentation</b><br>Please address any questions to <a href="mailto:[email protected]">[email protected]</a><br> (C) 2003-2009 - <a href="http://www.chai3d.org">CHAI 3D</a><br> All Rights Reserved.
lihuanshuai/chai3d
doc/resources/html/_c_generic_object_8h.html
HTML
gpl-2.0
3,948
//-------------------------------------------------------------------------- // Copyright (C) 2015-2016 Cisco and/or its affiliates. All rights reserved. // // 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. You may not use, modify or distribute // this program under any other version of the GNU General Public 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., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. //-------------------------------------------------------------------------- // rule_profiler.cc author Joel Cornett <[email protected]> #include "rule_profiler.h" #if HAVE_CONFIG_H #include "config.h" #endif #include <algorithm> #include <functional> #include <iostream> #include <sstream> #include <vector> #include "detection/detection_options.h" #include "detection/treenodes.h" #include "hash/sfghash.h" #include "main/snort_config.h" #include "main/thread_config.h" #include "parser/parser.h" #include "target_based/snort_protocols.h" #include "profiler_printer.h" #include "profiler_stats_table.h" #include "rule_profiler_defs.h" #ifdef UNIT_TEST #include "catch/catch.hpp" #endif #define s_rule_table_title "Rule Profile Statistics" static inline OtnState& operator+=(OtnState& lhs, const OtnState& rhs) { lhs.elapsed += rhs.elapsed; lhs.elapsed_match += rhs.elapsed_match; lhs.checks += rhs.checks; lhs.matches += rhs.matches; lhs.alerts += rhs.alerts; return lhs; } namespace rule_stats { static const StatsTable::Field fields[] = { { "#", 5, '\0', 0, std::ios_base::left }, { "gid", 6, '\0', 0, std::ios_base::fmtflags() }, { "sid", 6, '\0', 0, std::ios_base::fmtflags() }, { "rev", 4, '\0', 0, std::ios_base::fmtflags() }, { "checks", 7, '\0', 0, std::ios_base::fmtflags() }, { "matches", 8, '\0', 0, std::ios_base::fmtflags() }, { "alerts", 7, '\0', 0, std::ios_base::fmtflags() }, { "time (us)", 10, '\0', 0, std::ios_base::fmtflags() }, { "avg/check", 10, '\0', 1, std::ios_base::fmtflags() }, { "avg/match", 10, '\0', 1, std::ios_base::fmtflags() }, { "avg/non-match", 14, '\0', 1, std::ios_base::fmtflags() }, { "timeouts", 9, '\0', 0, std::ios_base::fmtflags() }, { "suspends", 9, '\0', 0, std::ios_base::fmtflags() }, { nullptr, 0, '\0', 0, std::ios_base::fmtflags() } }; struct View { OtnState state; SigInfo sig_info; hr_duration elapsed() const { return state.elapsed; } hr_duration elapsed_match() const { return state.elapsed_match; } hr_duration elapsed_no_match() const { return elapsed() - elapsed_match(); } uint64_t checks() const { return state.checks; } uint64_t matches() const { return state.matches; } uint64_t no_matches() const { return checks() - matches(); } uint64_t alerts() const { return state.alerts; } uint64_t timeouts() const { return state.latency_timeouts; } uint64_t suspends() const { return state.latency_suspends; } hr_duration time_per(hr_duration d, uint64_t v) const { if ( v == 0 ) return 0_ticks; return hr_duration(d.count() / v); } hr_duration avg_match() const { return time_per(elapsed_match(), matches()); } hr_duration avg_no_match() const { return time_per(elapsed_no_match(), no_matches()); } hr_duration avg_check() const { return time_per(elapsed(), checks()); } View(const OtnState& otn_state, const SigInfo* si = nullptr) : state(otn_state) { if ( si ) // FIXIT-L J does sig_info need to be initialized otherwise? sig_info = *si; } }; static const ProfilerSorter<View> sorters[] = { { "", nullptr }, { "checks", [](const View& lhs, const View& rhs) { return lhs.checks() >= rhs.checks(); } }, { "avg_check", [](const View& lhs, const View& rhs) { return lhs.avg_check() >= rhs.avg_check(); } }, { "total_time", [](const View& lhs, const View& rhs) { return lhs.elapsed().count() >= rhs.elapsed().count(); } }, { "matches", [](const View& lhs, const View& rhs) { return lhs.matches() >= rhs.matches(); } }, { "no_matches", [](const View& lhs, const View& rhs) { return lhs.no_matches() >= rhs.no_matches(); } }, { "avg_match", [](const View& lhs, const View& rhs) { return lhs.avg_match() >= rhs.avg_match(); } }, { "avg_no_match", [](const View& lhs, const View& rhs) { return lhs.avg_no_match() >= rhs.avg_no_match(); } } }; static void consolidate_otn_states(OtnState* states) { for ( unsigned i = 1; i < ThreadConfig::get_instance_max(); ++i ) states[0] += states[i]; } static std::vector<View> build_entries() { assert(snort_conf); detection_option_tree_update_otn_stats(snort_conf->detection_option_tree_hash_table); auto* otn_map = snort_conf->otn_map; std::vector<View> entries; for ( auto* h = sfghash_findfirst(otn_map); h; h = sfghash_findnext(otn_map) ) { auto* otn = static_cast<OptTreeNode*>(h->data); assert(otn); auto* states = otn->state; consolidate_otn_states(states); auto& state = states[0]; if ( !state ) continue; // FIXIT-L J should we assert(otn->sigInfo)? entries.emplace_back(state, &otn->sigInfo); } return entries; } // FIXIT-L J logic duplicated from ProfilerPrinter static void print_single_entry(const View& v, unsigned n) { using std::chrono::duration_cast; using std::chrono::microseconds; std::ostringstream ss; { StatsTable table(fields, ss); table << StatsTable::ROW; table << n; // # table << v.sig_info.generator; // gid table << v.sig_info.id; // sid table << v.sig_info.rev; // rev table << v.checks(); // checks table << v.matches(); // matches table << v.alerts(); // alerts table << duration_cast<microseconds>(v.elapsed()).count(); // time table << duration_cast<microseconds>(v.avg_check()).count(); // avg/check table << duration_cast<microseconds>(v.avg_match()).count(); // avg/match table << duration_cast<microseconds>(v.avg_no_match()).count(); // avg/non-match table << v.timeouts(); table << v.suspends(); } LogMessage("%s", ss.str().c_str()); } // FIXIT-L J logic duplicated from ProfilerPrinter static void print_entries(std::vector<View>& entries, ProfilerSorter<View> sort, unsigned count) { std::ostringstream ss; { StatsTable table(fields, ss); table << StatsTable::SEP; table << s_rule_table_title; if ( count ) table << " (worst " << count; else table << " (all"; if ( sort ) table << ", sorted by " << sort.name; table << ")\n"; table << StatsTable::HEADER; } LogMessage("%s", ss.str().c_str()); if ( !count || count > entries.size() ) count = entries.size(); if ( sort ) std::partial_sort(entries.begin(), entries.begin() + count, entries.end(), sort); for ( unsigned i = 0; i < count; ++i ) print_single_entry(entries[i], i + 1); } } void show_rule_profiler_stats(const RuleProfilerConfig& config) { if ( !config.show ) return; auto entries = rule_stats::build_entries(); // if there aren't any eval'd rules, don't sort or print if ( entries.empty() ) return; auto sort = rule_stats::sorters[config.sort]; // FIXIT-L J do we eventually want to be able print rule totals, too? print_entries(entries, sort, config.count); } void reset_rule_profiler_stats() { assert(snort_conf); auto* otn_map = snort_conf->otn_map; for ( auto* h = sfghash_findfirst(otn_map); h; h = sfghash_findnext(otn_map) ) { auto* otn = static_cast<OptTreeNode*>(h->data); assert(otn); auto* rtn = getRtnFromOtn(otn); if ( !rtn || !is_network_protocol(rtn->proto) ) continue; for ( unsigned i = 0; i < ThreadConfig::get_instance_max(); ++i ) { auto& state = otn->state[i]; state = OtnState(); } } } void RuleContext::stop(bool match) { if ( finished ) return; finished = true; stats.update(sw.get(), match); } #ifdef UNIT_TEST namespace { using RuleEntryVector = std::vector<rule_stats::View>; using RuleStatsVector = std::vector<OtnState>; } // anonymous namespace static inline bool operator==(const RuleEntryVector& lhs, const RuleStatsVector& rhs) { if ( lhs.size() != rhs.size() ) return false; for ( unsigned i = 0; i < lhs.size(); ++i ) if ( lhs[i].state != rhs[i] ) return false; return true; } static inline OtnState make_otn_state( hr_duration elapsed, hr_duration elapsed_match, uint64_t checks, uint64_t matches) { OtnState state; state.elapsed = elapsed; state.elapsed_match = elapsed_match; state.checks = checks; state.matches = matches; return state; } static inline rule_stats::View make_rule_entry( hr_duration elapsed, hr_duration elapsed_match, uint64_t checks, uint64_t matches) { return { make_otn_state(elapsed, elapsed_match, checks, matches), nullptr }; } static void avoid_optimization() { for ( int i = 0; i < 1024; ++i ); } TEST_CASE( "otn state", "[profiler][rule_profiler]" ) { OtnState state_a; state_a.elapsed = 1_ticks; state_a.elapsed_match = 2_ticks; state_a.elapsed_no_match = 2_ticks; state_a.checks = 1; state_a.matches = 2; state_a.noalerts = 3; state_a.alerts = 4; SECTION( "incremental addition" ) { OtnState state_b; state_b.elapsed = 4_ticks; state_b.elapsed_match = 5_ticks; state_b.elapsed_no_match = 6_ticks; state_b.checks = 5; state_b.matches = 6; state_b.noalerts = 7; state_b.alerts = 8; state_a += state_b; CHECK( state_a.elapsed == 5_ticks ); CHECK( state_a.elapsed_match == 7_ticks ); CHECK( state_a.checks == 6 ); CHECK( state_a.matches == 8 ); CHECK( state_a.alerts == 12 ); } SECTION( "reset" ) { state_a = OtnState(); CHECK( state_a.elapsed == 0_ticks ); CHECK( state_a.elapsed_match == 0_ticks ); CHECK( state_a.checks == 0 ); CHECK( state_a.matches == 0 ); CHECK( state_a.alerts == 0 ); } SECTION( "bool()" ) { CHECK( state_a ); OtnState state_c = OtnState(); CHECK_FALSE( state_c ); state_c.elapsed = 1_ticks; CHECK( state_c ); state_c.elapsed = 0_ticks; state_c.checks = 1; CHECK( state_c ); } } TEST_CASE( "rule entry", "[profiler][rule_profiler]" ) { SigInfo sig_info; auto entry = make_rule_entry(3_ticks, 2_ticks, 3, 2); entry.state.alerts = 77; entry.state.latency_timeouts = 5; entry.state.latency_suspends = 2; SECTION( "copy assignment" ) { auto copy = entry; CHECK( copy.sig_info.generator == entry.sig_info.generator ); CHECK( copy.sig_info.id == entry.sig_info.id ); CHECK( copy.sig_info.rev == entry.sig_info.rev ); CHECK( copy.state == entry.state ); } SECTION( "copy construction" ) { rule_stats::View copy(entry); CHECK( copy.sig_info.generator == entry.sig_info.generator ); CHECK( copy.sig_info.id == entry.sig_info.id ); CHECK( copy.sig_info.rev == entry.sig_info.rev ); CHECK( copy.state == entry.state ); } SECTION( "elapsed" ) { CHECK( entry.elapsed() == 3_ticks ); } SECTION( "elapsed_match" ) { CHECK( entry.elapsed_match() == 2_ticks ); } SECTION( "elapsed_no_match" ) { CHECK( entry.elapsed_no_match() == 1_ticks ); } SECTION( "checks" ) { CHECK( entry.checks() == 3 ); } SECTION( "matches" ) { CHECK( entry.matches() == 2 ); } SECTION( "no_matches" ) { CHECK( entry.no_matches() == 1 ); } SECTION( "alerts" ) { CHECK( entry.alerts() == 77 ); } SECTION( "timeouts" ) { CHECK( entry.timeouts() == 5 ); } SECTION( "suspends" ) { CHECK( entry.suspends() == 2 ); } SECTION( "avg_match" ) { auto ticks = entry.avg_match(); INFO( ticks.count() << " == " << (1_ticks).count() ); CHECK( ticks == 1_ticks ); } SECTION( "avg_no_match" ) { auto ticks = entry.avg_no_match(); INFO( ticks.count() << " == " << (1_ticks).count() ); CHECK( ticks == 1_ticks ); } SECTION( "avg_check" ) { auto ticks = entry.avg_check(); INFO( ticks.count() << " == " << (1_ticks).count() ); CHECK( ticks == 1_ticks ); } } TEST_CASE( "rule profiler sorting", "[profiler][rule_profiler]" ) { using Sort = RuleProfilerConfig::Sort; SECTION( "checks" ) { RuleEntryVector entries { make_rule_entry(0_ticks, 0_ticks, 0, 0), make_rule_entry(0_ticks, 0_ticks, 1, 0), make_rule_entry(0_ticks, 0_ticks, 2, 0) }; RuleStatsVector expected { make_otn_state(0_ticks, 0_ticks, 2, 0), make_otn_state(0_ticks, 0_ticks, 1, 0), make_otn_state(0_ticks, 0_ticks, 0, 0) }; const auto& sorter = rule_stats::sorters[Sort::SORT_CHECKS]; std::partial_sort(entries.begin(), entries.end(), entries.end(), sorter); CHECK( entries == expected ); } SECTION( "avg_check" ) { RuleEntryVector entries { make_rule_entry(2_ticks, 0_ticks, 2, 0), make_rule_entry(8_ticks, 0_ticks, 4, 0), make_rule_entry(4_ticks, 0_ticks, 1, 0) }; RuleStatsVector expected { make_otn_state(4_ticks, 0_ticks, 1, 0), make_otn_state(8_ticks, 0_ticks, 4, 0), make_otn_state(2_ticks, 0_ticks, 2, 0) }; const auto& sorter = rule_stats::sorters[Sort::SORT_AVG_CHECK]; std::partial_sort(entries.begin(), entries.end(), entries.end(), sorter); CHECK( entries == expected ); } SECTION( "total_time" ) { RuleEntryVector entries { make_rule_entry(0_ticks, 0_ticks, 0, 0), make_rule_entry(1_ticks, 0_ticks, 0, 0), make_rule_entry(2_ticks, 0_ticks, 0, 0) }; RuleStatsVector expected { make_otn_state(2_ticks, 0_ticks, 0, 0), make_otn_state(1_ticks, 0_ticks, 0, 0), make_otn_state(0_ticks, 0_ticks, 0, 0) }; const auto& sorter = rule_stats::sorters[Sort::SORT_TOTAL_TIME]; std::partial_sort(entries.begin(), entries.end(), entries.end(), sorter); CHECK( entries == expected ); } SECTION( "matches" ) { RuleEntryVector entries { make_rule_entry(0_ticks, 0_ticks, 0, 0), make_rule_entry(0_ticks, 0_ticks, 0, 1), make_rule_entry(0_ticks, 0_ticks, 0, 2) }; RuleStatsVector expected { make_otn_state(0_ticks, 0_ticks, 0, 2), make_otn_state(0_ticks, 0_ticks, 0, 1), make_otn_state(0_ticks, 0_ticks, 0, 0) }; const auto& sorter = rule_stats::sorters[Sort::SORT_MATCHES]; std::partial_sort(entries.begin(), entries.end(), entries.end(), sorter); CHECK( entries == expected ); } SECTION( "no matches" ) { RuleEntryVector entries { make_rule_entry(0_ticks, 0_ticks, 4, 3), make_rule_entry(0_ticks, 0_ticks, 3, 1), make_rule_entry(0_ticks, 0_ticks, 4, 1) }; RuleStatsVector expected { make_otn_state(0_ticks, 0_ticks, 4, 1), make_otn_state(0_ticks, 0_ticks, 3, 1), make_otn_state(0_ticks, 0_ticks, 4, 3) }; const auto& sorter = rule_stats::sorters[Sort::SORT_NO_MATCHES]; std::partial_sort(entries.begin(), entries.end(), entries.end(), sorter); CHECK( entries == expected ); } SECTION( "avg match" ) { RuleEntryVector entries { make_rule_entry(4_ticks, 0_ticks, 0, 2), make_rule_entry(6_ticks, 0_ticks, 0, 2), make_rule_entry(8_ticks, 0_ticks, 0, 2) }; RuleStatsVector expected { make_otn_state(8_ticks, 0_ticks, 0, 2), make_otn_state(6_ticks, 0_ticks, 0, 2), make_otn_state(4_ticks, 0_ticks, 0, 2) }; const auto& sorter = rule_stats::sorters[Sort::SORT_AVG_MATCH]; std::partial_sort(entries.begin(), entries.end(), entries.end(), sorter); CHECK( entries == expected ); } SECTION( "avg no match" ) { RuleEntryVector entries { make_rule_entry(4_ticks, 0_ticks, 6, 2), make_rule_entry(6_ticks, 0_ticks, 5, 2), make_rule_entry(8_ticks, 0_ticks, 2, 0) }; RuleStatsVector expected { make_otn_state(8_ticks, 0_ticks, 2, 0), make_otn_state(6_ticks, 0_ticks, 5, 2), make_otn_state(4_ticks, 0_ticks, 6, 2) }; const auto& sorter = rule_stats::sorters[Sort::SORT_AVG_NO_MATCH]; std::partial_sort(entries.begin(), entries.end(), entries.end(), sorter); CHECK( entries == expected ); } } TEST_CASE( "rule profiler time context", "[profiler][rule_profiler]" ) { dot_node_state_t stats; stats.elapsed = 0_ticks; stats.checks = 0; stats.elapsed_match = 0_ticks; SECTION( "automatically updates stats" ) { { RuleContext ctx(stats); avoid_optimization(); } INFO( "elapsed: " << stats.elapsed.count() ); CHECK( stats.elapsed > 0_ticks ); CHECK( stats.checks == 1 ); INFO( "elapsed_match: " << stats.elapsed_match.count() ); CHECK( stats.elapsed_match == 0_ticks ); } SECTION( "explicitly calling stop" ) { dot_node_state_t save; SECTION( "stop(true)" ) { { RuleContext ctx(stats); avoid_optimization(); ctx.stop(true); INFO( "elapsed: " << stats.elapsed.count() ); CHECK( stats.elapsed > 0_ticks ); CHECK( stats.checks == 1 ); CHECK( stats.elapsed_match == stats.elapsed ); save = stats; } } SECTION( "stop(false)" ) { { RuleContext ctx(stats); avoid_optimization(); ctx.stop(false); INFO( "elapsed: " << stats.elapsed.count() ); CHECK( stats.elapsed > 0_ticks ); CHECK( stats.checks == 1 ); CHECK( stats.elapsed_match == 0_ticks ); save = stats; } } INFO( "elapsed: " << stats.elapsed.count() ); CHECK( stats.elapsed == save.elapsed ); CHECK( stats.elapsed_match == save.elapsed_match ); CHECK( stats.checks == save.checks ); } } #endif
Ghorbani-Roozbahan-Gholipoor-Dashti/Snort
src/profiler/rule_profiler.cc
C++
gpl-2.0
19,967
// Copyright (C) 2015 Dave Griffiths // // 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. // messy scheme interface #include <unistd.h> #include <sys/time.h> #include <time.h> #include "scheme.h" #include "scheme-private.h" ///// starwisp stuff ////////////////////////// #ifdef ANDROID_NDK #include <android/log.h> #endif #include "engine/engine.h" #include "engine/shader.h" #include "core/geometry.h" #include "core/osc.h" #include "fluxa/graph.h" #include "fluxa/time.h" #include "audio.h" graph *m_audio_graph = NULL; audio_device *m_audio_device = NULL; char *starwisp_data = NULL; #ifdef USE_SQLITE #include "core/db_container.h" db_container the_db_container; #include "core/idmap.h" idmap the_idmap; #endif pointer scheme_interface(scheme *sc, enum scheme_opcodes op) { switch (op) { ///////////// FLUXUS case OP_ALOG: #ifdef ANDROID_NDK __android_log_print(ANDROID_LOG_INFO, "starwisp", string_value(car(sc->args))); #endif s_return(sc,sc->F); case OP_SEND: if (is_string(car(sc->args))) { if (starwisp_data!=NULL) { #ifdef ANDROID_NDK __android_log_print(ANDROID_LOG_INFO, "starwisp", "deleting starwisp data: something is wrong!"); #endif free(starwisp_data); } starwisp_data=strdup(string_value(car(sc->args))); } s_return(sc,sc->F); case OP_OPEN_DB: { #ifdef USE_SQLITE if (is_string(car(sc->args))) { the_db_container.add(string_value(car(sc->args)), new db(string_value(car(sc->args)))); s_return(sc,sc->T); } #endif s_return(sc,sc->F); } case OP_EXEC_DB: { #ifdef USE_SQLITE if (is_string(car(sc->args)) && is_string(cadr(sc->args))) { db *d=the_db_container.get(string_value(car(sc->args))); if (d!=NULL) { s_return(sc,db_exec(sc,d)); } } #endif s_return(sc,sc->F); } case OP_INSERT_DB: { #ifdef USE_SQLITE if (is_string(car(sc->args)) && is_string(cadr(sc->args))) { db *d=the_db_container.get(string_value(car(sc->args))); if (d!=NULL) { db_exec(sc,d); s_return(sc,mk_integer(sc,d->last_rowid())); } } #endif s_return(sc,sc->F); } /* case OP_INSERT_BLOB_DB: { #ifndef FLX_RPI if (is_string(car(sc->args)) && is_string(caddr(sc->args)) && is_string(cadddr(sc->args)) && is_string(caddddr(sc->args)) && is_string(cadddddr(sc->args))) { db *d=the_db_container.get(string_value(car(sc->args))); if (d!=NULL) { db_exec(sc,d); s_return(sc,mk_integer(sc,d->last_rowid())); } } #endif s_return(sc,sc->F); } */ case OP_STATUS_DB: { #ifdef USE_SQLITE if (is_string(car(sc->args))) { s_return(sc,mk_string(sc,the_db_container.status())); } #endif s_return(sc,sc->F); } case OP_TIME: { timeval t; // stop valgrind complaining t.tv_sec=0; t.tv_usec=0; gettimeofday(&t,NULL); s_return(sc,cons(sc,mk_integer(sc,t.tv_sec), cons(sc,mk_integer(sc,t.tv_usec),sc->NIL))); } case OP_NTP_TIME: { spiralcore::time t; t.set_to_now(); s_return(sc,cons(sc,mk_integer(sc,t.seconds), cons(sc,mk_integer(sc,t.fraction),sc->NIL))); } case OP_NTP_TIME_ADD: { spiralcore::time t(ivalue(car(car(sc->args))), ivalue(cadr(car(sc->args)))); t+=rvalue(cadr(sc->args)); s_return(sc,cons(sc,mk_integer(sc,t.seconds), cons(sc,mk_integer(sc,t.fraction),sc->NIL))); } case OP_NTP_TIME_DIFF: { spiralcore::time t(ivalue(car(car(sc->args))), ivalue(cadr(car(sc->args)))); spiralcore::time t2(ivalue(car(cadr(sc->args))), ivalue(cadr(cadr(sc->args)))); s_return(sc,mk_real(sc,t.get_difference(t2))); } case OP_NTP_TIME_GTR: { spiralcore::time t(ivalue(car(car(sc->args))), ivalue(cadr(car(sc->args)))); spiralcore::time t2(ivalue(car(cadr(sc->args))), ivalue(cadr(cadr(sc->args)))); if (t>t2) s_return(sc,sc->T); else s_return(sc,sc->F); } case OP_DATETIME: { timeval t; // stop valgrind complaining t.tv_sec=0; t.tv_usec=0; gettimeofday(&t,NULL); struct tm *now = gmtime((time_t *)&t.tv_sec); /* note: now->tm_year is the number of years SINCE 1900. On the year 2000, this will be 100 not 0. Do a man gmtime for more information */ s_return(sc,cons(sc,mk_integer(sc,now->tm_year + 1900), cons(sc,mk_integer(sc,now->tm_mon + 1), cons(sc,mk_integer(sc,now->tm_mday), cons(sc,mk_integer(sc,now->tm_hour), cons(sc,mk_integer(sc,now->tm_min), cons(sc,mk_integer(sc,now->tm_sec), sc->NIL))))))); } #ifdef USE_SQLITE case OP_ID_MAP_ADD: { the_idmap.add( string_value(car(sc->args)), ivalue(cadr(sc->args))); s_return(sc,sc->F); } case OP_ID_MAP_GET: { s_return( sc,mk_integer(sc,the_idmap.get( string_value(car(sc->args))))); } #endif //////////////////// fluxa ///////////////////////////////////////// case OP_SYNTH_INIT: { // name,buf,sr,synths m_audio_device = new audio_device(string_value(car(sc->args)), ivalue(cadr(sc->args)), ivalue(caddr(sc->args)), ivalue(cadddr(sc->args))); m_audio_graph = new graph(ivalue(caddddr(sc->args)),ivalue(caddr(sc->args))); m_audio_device->start_graph(m_audio_graph); s_return(sc,sc->F); } break; case OP_AUDIO_CHECK: { m_audio_device->check_audio(); s_return(sc,sc->F); } break; case OP_SYNTH_RECORD: { m_audio_device->start_recording(string_value(car(sc->args))); s_return(sc,sc->F); } break; case OP_AUDIO_EQ: { m_audio_device->m_left_eq.set_low(rvalue(car(sc->args))); m_audio_device->m_right_eq.set_low(rvalue(car(sc->args))); m_audio_device->m_left_eq.set_mid(rvalue(cadr(sc->args))); m_audio_device->m_right_eq.set_mid(rvalue(cadr(sc->args))); m_audio_device->m_left_eq.set_high(rvalue(caddr(sc->args))); m_audio_device->m_right_eq.set_high(rvalue(caddr(sc->args))); s_return(sc,sc->F); } break; case OP_AUDIO_COMP: { m_audio_device->m_left_comp.set_attack(rvalue(car(sc->args))); m_audio_device->m_right_comp.set_attack(rvalue(car(sc->args))); m_audio_device->m_left_comp.set_release(rvalue(cadr(sc->args))); m_audio_device->m_right_comp.set_release(rvalue(cadr(sc->args))); m_audio_device->m_left_comp.set_threshold(rvalue(caddr(sc->args))); m_audio_device->m_right_comp.set_threshold(rvalue(caddr(sc->args))); m_audio_device->m_left_comp.set_slope(rvalue(cadddr(sc->args))); m_audio_device->m_right_comp.set_slope(rvalue(cadddr(sc->args))); s_return(sc,sc->F); } break; case OP_SYNTH_CRT: { m_audio_graph ->create(ivalue(car(sc->args)), (graph::node_type)(ivalue(cadr(sc->args))), rvalue(caddr(sc->args))); s_return(sc,sc->F); } break; case OP_SYNTH_CON: { m_audio_graph ->connect(ivalue(car(sc->args)), ivalue(cadr(sc->args)), ivalue(caddr(sc->args))); s_return(sc,sc->F); } break; case OP_SYNTH_PLY: { m_audio_graph ->play(ivalue(car(sc->args)), ivalue(cadr(sc->args)), ivalue(caddr(sc->args)), rvalue(cadddr(sc->args))); s_return(sc,sc->F); } break; case OP_SLEEP: { usleep(ivalue(car(sc->args))); s_return(sc,sc->F); } break; case OP_FMOD: { s_return(sc,mk_real(sc,fmod(rvalue(car(sc->args)),rvalue(cadr(sc->args))))); } break; case OP_OSC_SEND: { const char *url=string_value(car(sc->args)); const char *name=string_value(cadr(sc->args)); const char *types=string_value(caddr(sc->args)); pointer data=cadddr(sc->args); // figure out size of the data packet u32 data_size=0; for (u32 i=0; i<strlen(types); ++i) { switch(types[i]) { case 'f': data_size+=sizeof(float); break; case 'i': data_size+=sizeof(int); break; case 'l': data_size+=sizeof(long long); break; case 's': data_size+=strlen(string_value(list_ref(sc,data,i)))+1; break; } } // build data packet char *packet = new char[data_size]; u32 data_pos=0; for (u32 i=0; i<strlen(types); ++i) { switch(types[i]) { case 'f': { float v=rvalue(list_ref(sc,data,i)); memcpy(packet+data_pos,&v,sizeof(float)); data_pos+=sizeof(float); } break; case 'i': { int v=ivalue(list_ref(sc,data,i)); memcpy(packet+data_pos,&v,sizeof(int)); data_pos+=sizeof(int); } break; case 'l': /*float v=ivalue(list_ref(sc,data,i)); memcpy(packet+data_pos,&v,sizeof(float)); data_pos+=sizeof(long long); */ break; case 's': { char *str=string_value(list_ref(sc,data,i)); memcpy(packet+data_pos,str,strlen(str)); data_pos+=strlen(string_value(list_ref(sc,data,i))); packet[data_pos]=0; // null terminator data_pos++; } break; } } network_osc::send(url,name,types,packet,data_size); delete[] packet; s_return(sc,sc->F); } break; //////////////////// fluxus ///////////////////////////////////////// case OP_PUSH: engine::get()->push(); s_return(sc,sc->F); case OP_POP: engine::get()->pop(); s_return(sc,sc->F); case OP_GRAB: engine::get()->grab(ivalue(car(sc->args))); s_return(sc,sc->F); case OP_UNGRAB: engine::get()->ungrab(); s_return(sc,sc->F); case OP_PARENT: engine::get()->parent(ivalue(car(sc->args))); s_return(sc,sc->F); case OP_LOCK_CAMERA: engine::get()->lock_camera(ivalue(car(sc->args))); s_return(sc,sc->F); case OP_IDENTITY: engine::get()->identity(); s_return(sc,sc->F); case OP_TRANSLATE: engine::get()->translate(rvalue(vector_elem(car(sc->args),0)), rvalue(vector_elem(car(sc->args),1)), rvalue(vector_elem(car(sc->args),2))); s_return(sc,sc->F); case OP_SCALE: if (!is_vector(car(sc->args))) // uniform scale with one arg { engine::get()->scale(rvalue(car(sc->args)), rvalue(car(sc->args)), rvalue(car(sc->args))); } else { engine::get()->scale(rvalue(vector_elem(car(sc->args),0)), rvalue(vector_elem(car(sc->args),1)), rvalue(vector_elem(car(sc->args),2))); } s_return(sc,sc->F); case OP_ROTATE: engine::get()->rotate(rvalue(vector_elem(car(sc->args),0)), rvalue(vector_elem(car(sc->args),1)), rvalue(vector_elem(car(sc->args),2))); s_return(sc,sc->F); case OP_AIM: engine::get()->aim(rvalue(vector_elem(car(sc->args),0)), rvalue(vector_elem(car(sc->args),1)), rvalue(vector_elem(car(sc->args),2)), rvalue(vector_elem(cadr(sc->args),0)), rvalue(vector_elem(cadr(sc->args),1)), rvalue(vector_elem(cadr(sc->args),2))); s_return(sc,sc->F); case OP_CONCAT: { mat44 t = mat44(rvalue(vector_elem(car(sc->args),0)), rvalue(vector_elem(car(sc->args),1)), rvalue(vector_elem(car(sc->args),2)), rvalue(vector_elem(car(sc->args),3)), rvalue(vector_elem(car(sc->args),4)), rvalue(vector_elem(car(sc->args),5)), rvalue(vector_elem(car(sc->args),6)), rvalue(vector_elem(car(sc->args),7)), rvalue(vector_elem(car(sc->args),8)), rvalue(vector_elem(car(sc->args),9)), rvalue(vector_elem(car(sc->args),10)), rvalue(vector_elem(car(sc->args),11)), rvalue(vector_elem(car(sc->args),12)), rvalue(vector_elem(car(sc->args),13)), rvalue(vector_elem(car(sc->args),14)), rvalue(vector_elem(car(sc->args),15))); t.transpose(); engine::get()->concat(t); s_return(sc,sc->F); } case OP_COLOUR: engine::get()->colour(rvalue(vector_elem(car(sc->args),0)), rvalue(vector_elem(car(sc->args),1)), rvalue(vector_elem(car(sc->args),2)), rvalue(vector_elem(car(sc->args),3))); s_return(sc,sc->F); case OP_HINT: { u32 h=ivalue(car(sc->args)); switch (h) { case 0: engine::get()->hint(HINT_NONE); break; //??? case 1: engine::get()->hint(HINT_SOLID); break; case 2: engine::get()->hint(HINT_WIRE); break; case 3: engine::get()->hint(HINT_NORMAL); break; case 4: engine::get()->hint(HINT_POINTS); break; case 5: engine::get()->hint(HINT_AALIAS); break; case 6: engine::get()->hint(HINT_BOUND); break; case 7: engine::get()->hint(HINT_UNLIT); break; case 8: engine::get()->hint(HINT_VERTCOLS); break; case 9: engine::get()->hint(HINT_ORIGIN); break; case 10: engine::get()->hint(HINT_CAST_SHADOW); break; case 11: engine::get()->hint(HINT_IGNORE_DEPTH); break; case 12: engine::get()->hint(HINT_DEPTH_SORT); break; case 13: engine::get()->hint(HINT_LAZY_PARENT); break; case 14: engine::get()->hint(HINT_CULL_CCW); break; case 15: engine::get()->hint(HINT_WIRE_STIPPLED); break; case 16: engine::get()->hint(HINT_SPHERE_MAP); break; case 17: engine::get()->hint(HINT_FRUSTUM_CULL); break; case 18: engine::get()->hint(HINT_NORMALISE); break; case 19: engine::get()->hint(HINT_NOBLEND); break; case 20: engine::get()->hint(HINT_NOZWRITE); break; } s_return(sc,sc->F); } case OP_DESTROY: engine::get()->destroy(rvalue(car(sc->args))); s_return(sc,sc->F); case OP_LINE_WIDTH: engine::get()->line_width(rvalue(car(sc->args))); s_return(sc,sc->F); case OP_TEXTURE: engine::get()->texture(rvalue(car(sc->args))); s_return(sc,sc->F); case OP_SHADER: engine::get()->set_shader(string_value(car(sc->args)), string_value(cadr(sc->args))); s_return(sc,sc->F); case OP_SHADER_SET: { shader *shader = engine::get()->get_current_shader(); shader->apply(); char *name = string_value(car(sc->args)); pointer arg=cadr(sc->args); if (is_vector(arg)) { switch (ivalue(arg)) { case 3: { vec3 vec(rvalue(vector_elem(arg,0)), rvalue(vector_elem(arg,1)), rvalue(vector_elem(arg,2))); shader->set_vector(name,vec); } break; case 16: { mat44 mat(rvalue(vector_elem(arg,0)), rvalue(vector_elem(arg,1)), rvalue(vector_elem(arg,2)), rvalue(vector_elem(arg,3)), rvalue(vector_elem(arg,4)), rvalue(vector_elem(arg,5)), rvalue(vector_elem(arg,6)), rvalue(vector_elem(arg,7)), rvalue(vector_elem(arg,8)), rvalue(vector_elem(arg,9)), rvalue(vector_elem(arg,10)), rvalue(vector_elem(arg,11)), rvalue(vector_elem(arg,12)), rvalue(vector_elem(arg,13)), rvalue(vector_elem(arg,14)), rvalue(vector_elem(arg,15))); shader->set_matrix(name,mat); } break; } } else { if (is_number(arg)) { if (num_is_integer(arg)) { shader->set_int(name,ivalue(arg)); } else { shader->set_float(name,rvalue(arg)); } } } shader->unapply(); s_return(sc,sc->F); } case OP_LOAD_TEXTURE: s_return(sc,mk_integer(sc,engine::get()->get_texture(string_value(car(sc->args))))); case OP_DRAW_INSTANCE: engine::get()->draw_instance(ivalue(car(sc->args))); s_return(sc,sc->F); case OP_BUILD_CUBE: s_return(sc,mk_integer(sc,engine::get()->build_cube())); case OP_LOAD_OBJ: s_return(sc,mk_integer(sc,engine::get()->load_obj(string_value(car(sc->args))))); case OP_RAW_OBJ: s_return(sc,mk_integer(sc,engine::get()->raw_obj(string_value(car(sc->args))))); case OP_BUILD_TEXT: s_return(sc,mk_integer(sc,engine::get()->build_text( string_value(car(sc->args))))); case OP_BUILD_JELLYFISH: s_return(sc,mk_integer(sc,engine::get()->build_jellyfish(ivalue(car(sc->args))))); case OP_BUILD_INSTANCE: s_return(sc,mk_integer(sc,engine::get()->build_instance(ivalue(car(sc->args))))); case OP_BUILD_POLYGONS: s_return(sc,mk_integer(sc,engine::get()->build_polygons( ivalue(car(sc->args)), ivalue(cadr(sc->args)) ))); case OP_GET_TRANSFORM: { flx_real *m=&(engine::get()->get_transform()->m[0][0]); pointer v=mk_vector(sc,16); int i=0; for (i=0; i<16; i++) { set_vector_elem(v,i,mk_real(sc,m[i])); } s_return(sc,v); } case OP_GET_GLOBAL_TRANSFORM: { mat44 mat=engine::get()->get_global_transform(); flx_real *m=&(mat.m[0][0]); pointer v=mk_vector(sc,16); int i=0; for (i=0; i<16; i++) { set_vector_elem(v,i,mk_real(sc,m[i])); } s_return(sc,v); } case OP_GET_CAMERA_TRANSFORM: { flx_real *m=&(engine::get()->get_camera_transform()->m[0][0]); pointer v=mk_vector(sc,16); int i=0; for (i=0; i<16; i++) { set_vector_elem(v,i,mk_real(sc,m[i])); } s_return(sc,v); } case OP_GET_SCREEN_SIZE: { unsigned int *s=engine::get()->get_screensize(); pointer v=mk_vector(sc,2); set_vector_elem(v,0,mk_real(sc,s[0])); set_vector_elem(v,1,mk_real(sc,s[1])); s_return(sc,v); } case OP_APPLY_TRANSFORM: engine::get()->apply_transform(); s_return(sc,sc->F); case OP_CLEAR: engine::get()->clear(); s_return(sc,sc->F); case OP_CLEAR_COLOUR: engine::get()->clear_colour(rvalue(vector_elem(car(sc->args),0)), rvalue(vector_elem(car(sc->args),1)), rvalue(vector_elem(car(sc->args),2)), rvalue(vector_elem(car(sc->args),3))); s_return(sc,sc->F); case OP_PDATA_SIZE: s_return(sc,mk_integer(sc,engine::get()->pdata_size())); case OP_PDATA_ADD: engine::get()->pdata_add(string_value(car(sc->args))); s_return(sc,sc->F); case OP_PDATA_REF: { vec3* vec=engine::get()->pdata_get(string_value(car(sc->args)), ivalue(cadr(sc->args))); pointer v=mk_vector(sc,3); if (vec) { set_vector_elem(v,0,mk_real(sc,vec->x)); set_vector_elem(v,1,mk_real(sc,vec->y)); set_vector_elem(v,2,mk_real(sc,vec->z)); } s_return(sc,v); } case OP_PDATA_SET: { vec3 vec(rvalue(vector_elem(caddr(sc->args),0)), rvalue(vector_elem(caddr(sc->args),1)), rvalue(vector_elem(caddr(sc->args),2))); engine::get()->pdata_set(string_value(car(sc->args)), ivalue(cadr(sc->args)), vec); s_return(sc,sc->F); } case OP_SET_TEXT: { engine::get()->text_set(string_value(car(sc->args))); s_return(sc,sc->F); } case OP_TEXT_PARAMS: { engine::get()->text_params(string_value(list_ref(sc,sc->args,0)), rvalue(list_ref(sc,sc->args,1)), rvalue(list_ref(sc,sc->args,2)), ivalue(list_ref(sc,sc->args,3)), ivalue(list_ref(sc,sc->args,4)), rvalue(list_ref(sc,sc->args,5)), rvalue(list_ref(sc,sc->args,6)), rvalue(list_ref(sc,sc->args,7)), rvalue(list_ref(sc,sc->args,8)), rvalue(list_ref(sc,sc->args,9)), rvalue(list_ref(sc,sc->args,10))); s_return(sc,sc->F); } case OP_RECALC_BB: { engine::get()->recalc_bb(); s_return(sc,sc->F); } case OP_BB_POINT_INTERSECT: { vec3 pvec(rvalue(vector_elem(car(sc->args),0)), rvalue(vector_elem(car(sc->args),1)), rvalue(vector_elem(car(sc->args),2))); s_return(sc,mk_integer(sc,engine::get()->bb_point_intersect(pvec,rvalue(cadr(sc->args))))); } case OP_GEO_LINE_INTERSECT: { vec3 svec(rvalue(vector_elem(car(sc->args),0)), rvalue(vector_elem(car(sc->args),1)), rvalue(vector_elem(car(sc->args),2))); vec3 evec(rvalue(vector_elem(cadr(sc->args),0)), rvalue(vector_elem(cadr(sc->args),1)), rvalue(vector_elem(cadr(sc->args),2))); bb::list *points=engine::get()->geo_line_intersect(svec,evec); if (points!=NULL) { pointer list=sc->NIL; intersect_point *p=static_cast<intersect_point*>(points->m_head); while (p!=NULL) { list=cons(sc,mk_real(sc,p->m_t),list); pointer blend=sc->NIL; intersect_point::blend *b= static_cast<intersect_point::blend*> (p->m_blends.m_head); while (b!=NULL) { pointer v=mk_vector(sc,3); set_vector_elem(v,0,mk_real(sc,b->m_blend.x)); set_vector_elem(v,1,mk_real(sc,b->m_blend.y)); set_vector_elem(v,2,mk_real(sc,b->m_blend.z)); pointer l=sc->NIL; l=cons(sc,mk_string(sc,b->m_name),v); blend=cons(sc,l,blend); b=static_cast<intersect_point::blend*>(b->m_next); } list=cons(sc,blend,list); p=static_cast<intersect_point*>(p->m_next); } s_return(sc,list); } s_return(sc,sc->F); } case OP_GET_LINE_INTERSECT: { vec3 svec(rvalue(vector_elem(car(sc->args),0)), rvalue(vector_elem(car(sc->args),1)), rvalue(vector_elem(car(sc->args),2))); vec3 evec(rvalue(vector_elem(cadr(sc->args),0)), rvalue(vector_elem(cadr(sc->args),1)), rvalue(vector_elem(cadr(sc->args),2))); s_return(sc,mk_integer(sc,engine::get()->get_line_intersect(svec,evec))); } case OP_MINVERSE: { mat44 inm; int i=0; for (i=0; i<16; i++) { inm.arr()[i]=rvalue(vector_elem(car(sc->args),i)); } inm=inm.inverse(); pointer v=mk_vector(sc,16); for (i=0; i<16; i++) { set_vector_elem(v,i,mk_real(sc,inm.arr()[i])); } s_return(sc,v); } case OP_BITWISE_IOR: { s_return(sc,mk_integer(sc, ivalue(car(sc->args))| ivalue(cadr(sc->args))| ivalue(caddr(sc->args)) )); } case OP_BLEND_MODE: { u32 src = GL_SRC_ALPHA; u32 dst = GL_ONE_MINUS_SRC_ALPHA; u32 s = ivalue(car(sc->args)); u32 d = ivalue(cadr(sc->args)); if (s==0) src=GL_ZERO; else if (s==1) src=GL_ONE; else if (s==2) src=GL_DST_COLOR; else if (s==3) src=GL_ONE_MINUS_DST_COLOR; else if (s==4) src=GL_SRC_ALPHA; else if (s==5) src=GL_ONE_MINUS_SRC_ALPHA; else if (s==6) src=GL_DST_ALPHA; else if (s==7) src=GL_ONE_MINUS_DST_ALPHA; else if (s==8) src=GL_SRC_ALPHA_SATURATE; if (d==0) dst=GL_ZERO; else if (d==1) dst=GL_ONE; else if (d==9) dst=GL_SRC_COLOR; else if (d==10) dst=GL_ONE_MINUS_SRC_COLOR; else if (d==4) dst=GL_SRC_ALPHA; else if (d==5) dst=GL_ONE_MINUS_SRC_ALPHA; else if (d==6) dst=GL_DST_ALPHA; else if (d==7) dst=GL_ONE_MINUS_DST_ALPHA; engine::get()->blend_mode(src,dst); s_return(sc,sc->F); } default: snprintf(sc->strbuff,STRBUFFSIZE,"%d: illegal operator", sc->op); Error_0(sc,sc->strbuff); } //////////////////// }
nebogeo/jellyfish
src/scheme/interface.cpp
C++
gpl-2.0
22,783
/* * Copyright 2008-2009 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ #include "jni.h" #include "jni_util.h" #include "jvm.h" #include "jlong.h" #include <dlfcn.h> #include <errno.h> #include <sys/acl.h> #include "sun_nio_fs_SolarisNativeDispatcher.h" static void throwUnixException(JNIEnv* env, int errnum) { jobject x = JNU_NewObjectByName(env, "sun/nio/fs/UnixException", "(I)V", errnum); if (x != NULL) { (*env)->Throw(env, x); } } JNIEXPORT void JNICALL Java_sun_nio_fs_SolarisNativeDispatcher_init(JNIEnv *env, jclass clazz) { } JNIEXPORT jint JNICALL Java_sun_nio_fs_SolarisNativeDispatcher_facl(JNIEnv* env, jclass this, jint fd, jint cmd, jint nentries, jlong address) { void* aclbufp = jlong_to_ptr(address); int n = -1; n = facl((int)fd, (int)cmd, (int)nentries, aclbufp); if (n == -1) { throwUnixException(env, errno); } return (jint)n; }
TheTypoMaster/Scaper
openjdk/jdk/src/solaris/native/sun/nio/fs/SolarisNativeDispatcher.c
C
gpl-2.0
2,058
#include "TreeFactory.h" #include "RobotFactory.h" #include "Robot.h" #include "kinematic/Tree.h" #include "kinematic/Enums.h" #include <vector> #include <list> using namespace matrices; using namespace manip_core::enums; using namespace manip_core::enums::robot; namespace factories { const Vector3 unitx(1, 0, 0); const Vector3 unity(0, 1, 0); const Vector3 unitz(0, 0, 1); const Vector3 unit1(sqrt(14.0)/8.0, 1.0/8.0, 7.0/8.0); const Vector3 zero(0,0,0); struct RobotFactoryPimpl{ RobotFactoryPimpl() { // NOTHING } ~RobotFactoryPimpl() { // NOTHING } // TODO Joint that do not move Robot* CreateHuman(const Matrix4& robotBasis) const { Robot* res = new Robot(robotBasis, treeFact_.CreateTree( HumanTorso, Vector3(0.0, 0., 0), 4), manip_core::enums::robot::Human); Tree* rightLeg = treeFact_.CreateTree( RightLeg, Vector3(0.0, -0.2, 0.1), 0); Tree* leftLeg = treeFact_.CreateTree( LeftLeg, Vector3(0.0, 0.2 , 0.1), 1); Tree* rightArm = treeFact_.CreateTree( RightArm, Vector3(0.0, -0.4, 1.3), 2); Tree* leftArm = treeFact_.CreateTree( LeftArm, Vector3(0.0, 0.4, 1.3), 3); //rightArm->SetBoundaryRadius(rightArm->GetBoundaryRadius() * 8 / 10 ); //leftArm->SetBoundaryRadius(leftArm->GetBoundaryRadius() * 8 / 10 ); res->AddTree(rightLeg, matrices::Vector3(0,0,0), 0); res->AddTree(leftLeg, matrices::Vector3(0,0,0), 0); res->AddTree(rightArm, matrices::Vector3(0,0,1.2), 1); res->AddTree(leftArm, matrices::Vector3(0,0,1.2), 1); /*rightLeg->LockTarget(rightLeg->GetTarget()); leftLeg->LockTarget(leftLeg->GetTarget());*/ //rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.6))); //leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4))); return res; } Robot* CreateHumanEscalade(const Matrix4& robotBasis) const { Robot* res = new Robot(robotBasis, treeFact_.CreateTree( HumanTorso, Vector3(0.0, 0., 0), 4), manip_core::enums::robot::HumanEscalade); Tree* rightLeg = treeFact_.CreateTree( RightLegEscalade, Vector3(0.0, -0.2, 0.1), 0); Tree* leftLeg = treeFact_.CreateTree( LeftLegEscalade, Vector3(0.0, 0.2 , 0.1), 1); Tree* rightArm = treeFact_.CreateTree( RightArmEscalade, Vector3(0.0, -0.4, 1.3), 2); Tree* leftArm = treeFact_.CreateTree( LeftArmEscalade, Vector3(0.0, 0.4, 1.3), 3); //rightArm->SetBoundaryRadius(rightArm->GetBoundaryRadius() * 8 / 10 ); //leftArm->SetBoundaryRadius(leftArm->GetBoundaryRadius() * 8 / 10 ); res->AddTree(rightLeg, matrices::Vector3(0,0,0), 0); res->AddTree(leftLeg, matrices::Vector3(0,0,0), 0); res->AddTree(rightArm, matrices::Vector3(0,0,1.2), 1); res->AddTree(leftArm, matrices::Vector3(0,0,1.2), 1); /*rightLeg->LockTarget(rightLeg->GetTarget()); leftLeg->LockTarget(leftLeg->GetTarget());*/ //rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.6))); //leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4))); return res; } Robot* CreateHumanCanap(const Matrix4& robotBasis) const { Robot* res = new Robot(robotBasis, treeFact_.CreateTree( HumanTorso, Vector3(0.0, 0., 0), 4), manip_core::enums::robot::HumanCanap); Tree* rightLeg = treeFact_.CreateTree( RightLegCanap, Vector3(0.0, -0.2, 0.1), 0); Tree* leftLeg = treeFact_.CreateTree( LeftLegCanap, Vector3(0.0, 0.2 , 0.1), 1); Tree* rightArm = treeFact_.CreateTree( RightArmCanap, Vector3(0.0, -0.4, 1.3), 2); Tree* leftArm = treeFact_.CreateTree( LeftArmCanap, Vector3(0.0, 0.4, 1.3), 3); //rightArm->SetBoundaryRadius(rightArm->GetBoundaryRadius() * 8 / 10 ); //leftArm->SetBoundaryRadius(leftArm->GetBoundaryRadius() * 8 / 10 ); res->AddTree(rightLeg, matrices::Vector3(0,0,0), 0); res->AddTree(leftLeg, matrices::Vector3(0,0,0), 0); res->AddTree(rightArm, matrices::Vector3(0,0,1.2), 1); res->AddTree(leftArm, matrices::Vector3(0,0,1.2), 1); /*rightLeg->LockTarget(rightLeg->GetTarget()); leftLeg->LockTarget(leftLeg->GetTarget());*/ //rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.6))); //leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4))); return res; } Robot* CreateHumanCrouch(const Matrix4& robotBasis) const { Robot* res = new Robot(robotBasis, treeFact_.CreateTree( HumanTorsoCrouch, Vector3(0.0, 0., 0), 4), manip_core::enums::robot::Human); Tree* rightLeg = treeFact_.CreateTree( RightLegCrouch, Vector3(0.1, -0.2, 0.), 0); Tree* leftLeg = treeFact_.CreateTree( LeftLegCrouch, Vector3(0.1, 0.2 , 0.), 1); Tree* rightArm = treeFact_.CreateTree( RightArmCrouch, Vector3(1.3, -0.4, 0.), 2); Tree* leftArm = treeFact_.CreateTree( LeftArmCrouch, Vector3(1.3, 0.4, 0.), 3); //rightArm->SetBoundaryRadius(rightArm->GetBoundaryRadius() * 8 / 10 ); //leftArm->SetBoundaryRadius(leftArm->GetBoundaryRadius() * 8 / 10 ); res->AddTree(rightLeg, matrices::Vector3(0,0,0), 0); res->AddTree(leftLeg, matrices::Vector3(0,0,0), 0); res->AddTree(rightArm, matrices::Vector3(1.2,0,0), 1); res->AddTree(leftArm, matrices::Vector3(1.2,0,0), 1); /*rightLeg->LockTarget(rightLeg->GetTarget()); leftLeg->LockTarget(leftLeg->GetTarget());*/ //rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.6))); //leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4))); return res; } Robot* CreateHumanCrouch180(const Matrix4& robotBasis) const { Robot* res = new Robot(robotBasis, treeFact_.CreateTree( HumanTorsoCrouch180, Vector3(0, 0., 0), 4), manip_core::enums::robot::Human); Tree* rightLeg = treeFact_.CreateTree( RightLegCrouch180, Vector3(0.1, -0.2, 0.), 0); Tree* leftLeg = treeFact_.CreateTree( LeftLegCrouch180, Vector3(0.1, 0.2 , 0.), 1); Tree* rightArm = treeFact_.CreateTree( RightArmCrouch180, Vector3(1.3, -0.4, 0.), 2); Tree* leftArm = treeFact_.CreateTree( LeftArmCrouch180, Vector3(1.3, 0.4, 0.), 3); //rightArm->SetBoundaryRadius(rightArm->GetBoundaryRadius() * 8 / 10 ); //leftArm->SetBoundaryRadius(leftArm->GetBoundaryRadius() * 8 / 10 ); res->AddTree(rightLeg, matrices::Vector3(0,0,0), 0); res->AddTree(leftLeg, matrices::Vector3(0,0,0), 0); res->AddTree(rightArm, matrices::Vector3(1.2,0,0), 1); res->AddTree(leftArm, matrices::Vector3(1.2,0,0), 1); /*rightLeg->LockTarget(rightLeg->GetTarget()); leftLeg->LockTarget(leftLeg->GetTarget());*/ //rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.6))); //leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4))); return res; } Robot* CreateHumanWalk(const Matrix4& robotBasis) const { Robot* res = new Robot(robotBasis, treeFact_.CreateTree( HumanTorso, Vector3(0.0, 0., 0), 4), manip_core::enums::robot::HumanWalk); Tree* rightLeg = treeFact_.CreateTree( RightLegWalk, Vector3(0.0, -0.2, 0.1), 0); Tree* leftLeg = treeFact_.CreateTree( LeftLegWalk, Vector3(0.0, 0.2 , 0.1), 1); Tree* rightArm = treeFact_.CreateTree( RightArm, Vector3(0.0, -0.4, 1.3), 2); Tree* leftArm = treeFact_.CreateTree( LeftArm, Vector3(0.0, 0.4, 1.3), 3); res->AddTree(rightLeg, matrices::Vector3(0,0,0), 0); res->AddTree(leftLeg, matrices::Vector3(0,0,0), 0); res->AddTree(rightArm, matrices::Vector3(0,0,1.2), 1); res->AddTree(leftArm, matrices::Vector3(0,0,1.2), 1); /*rightLeg->LockTarget(rightLeg->GetTarget()); leftLeg->LockTarget(leftLeg->GetTarget());*/ //rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.6))); //leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4))); return res; } Robot* CreateHumanEllipse(const Matrix4& robotBasis) const { Robot* res = new Robot(robotBasis, treeFact_.CreateTree( HumanTorso, Vector3(0.0, 0., 0), 1), manip_core::enums::robot::HumanEllipse); //Tree* rightLeg = treeFact_.CreateTree( RightLegWalk, Vector3(0.0, -0.2, 0.1), 0); //Tree* leftLeg = treeFact_.CreateTree( LeftLegWalk, Vector3(0.0, 0.2 , 0.1), 1); Tree* rightArm = treeFact_.CreateTree( RightArmEllipse, Vector3(0.0, -0.4, 1.3), 0); //Tree* leftArm = treeFact_.CreateTree( LeftArm, Vector3(0.0, 0.4, 1.3), 3); /*res->AddTree(rightLeg, matrices::Vector3(0,0,0), 0); res->AddTree(leftLeg, matrices::Vector3(0,0,0), 0);*/ res->AddTree(rightArm, matrices::Vector3(0,0,1.2), 0); //res->AddTree(leftArm, matrices::Vector3(0,0,1.2), 1); /*rightLeg->LockTarget(rightLeg->GetTarget()); leftLeg->LockTarget(leftLeg->GetTarget());*/ //rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.6))); //leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4))); return res; } Robot* CreateQuadruped(const Matrix4& robotBasis) const { // TODO Remove order neccessity to create ids ... Robot* res = new Robot(robotBasis, treeFact_.CreateTree( QuadrupedTorso, Vector3(0.0, 0., 0.0), 4), manip_core::enums::robot::Quadruped); factories::TreeFactory factory; Tree* rightLeg = treeFact_.CreateTree( QuadrupedLegRight, Vector3(-1.2, -0.25, -0.1), 0); Tree* leftLeg = treeFact_.CreateTree( QuadrupedLegLeft, Vector3(-1.2, 0.25 , -0.1), 1); Tree* leftArm = treeFact_.CreateTree( QuadrupedLegLeft, Vector3(0.3, 0.25 , -0.1), 2); Tree* rightArm = treeFact_.CreateTree( QuadrupedLegRight, Vector3(0.3, -0.25, -0.1), 3); res->AddTree(rightLeg, matrices::Vector3(-1.2,0,0), 0); res->AddTree(leftLeg, matrices::Vector3(-1.2,0,0), 0); res->AddTree(leftArm, matrices::Vector3(0.3,0,0), 1); res->AddTree(rightArm, matrices::Vector3(0.3,0,0), 1); /*rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3(-0.3, 0, -1.3))); leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.5, 0, -1.3))); rightArm->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightArm->GetPosition() + Vector3( 0.3, 0, -1.3)));*/ rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.4))); leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4))); rightArm->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightArm->GetPosition() + Vector3( 0.4, 0, -1.4))); leftArm->LockTarget (matrix4TimesVect3(res->ToWorldCoordinates(), leftArm->GetPosition() + Vector3( -0.4, 0, -1.4))); return res; } Robot* CreateQuadrupedDown(const Matrix4& robotBasis) const { // TODO Remove order neccessity to create ids ... Robot* res = new Robot(robotBasis, treeFact_.CreateTree( QuadrupedTorso, Vector3(0.0, 0., 0.0), 4), manip_core::enums::robot::Quadruped); factories::TreeFactory factory; Tree* rightLeg = treeFact_.CreateTree( QuadrupedLegDownRight, Vector3(0.0, -0.25, -0.1), 0); Tree* leftLeg = treeFact_.CreateTree( QuadrupedLegDownLeft, Vector3(0.0, 0.25 , -0.1), 1); Tree* leftArm = treeFact_.CreateTree( QuadrupedLegDownLeft, Vector3(1.5, 0.25 , -0.1), 2); Tree* rightArm = treeFact_.CreateTree( QuadrupedLegDownRight, Vector3(1.5, -0.25, -0.1), 3); res->AddTree(rightLeg, matrices::Vector3(0,0,0), 0); res->AddTree(leftLeg, matrices::Vector3(0,0,0), 0); res->AddTree(leftArm, matrices::Vector3(1.5,0,0), 1); res->AddTree(rightArm, matrices::Vector3(1.5,0,0), 1); /*rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3(-0.3, 0, -1.3))); leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.5, 0, -1.3))); rightArm->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightArm->GetPosition() + Vector3( 0.3, 0, -1.3)));*/ rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.4))); leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4))); rightArm->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightArm->GetPosition() + Vector3( 0.4, 0, -1.4))); leftArm->LockTarget (matrix4TimesVect3(res->ToWorldCoordinates(), leftArm->GetPosition() + Vector3( -0.4, 0, -1.4))); return res; } Robot* CreateSpider(const Matrix4& robotBasis) const { // TODO Remove order neccessity to create ids ... Robot* res = new Robot(robotBasis, treeFact_.CreateTree( SpiderTorso, Vector3(0.0, 0., 0.0), 8), manip_core::enums::robot::Spider); factories::TreeFactory factory; Vector3 zeroAngle(0.25, 0, 0); Tree* t1 = treeFact_.CreateTree( SpiderLeg, zeroAngle, 0); Tree* t2 = treeFact_.CreateTree( SpiderLeg, zeroAngle, 1); Tree* t3 = treeFact_.CreateTree( SpiderLeg, zeroAngle, 2); Tree* t4 = treeFact_.CreateTree( SpiderLeg, zeroAngle, 3); Tree* t5 = treeFact_.CreateTree( SpiderLeg, zeroAngle, 4); Tree* t6 = treeFact_.CreateTree( SpiderLeg, zeroAngle, 5); Tree* t7 = treeFact_.CreateTree( SpiderLeg, zeroAngle, 6); Tree* t8 = treeFact_.CreateTree( SpiderLeg, zeroAngle, 7); matrices::Vector3 position(0,0,0); res->AddTree(t1,position, 1); res->AddTree(t2,position, 1); res->AddTree(t3,position, 1); res->AddTree(t4,position, 1); res->AddTree(t5,position, 1); res->AddTree(t6,position, 1); res->AddTree(t7,position, 1); res->AddTree(t8,position, 1); /*rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3(-0.3, 0, -1.3))); leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.5, 0, -1.3))); rightArm->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightArm->GetPosition() + Vector3( 0.3, 0, -1.3)));*/ /*rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.4))); leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4))); rightArm->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightArm->GetPosition() + Vector3( 0.4, 0, -1.4))); leftArm->LockTarget (matrix4TimesVect3(res->ToWorldCoordinates(), leftArm->GetPosition() + Vector3( -0.4, 0, -1.4)));*/ return res; } Robot* CreateSpiderRace(const Matrix4& robotBasis) const { // TODO Remove order neccessity to create ids ... Robot* res = new Robot(robotBasis, treeFact_.CreateTree( SpiderTorsoRace, Vector3(0.0, 0., 0.0), 4), manip_core::enums::robot::SpiderRace); factories::TreeFactory factory; Vector3 zeroAngle(0.25, 0, 0); Tree* t1 = treeFact_.CreateTree( SpiderLegRace, zeroAngle, 0); Tree* t2 = treeFact_.CreateTree( SpiderLegRace, zeroAngle, 1); Tree* t3 = treeFact_.CreateTree( SpiderLegRace, zeroAngle, 2); Tree* t4 = treeFact_.CreateTree( SpiderLegRace, zeroAngle, 3); matrices::Vector3 position(0,0,0); res->AddTree(t1,position, 1); res->AddTree(t2,position, 1); res->AddTree(t3,position, 1); res->AddTree(t4,position, 1); return res; } Robot* CreateSpiderSix(const Matrix4& robotBasis) const { // TODO Remove order neccessity to create ids ... Robot* res = new Robot(robotBasis, treeFact_.CreateTree( SpiderTorsoRace, Vector3(0.0, 0., 0.0), 4), manip_core::enums::robot::SpiderSix); factories::TreeFactory factory; Vector3 zeroAngle(0.25, 0, 0); Tree* t1 = treeFact_.CreateTree( SpiderLegSix, zeroAngle, 0); Tree* t2 = treeFact_.CreateTree( SpiderLegSix, zeroAngle, 1); Tree* t3 = treeFact_.CreateTree( SpiderLegSix, zeroAngle, 2); Tree* t4 = treeFact_.CreateTree( SpiderLegSix, zeroAngle, 3); Tree* t5 = treeFact_.CreateTree( SpiderLegSix, zeroAngle, 4); Tree* t6 = treeFact_.CreateTree( SpiderLegSix, zeroAngle, 5); matrices::Vector3 position(0,0,0); res->AddTree(t1,position, 1); res->AddTree(t2,position, 1); res->AddTree(t3,position, 1); res->AddTree(t4,position, 1); res->AddTree(t5,position, 1); res->AddTree(t6,position, 1); return res; } TreeFactory treeFact_; }; } using namespace factories; RobotFactory::RobotFactory() : pImpl_(new RobotFactoryPimpl()) { // NOTHING } RobotFactory::~RobotFactory() { // NOTHING } Robot* RobotFactory::CreateRobot(const eRobots robots, const Matrix4& robotBasis) const { switch (robots) { case Human: { return pImpl_->CreateHuman(robotBasis); } case HumanWalk: { return pImpl_->CreateHumanWalk(robotBasis); } case HumanEscalade: { return pImpl_->CreateHumanEscalade(robotBasis); } case HumanCanap: { return pImpl_->CreateHumanCanap(robotBasis); } case HumanEllipse: { return pImpl_->CreateHumanEllipse(robotBasis); } case Quadruped: { return pImpl_->CreateQuadruped(robotBasis); } case QuadrupedDown: { return pImpl_->CreateQuadrupedDown(robotBasis); } case Spider: { return pImpl_->CreateSpider(robotBasis); } case SpiderSix: { return pImpl_->CreateSpiderSix(robotBasis); } case SpiderRace: { return pImpl_->CreateSpiderRace(robotBasis); } case HumanCrouch: { return pImpl_->CreateHumanCrouch(robotBasis); } case HumanCrouch180: { return pImpl_->CreateHumanCrouch180(robotBasis); } default: throw(std::exception()); } } /* bool IsSpine(const joint_def_t* root) { const std::string headTag("head"); std::string taf(root->tag); return (root->nbChildren_ == 0) ? (taf == headTag) : IsSpine(root->children[0]); } const joint_def_t* RetrieveSpine(std::list<const joint_def_t*>& trees) { for(std::list<const joint_def_t*>::const_iterator it = trees.begin(); it!= trees.end(); ++it) { if(IsSpine(*it)) { const joint_def_t* res = (*it); trees.remove(*it); return res; } } return 0; } void GetTrees(const joint_def_t* root, std::list<const joint_def_t*>& trees) { if(root->is_simple() && !root->is_locked()) { trees.push_back(root); } else { for(unsigned int i = 0; i < root->nbChildren_; ++i) { GetTrees(root->children[i], trees); } } } #include "Pi.h" #include "kinematic/Com.h" #include "kinematic/Joint.h" #include "kinematic/Tree.h" Joint* GetLast(Tree* tree) { Joint* j = tree->GetRoot(); while(j) { if(j->pChild_) j = j->pChild_; else return j; } return 0; } void ReadOneJointDef(matrices::Vector3 root, const joint_def_t* jointDef, Tree* tree, const ComFactory& comFact_) { const Vector3 unitx(1, 0, 0); const Vector3 unity(0, 1, 0); const Vector3 unitz(0, 0, 1); const Vector3 vectors []= {unitx, unity, unitz}; Joint* previous = GetLast(tree); matrices::Vector3 attach(jointDef->offset[0], jointDef->offset[1], jointDef->offset[2]); attach += root; bool lastIsEffector = jointDef->nbChildren_ == 0; for(int i = 0; i < 3; ++ i) { Joint* j = new Joint(attach, vectors[i], (lastIsEffector && i == 2) ? EFFECTOR : JOINT, comFact_.CreateCom(None) , RADIAN(jointDef->minAngleValues[i]), RADIAN(jointDef->maxAngleValues[i]), RADIAN(jointDef->defaultAngleValues[i]), rotation::eRotation(i)); if(previous) { tree->InsertChild(previous, j); } else { tree->InsertRoot(j); } previous = j; } if(!lastIsEffector) ReadOneJointDef(attach, jointDef->children[0], tree, comFact_); } Tree* MakeTree(const joint_def_t* root, unsigned int& id) { assert(root->is_simple()); const ComFactory comFact; Tree* tree = new Tree(id++); const joint_def_t* current_joint = root; matrices::Vector3 attach(0,0,0); ReadOneJointDef(attach, root, tree, comFact); return tree; } Robot* RobotFactory::CreateRobot(const joint_def_t& joint, const Matrix4& robotBasis) const { std::list<const joint_def_t*> trees; GetTrees(&joint, trees); const joint_def_t * spine = RetrieveSpine(trees); unsigned int id = 0; unsigned int torsoIndex = trees.size(); Robot* res = new Robot(robotBasis, MakeTree(spine, torsoIndex)); for(std::list<const joint_def_t*>::const_iterator it = trees.begin(); it!= trees.end(); ++it) { matrices::Vector3 offset((*it)->offset[0], (*it)->offset[1], (*it)->offset[2]); res->AddTree( MakeTree((*it), id), offset, 0); // TODO find good column joint for rendering } return res; }*/
heyang123/ManipulabilitySampleTestapp
src/manipulability_core/kinematic/RobotFactory.cpp
C++
gpl-2.0
20,561
<!DOCTYPE html> <html lang="en"> <head> <?php ////////////////////////////////////////////////////// ///Copyright 2015 Luna Claudio,Rebolloso Leandro./// //////////////////////////////////////////////////// // //This file is part of ARSoftware. //ARSoftware 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. // //ARSoftware 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ?> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>ARSoftware</title> <?php include_once($_SERVER["DOCUMENT_ROOT"]."/arsoftware/utiles/headerAdmin.php"); include_once($docRootSitio."modelo/Administrador.php"); #Paginación $limit=15; if(is_numeric($_GET['pagina']) && $_GET['pagina']>=1){ $offset = ($_GET['pagina']-1) * $limit; } else{ $offset=0; } #Orden por defecto if(!isset($_GET['campoOrder']) && !isset($_GET['order']) ){ $order = "DESC"; } else{ $campoOrder = $_GET['campoOrder']; $order = $_GET['order']; } #incluyo clases include_once($docRootSitio."modelo/Marca.php"); #nuevo objeto $mar1 = new Marca(); $adm1 = new Administrador(); $usuario = $_SESSION["nombreUsuario"]; $mar1->setNombreUsuario($usuario); $_marcas = $mar1->listarMarcas($offset,$limit,$campoOrder,$order); $_nombre = $adm1->listarAdministradorins2($usuario); #getCantRegistros $cantRegistros = $mar1->getCantRegistros(); $cantPaginas = ceil($cantRegistros/$limit); ?> <!-- Bootstrap Core CSS --> <link href="<?php echo $httpHostSitio?>plantilla/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom CSS --> <link href="<?php echo $httpHostSitio?>plantilla/css/sb-admin.css" rel="stylesheet"> <!-- Morris Charts CSS --> <link href="<?php echo $httpHostSitio?>plantilla/css/plugins/morris.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="<?php echo $httpHostSitio?>plantilla/font-awesome-4.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <script src="<?php echo $httpHostSitio?>jquery/jquery-1.11.1.js"></script> <script src="<?php echo $httpHostSitio?>plantilla/js/bootstrap.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/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div id="wrapper"> <!-- Navigation --> <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <div onclick="location = ('<?php echo $httpHostSitio?>modulos/back-end/administradores/principalAdministradorAR.php')"; style="height: 52px; width:225px; max-width: 100%; background: #FFFFFF; background-image: url(<?php echo $httpHostSitio?>plantilla/imagenes/logotipoe.png);"></div> </div> <ul class="nav navbar-right top-nav"> <li class="dropdown"> <a href="principalAdministrador.php" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-user"></i> <?php echo $_nombre['nombre'].' '.$_nombre['apellido']?> <b class="caret"></b></a> <ul class="dropdown-menu"> <li> <a href="<?php echo $httpHostSitio?>utiles/ctrlLogout.php"><i class="fa fa-fw fa-power-off"></i> Salir</a> </li> </ul> </li> </ul> <!-- Sidebar Menu Items - These collapse to the responsive navigation menu on small screens --> <div class="collapse navbar-collapse navbar-ex1-collapse"> <?php include_once($docRootSitio."utiles/menuAdministradorAR.php");?> </div> <!-- /.navbar-collapse --> </nav> <div id="page-wrapper"> <div class="container-fluid"> </div> <!-- /.container-fluid ------------------------------------------------------------------------------------------------------> <div class="row"> <div class="col-lg-12"> <h1 class="page-header"> Marcas Netbooks </h1> <ol class="breadcrumb"> <li class="active"> <i class="fa fa-dashboard"></i> Marcas Netbooks </li> </ol> </div> </div> <?php if($_GET['insert']==1){?> <div class="alert alert-success"> <strong>La Marca Se Agrego Exitosamente.</strong> </div> <?php }?> <?php if($_GET['update']==1){?> <div class="alert alert-success"> <strong>La Marca Se Modificó Exitosamente.</strong> </div> <?php }?> <?php if($_GET['delete']==1){?> <div class="alert alert-success"> <strong>La Marca Se Elimino Exitosamente.</strong> </div> <?php }?> <p> <button type="button" class="btn btn-primary" onclick="location = ('<?php echo $httpHostSitio?>modulos/back-end/netescuela/listarNetbooks.php')" > Remanente Netbook</button> <button type="button" class="btn btn-success" onclick="location = ('<?php echo $httpHostSitio?>modulos/back-end/prestamo/listarPrestamos.php')" > Prestamos Netbook</button> <button type="button" class="btn btn-warning" onclick="location = ('<?php echo $httpHostSitio?>modulos/back-end/marcas/listarMarcas.php')" > Marcas Netbooks</button> <button type="button" class="btn btn-danger" onclick="location = ('<?php echo $httpHostSitio?>modulos/back-end/marcas/agregarMarca.php')" > Agregar Marca Netbooks</button> </p> <?php if(!isset($_GET['order']) || $_GET['order']=="DESC"){ $order = "ASC"; } else{ $order = "DESC"; } if(count($_marcas)){?> <table class="table table-bordered table-hover table-striped"> <tr> <td> <center><b>Nombre</b></center> </td> <td> <center><b>Acciones</b></center> </td> </tr> <?php for($i=1;$i<=count($_marcas);$i++){ if($i%2==0){ $class="class='alt'"; $classTh="class='specalt'"; } else{ $class=""; $classTh="class='spec'"; } ?> <tr> <td> <center><?php echo $_marcas[$i]['nombre']?></center> </td> <td> <div id="celdaAcciones"> <center><form method="post" action="modificarMarca.php"> <input type="hidden" name="Marca" value="<?php echo $_marcas[$i]['id']?>"> <input type="submit" value="Editar" class="btn btn-primary"> </form></center> </div> <div id="celdaAcciones"> <center><form method="post" action="eliminarMarca.php"> <input type="hidden" name="Marca" value="<?php echo $_marcas[$i]['id']?>"> <input type="submit" value="Eliminar" class="btn btn-success" onclick="return confirm('¿Está seguro que desea eliminar la siguiente marca <?php echo $_marcas[$i]['nombre']?>?');"> </form></center> </div> </td> </tr> <?php }?> </table> <div id="paginacion"> <?php if(!is_numeric($_GET['pagina']) || $_GET['pagina']<=1){ $_GET['pagina'] = 1; } else{ $paginaAnterior=$_GET['pagina']-1; if(isset($_GET['campoOrder']) && isset($_GET['order'])){ $campoOrder = $_GET['campoOrder'];+ $order = $_GET['order']; $criteriosOrder = "&campoOrder=$campoOrder&order=$order"; } ?> <a href="listarMarcas.php?pagina=<?php echo $paginaAnterior?><?php echo $criteriosOrder?>">Anterior</a> <?php }?> Página <?php echo $_GET['pagina']?>/<?php echo $cantPaginas?> de <?php echo $cantRegistros?> registros <?php if($_GET['pagina']<$cantPaginas){ $paginaSiguiente=$_GET['pagina']+1; if(isset($_GET['campoOrder']) && isset($_GET['order'])){ $campoOrder = $_GET['campoOrder'];+ $order = $_GET['order']; $criteriosOrder = "&campoOrder=$campoOrder&order=$order"; } ?> <a href="listarMarcas.php?pagina=<?php echo $paginaSiguiente?><?php echo $criteriosOrder?>">Siguiente</a> <?php }?> </div> <?php } else{?> <div class="alert alert-info"> <center><strong>Aviso! </strong> No existen marcas de netbooks cargadas.</center> </div> <?php }?> </div><!-- Fin container-fluid ------------------------------------------------------------------------------------------------------> <!-- /#page-wrapper --> <!-- /#wrapper --> <!-- jQuery Version 1.11.0 --> <script src="js/jquery-1.11.0.js"></script> <!-- Bootstrap Core JavaScript --> <script src="js/bootstrap.min.js"></script> <!-- Morris Charts JavaScript --> <script src="js/plugins/morris/raphael.min.js"></script> <script src="js/plugins/morris/morris.min.js"></script> <script src="js/plugins/morris/morris-data.js"></script> </body> </html>
claudioLuna/arsoftware
modulos/back-end/marcas/listarMarcas.php
PHP
gpl-2.0
10,483
/* * SSLv3/TLSv1 server-side functions * * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed 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. * * This file is part of mbed TLS (https://tls.mbed.org) */ #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #if defined(MBEDTLS_SSL_SRV_C) #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else #include <stdlib.h> #define mbedtls_calloc calloc #define mbedtls_free free #endif #include "mbedtls/ssl.h" #include "mbedtls/ssl_internal.h" #include "mbedtls/debug.h" #include "mbedtls/error.h" #include "mbedtls/platform_util.h" #include <string.h> #if defined(MBEDTLS_ECP_C) #include "mbedtls/ecp.h" #endif #if defined(MBEDTLS_HAVE_TIME) #include "mbedtls/platform_time.h" #endif #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) int mbedtls_ssl_set_client_transport_id( mbedtls_ssl_context *ssl, const unsigned char *info, size_t ilen ) { if( ssl->conf->endpoint != MBEDTLS_SSL_IS_SERVER ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); mbedtls_free( ssl->cli_id ); if( ( ssl->cli_id = mbedtls_calloc( 1, ilen ) ) == NULL ) return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); memcpy( ssl->cli_id, info, ilen ); ssl->cli_id_len = ilen; return( 0 ); } void mbedtls_ssl_conf_dtls_cookies( mbedtls_ssl_config *conf, mbedtls_ssl_cookie_write_t *f_cookie_write, mbedtls_ssl_cookie_check_t *f_cookie_check, void *p_cookie ) { conf->f_cookie_write = f_cookie_write; conf->f_cookie_check = f_cookie_check; conf->p_cookie = p_cookie; } #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */ #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) static int ssl_parse_servername_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t servername_list_size, hostname_len; const unsigned char *p; MBEDTLS_SSL_DEBUG_MSG( 3, ( "parse ServerName extension" ) ); if( len < 2 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } servername_list_size = ( ( buf[0] << 8 ) | ( buf[1] ) ); if( servername_list_size + 2 != len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } p = buf + 2; while( servername_list_size > 2 ) { hostname_len = ( ( p[1] << 8 ) | p[2] ); if( hostname_len + 3 > servername_list_size ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } if( p[0] == MBEDTLS_TLS_EXT_SERVERNAME_HOSTNAME ) { ret = ssl->conf->f_sni( ssl->conf->p_sni, ssl, p + 3, hostname_len ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_sni_wrapper", ret ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNRECOGNIZED_NAME ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } return( 0 ); } servername_list_size -= hostname_len + 3; p += hostname_len + 3; } if( servername_list_size != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } return( 0 ); } #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */ #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) static int ssl_conf_has_psk_or_cb( mbedtls_ssl_config const *conf ) { if( conf->f_psk != NULL ) return( 1 ); if( conf->psk_identity_len == 0 || conf->psk_identity == NULL ) return( 0 ); if( conf->psk != NULL && conf->psk_len != 0 ) return( 1 ); #if defined(MBEDTLS_USE_PSA_CRYPTO) if( conf->psk_opaque != 0 ) return( 1 ); #endif /* MBEDTLS_USE_PSA_CRYPTO */ return( 0 ); } #if defined(MBEDTLS_USE_PSA_CRYPTO) static int ssl_use_opaque_psk( mbedtls_ssl_context const *ssl ) { if( ssl->conf->f_psk != NULL ) { /* If we've used a callback to select the PSK, * the static configuration is irrelevant. */ if( ssl->handshake->psk_opaque != 0 ) return( 1 ); return( 0 ); } if( ssl->conf->psk_opaque != 0 ) return( 1 ); return( 0 ); } #endif /* MBEDTLS_USE_PSA_CRYPTO */ #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */ static int ssl_parse_renegotiation_info( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ) { /* Check verify-data in constant-time. The length OTOH is no secret */ if( len != 1 + ssl->verify_data_len || buf[0] != ssl->verify_data_len || mbedtls_ssl_safer_memcmp( buf + 1, ssl->peer_verify_data, ssl->verify_data_len ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching renegotiation info" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } } else #endif /* MBEDTLS_SSL_RENEGOTIATION */ { if( len != 1 || buf[0] != 0x0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-zero length renegotiation info" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION; } return( 0 ); } #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) /* * Status of the implementation of signature-algorithms extension: * * Currently, we are only considering the signature-algorithm extension * to pick a ciphersuite which allows us to send the ServerKeyExchange * message with a signature-hash combination that the user allows. * * We do *not* check whether all certificates in our certificate * chain are signed with an allowed signature-hash pair. * This needs to be done at a later stage. * */ static int ssl_parse_signature_algorithms_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { size_t sig_alg_list_size; const unsigned char *p; const unsigned char *end = buf + len; mbedtls_md_type_t md_cur; mbedtls_pk_type_t sig_cur; if ( len < 2 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } sig_alg_list_size = ( ( buf[0] << 8 ) | ( buf[1] ) ); if( sig_alg_list_size + 2 != len || sig_alg_list_size % 2 != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* Currently we only guarantee signing the ServerKeyExchange message according * to the constraints specified in this extension (see above), so it suffices * to remember only one suitable hash for each possible signature algorithm. * * This will change when we also consider certificate signatures, * in which case we will need to remember the whole signature-hash * pair list from the extension. */ for( p = buf + 2; p < end; p += 2 ) { /* Silently ignore unknown signature or hash algorithms. */ if( ( sig_cur = mbedtls_ssl_pk_alg_from_sig( p[1] ) ) == MBEDTLS_PK_NONE ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext" " unknown sig alg encoding %d", p[1] ) ); continue; } /* Check if we support the hash the user proposes */ md_cur = mbedtls_ssl_md_alg_from_hash( p[0] ); if( md_cur == MBEDTLS_MD_NONE ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext:" " unknown hash alg encoding %d", p[0] ) ); continue; } if( mbedtls_ssl_check_sig_hash( ssl, md_cur ) == 0 ) { mbedtls_ssl_sig_hash_set_add( &ssl->handshake->hash_algs, sig_cur, md_cur ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext:" " match sig %d and hash %d", sig_cur, md_cur ) ); } else { MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext: " "hash alg %d not supported", md_cur ) ); } } return( 0 ); } #endif /* MBEDTLS_SSL_PROTO_TLS1_2 && MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */ #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) static int ssl_parse_supported_elliptic_curves( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { size_t list_size, our_size; const unsigned char *p; const mbedtls_ecp_curve_info *curve_info, **curves; if ( len < 2 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } list_size = ( ( buf[0] << 8 ) | ( buf[1] ) ); if( list_size + 2 != len || list_size % 2 != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* Should never happen unless client duplicates the extension */ if( ssl->handshake->curves != NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* Don't allow our peer to make us allocate too much memory, * and leave room for a final 0 */ our_size = list_size / 2 + 1; if( our_size > MBEDTLS_ECP_DP_MAX ) our_size = MBEDTLS_ECP_DP_MAX; if( ( curves = mbedtls_calloc( our_size, sizeof( *curves ) ) ) == NULL ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR ); return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); } ssl->handshake->curves = curves; p = buf + 2; while( list_size > 0 && our_size > 1 ) { curve_info = mbedtls_ecp_curve_info_from_tls_id( ( p[0] << 8 ) | p[1] ); if( curve_info != NULL ) { *curves++ = curve_info; our_size--; } list_size -= 2; p += 2; } return( 0 ); } static int ssl_parse_supported_point_formats( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { size_t list_size; const unsigned char *p; if( len == 0 || (size_t)( buf[0] + 1 ) != len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } list_size = buf[0]; p = buf + 1; while( list_size > 0 ) { if( p[0] == MBEDTLS_ECP_PF_UNCOMPRESSED || p[0] == MBEDTLS_ECP_PF_COMPRESSED ) { #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) ssl->handshake->ecdh_ctx.point_format = p[0]; #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) ssl->handshake->ecjpake_ctx.point_format = p[0]; #endif MBEDTLS_SSL_DEBUG_MSG( 4, ( "point format selected: %d", p[0] ) ); return( 0 ); } list_size--; p++; } return( 0 ); } #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) static int ssl_parse_ecjpake_kkpp( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; if( mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip ecjpake kkpp extension" ) ); return( 0 ); } if( ( ret = mbedtls_ecjpake_read_round_one( &ssl->handshake->ecjpake_ctx, buf, len ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_one", ret ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( ret ); } /* Only mark the extension as OK when we're sure it is */ ssl->handshake->cli_exts |= MBEDTLS_TLS_EXT_ECJPAKE_KKPP_OK; return( 0 ); } #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) static int ssl_parse_max_fragment_length_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { if( len != 1 || buf[0] >= MBEDTLS_SSL_MAX_FRAG_LEN_INVALID ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ssl->session_negotiate->mfl_code = buf[0]; return( 0 ); } #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) static int ssl_parse_cid_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { size_t peer_cid_len; /* CID extension only makes sense in DTLS */ if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* * Quoting draft-ietf-tls-dtls-connection-id-05 * https://tools.ietf.org/html/draft-ietf-tls-dtls-connection-id-05 * * struct { * opaque cid<0..2^8-1>; * } ConnectionId; */ if( len < 1 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } peer_cid_len = *buf++; len--; if( len != peer_cid_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* Ignore CID if the user has disabled its use. */ if( ssl->negotiate_cid == MBEDTLS_SSL_CID_DISABLED ) { /* Leave ssl->handshake->cid_in_use in its default * value of MBEDTLS_SSL_CID_DISABLED. */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "Client sent CID extension, but CID disabled" ) ); return( 0 ); } if( peer_cid_len > MBEDTLS_SSL_CID_OUT_LEN_MAX ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ssl->handshake->cid_in_use = MBEDTLS_SSL_CID_ENABLED; ssl->handshake->peer_cid_len = (uint8_t) peer_cid_len; memcpy( ssl->handshake->peer_cid, buf, peer_cid_len ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "Use of CID extension negotiated" ) ); MBEDTLS_SSL_DEBUG_BUF( 3, "Client CID", buf, peer_cid_len ); return( 0 ); } #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ #if defined(MBEDTLS_SSL_TRUNCATED_HMAC) static int ssl_parse_truncated_hmac_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { if( len != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ((void) buf); if( ssl->conf->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_ENABLED ) ssl->session_negotiate->trunc_hmac = MBEDTLS_SSL_TRUNC_HMAC_ENABLED; return( 0 ); } #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */ #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) static int ssl_parse_encrypt_then_mac_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { if( len != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ((void) buf); if( ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED && ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0 ) { ssl->session_negotiate->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED; } return( 0 ); } #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) static int ssl_parse_extended_ms_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { if( len != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ((void) buf); if( ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_ENABLED && ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0 ) { ssl->handshake->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED; } return( 0 ); } #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) static int ssl_parse_session_ticket_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; mbedtls_ssl_session session; mbedtls_ssl_session_init( &session ); if( ssl->conf->f_ticket_parse == NULL || ssl->conf->f_ticket_write == NULL ) { return( 0 ); } /* Remember the client asked us to send a new ticket */ ssl->handshake->new_session_ticket = 1; MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket length: %d", len ) ); if( len == 0 ) return( 0 ); #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket rejected: renegotiating" ) ); return( 0 ); } #endif /* MBEDTLS_SSL_RENEGOTIATION */ /* * Failures are ok: just ignore the ticket and proceed. */ if( ( ret = ssl->conf->f_ticket_parse( ssl->conf->p_ticket, &session, buf, len ) ) != 0 ) { mbedtls_ssl_session_free( &session ); if( ret == MBEDTLS_ERR_SSL_INVALID_MAC ) MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket is not authentic" ) ); else if( ret == MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED ) MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket is expired" ) ); else MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_ticket_parse", ret ); return( 0 ); } /* * Keep the session ID sent by the client, since we MUST send it back to * inform them we're accepting the ticket (RFC 5077 section 3.4) */ session.id_len = ssl->session_negotiate->id_len; memcpy( &session.id, ssl->session_negotiate->id, session.id_len ); mbedtls_ssl_session_free( ssl->session_negotiate ); memcpy( ssl->session_negotiate, &session, sizeof( mbedtls_ssl_session ) ); /* Zeroize instead of free as we copied the content */ mbedtls_platform_zeroize( &session, sizeof( mbedtls_ssl_session ) ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "session successfully restored from ticket" ) ); ssl->handshake->resume = 1; /* Don't send a new ticket after all, this one is OK */ ssl->handshake->new_session_ticket = 0; return( 0 ); } #endif /* MBEDTLS_SSL_SESSION_TICKETS */ #if defined(MBEDTLS_SSL_ALPN) static int ssl_parse_alpn_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { size_t list_len, cur_len, ours_len; const unsigned char *theirs, *start, *end; const char **ours; /* If ALPN not configured, just ignore the extension */ if( ssl->conf->alpn_list == NULL ) return( 0 ); /* * opaque ProtocolName<1..2^8-1>; * * struct { * ProtocolName protocol_name_list<2..2^16-1> * } ProtocolNameList; */ /* Min length is 2 (list_len) + 1 (name_len) + 1 (name) */ if( len < 4 ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } list_len = ( buf[0] << 8 ) | buf[1]; if( list_len != len - 2 ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* * Validate peer's list (lengths) */ start = buf + 2; end = buf + len; for( theirs = start; theirs != end; theirs += cur_len ) { cur_len = *theirs++; /* Current identifier must fit in list */ if( cur_len > (size_t)( end - theirs ) ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* Empty strings MUST NOT be included */ if( cur_len == 0 ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } } /* * Use our order of preference */ for( ours = ssl->conf->alpn_list; *ours != NULL; ours++ ) { ours_len = strlen( *ours ); for( theirs = start; theirs != end; theirs += cur_len ) { cur_len = *theirs++; if( cur_len == ours_len && memcmp( theirs, *ours, cur_len ) == 0 ) { ssl->alpn_chosen = *ours; return( 0 ); } } } /* If we get there, no match was found */ mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_NO_APPLICATION_PROTOCOL ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } #endif /* MBEDTLS_SSL_ALPN */ /* * Auxiliary functions for ServerHello parsing and related actions */ #if defined(MBEDTLS_X509_CRT_PARSE_C) /* * Return 0 if the given key uses one of the acceptable curves, -1 otherwise */ #if defined(MBEDTLS_ECDSA_C) static int ssl_check_key_curve( mbedtls_pk_context *pk, const mbedtls_ecp_curve_info **curves ) { const mbedtls_ecp_curve_info **crv = curves; mbedtls_ecp_group_id grp_id = mbedtls_pk_ec( *pk )->grp.id; while( *crv != NULL ) { if( (*crv)->grp_id == grp_id ) return( 0 ); crv++; } return( -1 ); } #endif /* MBEDTLS_ECDSA_C */ /* * Try picking a certificate for this ciphersuite, * return 0 on success and -1 on failure. */ static int ssl_pick_cert( mbedtls_ssl_context *ssl, const mbedtls_ssl_ciphersuite_t * ciphersuite_info ) { mbedtls_ssl_key_cert *cur, *list, *fallback = NULL; mbedtls_pk_type_t pk_alg = mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info ); uint32_t flags; #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) if( ssl->handshake->sni_key_cert != NULL ) list = ssl->handshake->sni_key_cert; else #endif list = ssl->conf->key_cert; if( pk_alg == MBEDTLS_PK_NONE ) return( 0 ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite requires certificate" ) ); if( list == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "server has no certificate" ) ); return( -1 ); } for( cur = list; cur != NULL; cur = cur->next ) { flags = 0; MBEDTLS_SSL_DEBUG_CRT( 3, "candidate certificate chain, certificate", cur->cert ); if( ! mbedtls_pk_can_do( &cur->cert->pk, pk_alg ) ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "certificate mismatch: key type" ) ); continue; } /* * This avoids sending the client a cert it'll reject based on * keyUsage or other extensions. * * It also allows the user to provision different certificates for * different uses based on keyUsage, eg if they want to avoid signing * and decrypting with the same RSA key. */ if( mbedtls_ssl_check_cert_usage( cur->cert, ciphersuite_info, MBEDTLS_SSL_IS_SERVER, &flags ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "certificate mismatch: " "(extended) key usage extension" ) ); continue; } #if defined(MBEDTLS_ECDSA_C) if( pk_alg == MBEDTLS_PK_ECDSA && ssl_check_key_curve( &cur->cert->pk, ssl->handshake->curves ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "certificate mismatch: elliptic curve" ) ); continue; } #endif /* * Try to select a SHA-1 certificate for pre-1.2 clients, but still * present them a SHA-higher cert rather than failing if it's the only * one we got that satisfies the other conditions. */ if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 && cur->cert->sig_md != MBEDTLS_MD_SHA1 ) { if( fallback == NULL ) fallback = cur; { MBEDTLS_SSL_DEBUG_MSG( 3, ( "certificate not preferred: " "sha-2 with pre-TLS 1.2 client" ) ); continue; } } /* If we get there, we got a winner */ break; } if( cur == NULL ) cur = fallback; /* Do not update ssl->handshake->key_cert unless there is a match */ if( cur != NULL ) { ssl->handshake->key_cert = cur; MBEDTLS_SSL_DEBUG_CRT( 3, "selected certificate chain, certificate", ssl->handshake->key_cert->cert ); return( 0 ); } return( -1 ); } #endif /* MBEDTLS_X509_CRT_PARSE_C */ /* * Check if a given ciphersuite is suitable for use with our config/keys/etc * Sets ciphersuite_info only if the suite matches. */ static int ssl_ciphersuite_match( mbedtls_ssl_context *ssl, int suite_id, const mbedtls_ssl_ciphersuite_t **ciphersuite_info ) { const mbedtls_ssl_ciphersuite_t *suite_info; #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) mbedtls_pk_type_t sig_type; #endif suite_info = mbedtls_ssl_ciphersuite_from_id( suite_id ); if( suite_info == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "trying ciphersuite: %s", suite_info->name ) ); if( suite_info->min_minor_ver > ssl->minor_ver || suite_info->max_minor_ver < ssl->minor_ver ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: version" ) ); return( 0 ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ( suite_info->flags & MBEDTLS_CIPHERSUITE_NODTLS ) ) return( 0 ); #endif #if defined(MBEDTLS_ARC4_C) if( ssl->conf->arc4_disabled == MBEDTLS_SSL_ARC4_DISABLED && suite_info->cipher == MBEDTLS_CIPHER_ARC4_128 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: rc4" ) ); return( 0 ); } #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) if( suite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE && ( ssl->handshake->cli_exts & MBEDTLS_TLS_EXT_ECJPAKE_KKPP_OK ) == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: ecjpake " "not configured or ext missing" ) ); return( 0 ); } #endif #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) if( mbedtls_ssl_ciphersuite_uses_ec( suite_info ) && ( ssl->handshake->curves == NULL || ssl->handshake->curves[0] == NULL ) ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: " "no common elliptic curve" ) ); return( 0 ); } #endif #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) /* If the ciphersuite requires a pre-shared key and we don't * have one, skip it now rather than failing later */ if( mbedtls_ssl_ciphersuite_uses_psk( suite_info ) && ssl_conf_has_psk_or_cb( ssl->conf ) == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: no pre-shared key" ) ); return( 0 ); } #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) /* If the ciphersuite requires signing, check whether * a suitable hash algorithm is present. */ if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { sig_type = mbedtls_ssl_get_ciphersuite_sig_alg( suite_info ); if( sig_type != MBEDTLS_PK_NONE && mbedtls_ssl_sig_hash_set_find( &ssl->handshake->hash_algs, sig_type ) == MBEDTLS_MD_NONE ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: no suitable hash algorithm " "for signature algorithm %d", sig_type ) ); return( 0 ); } } #endif /* MBEDTLS_SSL_PROTO_TLS1_2 && MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */ #if defined(MBEDTLS_X509_CRT_PARSE_C) /* * Final check: if ciphersuite requires us to have a * certificate/key of a particular type: * - select the appropriate certificate if we have one, or * - try the next ciphersuite if we don't * This must be done last since we modify the key_cert list. */ if( ssl_pick_cert( ssl, suite_info ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: " "no suitable certificate" ) ); return( 0 ); } #endif *ciphersuite_info = suite_info; return( 0 ); } #if defined(MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO) static int ssl_parse_client_hello_v2( mbedtls_ssl_context *ssl ) { int ret, got_common_suite; unsigned int i, j; size_t n; unsigned int ciph_len, sess_len, chal_len; unsigned char *buf, *p; const int *ciphersuites; const mbedtls_ssl_ciphersuite_t *ciphersuite_info; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse client hello v2" ) ); #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "client hello v2 illegal for renegotiation" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } #endif /* MBEDTLS_SSL_RENEGOTIATION */ buf = ssl->in_hdr; MBEDTLS_SSL_DEBUG_BUF( 4, "record header", buf, 5 ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v2, message type: %d", buf[2] ) ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v2, message len.: %d", ( ( buf[0] & 0x7F ) << 8 ) | buf[1] ) ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v2, max. version: [%d:%d]", buf[3], buf[4] ) ); /* * SSLv2 Client Hello * * Record layer: * 0 . 1 message length * * SSL layer: * 2 . 2 message type * 3 . 4 protocol version */ if( buf[2] != MBEDTLS_SSL_HS_CLIENT_HELLO || buf[3] != MBEDTLS_SSL_MAJOR_VERSION_3 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } n = ( ( buf[0] << 8 ) | buf[1] ) & 0x7FFF; if( n < 17 || n > 512 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ssl->major_ver = MBEDTLS_SSL_MAJOR_VERSION_3; ssl->minor_ver = ( buf[4] <= ssl->conf->max_minor_ver ) ? buf[4] : ssl->conf->max_minor_ver; if( ssl->minor_ver < ssl->conf->min_minor_ver ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "client only supports ssl smaller than minimum" " [%d:%d] < [%d:%d]", ssl->major_ver, ssl->minor_ver, ssl->conf->min_major_ver, ssl->conf->min_minor_ver ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION ); return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION ); } ssl->handshake->max_major_ver = buf[3]; ssl->handshake->max_minor_ver = buf[4]; if( ( ret = mbedtls_ssl_fetch_input( ssl, 2 + n ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret ); return( ret ); } ssl->handshake->update_checksum( ssl, buf + 2, n ); buf = ssl->in_msg; n = ssl->in_left - 5; /* * 0 . 1 ciphersuitelist length * 2 . 3 session id length * 4 . 5 challenge length * 6 . .. ciphersuitelist * .. . .. session id * .. . .. challenge */ MBEDTLS_SSL_DEBUG_BUF( 4, "record contents", buf, n ); ciph_len = ( buf[0] << 8 ) | buf[1]; sess_len = ( buf[2] << 8 ) | buf[3]; chal_len = ( buf[4] << 8 ) | buf[5]; MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciph_len: %d, sess_len: %d, chal_len: %d", ciph_len, sess_len, chal_len ) ); /* * Make sure each parameter length is valid */ if( ciph_len < 3 || ( ciph_len % 3 ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } if( sess_len > 32 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } if( chal_len < 8 || chal_len > 32 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } if( n != 6 + ciph_len + sess_len + chal_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, ciphersuitelist", buf + 6, ciph_len ); MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, session id", buf + 6 + ciph_len, sess_len ); MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, challenge", buf + 6 + ciph_len + sess_len, chal_len ); p = buf + 6 + ciph_len; ssl->session_negotiate->id_len = sess_len; memset( ssl->session_negotiate->id, 0, sizeof( ssl->session_negotiate->id ) ); memcpy( ssl->session_negotiate->id, p, ssl->session_negotiate->id_len ); p += sess_len; memset( ssl->handshake->randbytes, 0, 64 ); memcpy( ssl->handshake->randbytes + 32 - chal_len, p, chal_len ); /* * Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV */ for( i = 0, p = buf + 6; i < ciph_len; i += 3, p += 3 ) { if( p[0] == 0 && p[1] == 0 && p[2] == MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "received TLS_EMPTY_RENEGOTIATION_INFO " ) ); #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "received RENEGOTIATION SCSV " "during renegotiation" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } #endif /* MBEDTLS_SSL_RENEGOTIATION */ ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION; break; } } #if defined(MBEDTLS_SSL_FALLBACK_SCSV) for( i = 0, p = buf + 6; i < ciph_len; i += 3, p += 3 ) { if( p[0] == 0 && p[1] == (unsigned char)( ( MBEDTLS_SSL_FALLBACK_SCSV_VALUE >> 8 ) & 0xff ) && p[2] == (unsigned char)( ( MBEDTLS_SSL_FALLBACK_SCSV_VALUE ) & 0xff ) ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "received FALLBACK_SCSV" ) ); if( ssl->minor_ver < ssl->conf->max_minor_ver ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "inapropriate fallback" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_INAPROPRIATE_FALLBACK ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } break; } } #endif /* MBEDTLS_SSL_FALLBACK_SCSV */ got_common_suite = 0; ciphersuites = ssl->conf->ciphersuite_list[ssl->minor_ver]; ciphersuite_info = NULL; #if defined(MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE) for( j = 0, p = buf + 6; j < ciph_len; j += 3, p += 3 ) for( i = 0; ciphersuites[i] != 0; i++ ) #else for( i = 0; ciphersuites[i] != 0; i++ ) for( j = 0, p = buf + 6; j < ciph_len; j += 3, p += 3 ) #endif { if( p[0] != 0 || p[1] != ( ( ciphersuites[i] >> 8 ) & 0xFF ) || p[2] != ( ( ciphersuites[i] ) & 0xFF ) ) continue; got_common_suite = 1; if( ( ret = ssl_ciphersuite_match( ssl, ciphersuites[i], &ciphersuite_info ) ) != 0 ) return( ret ); if( ciphersuite_info != NULL ) goto have_ciphersuite_v2; } if( got_common_suite ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "got ciphersuites in common, " "but none of them usable" ) ); return( MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE ); } else { MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no ciphersuites in common" ) ); return( MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN ); } have_ciphersuite_v2: MBEDTLS_SSL_DEBUG_MSG( 2, ( "selected ciphersuite: %s", ciphersuite_info->name ) ); ssl->session_negotiate->ciphersuite = ciphersuites[i]; ssl->handshake->ciphersuite_info = ciphersuite_info; /* * SSLv2 Client Hello relevant renegotiation security checks */ if( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION && ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation, breaking off handshake" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ssl->in_left = 0; ssl->state++; MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse client hello v2" ) ); return( 0 ); } #endif /* MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO */ /* This function doesn't alert on errors that happen early during ClientHello parsing because they might indicate that the client is not talking SSL/TLS at all and would not understand our alert. */ static int ssl_parse_client_hello( mbedtls_ssl_context *ssl ) { int ret, got_common_suite; size_t i, j; size_t ciph_offset, comp_offset, ext_offset; size_t msg_len, ciph_len, sess_len, comp_len, ext_len; #if defined(MBEDTLS_SSL_PROTO_DTLS) size_t cookie_offset, cookie_len; #endif unsigned char *buf, *p, *ext; #if defined(MBEDTLS_SSL_RENEGOTIATION) int renegotiation_info_seen = 0; #endif int handshake_failure = 0; const int *ciphersuites; const mbedtls_ssl_ciphersuite_t *ciphersuite_info; int major, minor; /* If there is no signature-algorithm extension present, * we need to fall back to the default values for allowed * signature-hash pairs. */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) int sig_hash_alg_ext_present = 0; #endif /* MBEDTLS_SSL_PROTO_TLS1_2 && MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */ MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse client hello" ) ); #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) read_record_header: #endif /* * If renegotiating, then the input was read with mbedtls_ssl_read_record(), * otherwise read it ourselves manually in order to support SSLv2 * ClientHello, which doesn't use the same record layer format. */ #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE ) #endif { if( ( ret = mbedtls_ssl_fetch_input( ssl, 5 ) ) != 0 ) { /* No alert on a read error. */ MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret ); return( ret ); } } buf = ssl->in_hdr; #if defined(MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO) #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_STREAM ) #endif if( ( buf[0] & 0x80 ) != 0 ) return( ssl_parse_client_hello_v2( ssl ) ); #endif MBEDTLS_SSL_DEBUG_BUF( 4, "record header", buf, mbedtls_ssl_in_hdr_len( ssl ) ); /* * SSLv3/TLS Client Hello * * Record layer: * 0 . 0 message type * 1 . 2 protocol version * 3 . 11 DTLS: epoch + record sequence number * 3 . 4 message length */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, message type: %d", buf[0] ) ); if( buf[0] != MBEDTLS_SSL_MSG_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, message len.: %d", ( ssl->in_len[0] << 8 ) | ssl->in_len[1] ) ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, protocol version: [%d:%d]", buf[1], buf[2] ) ); mbedtls_ssl_read_version( &major, &minor, ssl->conf->transport, buf + 1 ); /* According to RFC 5246 Appendix E.1, the version here is typically * "{03,00}, the lowest version number supported by the client, [or] the * value of ClientHello.client_version", so the only meaningful check here * is the major version shouldn't be less than 3 */ if( major < MBEDTLS_SSL_MAJOR_VERSION_3 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* For DTLS if this is the initial handshake, remember the client sequence * number to use it in our next message (RFC 6347 4.2.1) */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM #if defined(MBEDTLS_SSL_RENEGOTIATION) && ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE #endif ) { /* Epoch should be 0 for initial handshakes */ if( ssl->in_ctr[0] != 0 || ssl->in_ctr[1] != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } memcpy( ssl->cur_out_ctr + 2, ssl->in_ctr + 2, 6 ); #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) if( mbedtls_ssl_dtls_replay_check( ssl ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "replayed record, discarding" ) ); ssl->next_record_offset = 0; ssl->in_left = 0; goto read_record_header; } /* No MAC to check yet, so we can update right now */ mbedtls_ssl_dtls_replay_update( ssl ); #endif } #endif /* MBEDTLS_SSL_PROTO_DTLS */ msg_len = ( ssl->in_len[0] << 8 ) | ssl->in_len[1]; #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ) { /* Set by mbedtls_ssl_read_record() */ msg_len = ssl->in_hslen; } else #endif { if( msg_len > MBEDTLS_SSL_IN_CONTENT_LEN ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } if( ( ret = mbedtls_ssl_fetch_input( ssl, mbedtls_ssl_in_hdr_len( ssl ) + msg_len ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret ); return( ret ); } /* Done reading this record, get ready for the next one */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) ssl->next_record_offset = msg_len + mbedtls_ssl_in_hdr_len( ssl ); else #endif ssl->in_left = 0; } buf = ssl->in_msg; MBEDTLS_SSL_DEBUG_BUF( 4, "record contents", buf, msg_len ); ssl->handshake->update_checksum( ssl, buf, msg_len ); /* * Handshake layer: * 0 . 0 handshake type * 1 . 3 handshake length * 4 . 5 DTLS only: message seqence number * 6 . 8 DTLS only: fragment offset * 9 . 11 DTLS only: fragment length */ if( msg_len < mbedtls_ssl_hs_hdr_len( ssl ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, handshake type: %d", buf[0] ) ); if( buf[0] != MBEDTLS_SSL_HS_CLIENT_HELLO ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, handshake len.: %d", ( buf[1] << 16 ) | ( buf[2] << 8 ) | buf[3] ) ); /* We don't support fragmentation of ClientHello (yet?) */ if( buf[1] != 0 || msg_len != mbedtls_ssl_hs_hdr_len( ssl ) + ( ( buf[2] << 8 ) | buf[3] ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { /* * Copy the client's handshake message_seq on initial handshakes, * check sequence number on renego. */ #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS ) { /* This couldn't be done in ssl_prepare_handshake_record() */ unsigned int cli_msg_seq = ( ssl->in_msg[4] << 8 ) | ssl->in_msg[5]; if( cli_msg_seq != ssl->handshake->in_msg_seq ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message_seq: " "%d (expected %d)", cli_msg_seq, ssl->handshake->in_msg_seq ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ssl->handshake->in_msg_seq++; } else #endif { unsigned int cli_msg_seq = ( ssl->in_msg[4] << 8 ) | ssl->in_msg[5]; ssl->handshake->out_msg_seq = cli_msg_seq; ssl->handshake->in_msg_seq = cli_msg_seq + 1; } /* * For now we don't support fragmentation, so make sure * fragment_offset == 0 and fragment_length == length */ if( ssl->in_msg[6] != 0 || ssl->in_msg[7] != 0 || ssl->in_msg[8] != 0 || memcmp( ssl->in_msg + 1, ssl->in_msg + 9, 3 ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "ClientHello fragmentation not supported" ) ); return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); } } #endif /* MBEDTLS_SSL_PROTO_DTLS */ buf += mbedtls_ssl_hs_hdr_len( ssl ); msg_len -= mbedtls_ssl_hs_hdr_len( ssl ); /* * ClientHello layer: * 0 . 1 protocol version * 2 . 33 random bytes (starting with 4 bytes of Unix time) * 34 . 35 session id length (1 byte) * 35 . 34+x session id * 35+x . 35+x DTLS only: cookie length (1 byte) * 36+x . .. DTLS only: cookie * .. . .. ciphersuite list length (2 bytes) * .. . .. ciphersuite list * .. . .. compression alg. list length (1 byte) * .. . .. compression alg. list * .. . .. extensions length (2 bytes, optional) * .. . .. extensions (optional) */ /* * Minimal length (with everything empty and extensions omitted) is * 2 + 32 + 1 + 2 + 1 = 38 bytes. Check that first, so that we can * read at least up to session id length without worrying. */ if( msg_len < 38 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* * Check and save the protocol version */ MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, version", buf, 2 ); mbedtls_ssl_read_version( &ssl->major_ver, &ssl->minor_ver, ssl->conf->transport, buf ); ssl->handshake->max_major_ver = ssl->major_ver; ssl->handshake->max_minor_ver = ssl->minor_ver; if( ssl->major_ver < ssl->conf->min_major_ver || ssl->minor_ver < ssl->conf->min_minor_ver ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "client only supports ssl smaller than minimum" " [%d:%d] < [%d:%d]", ssl->major_ver, ssl->minor_ver, ssl->conf->min_major_ver, ssl->conf->min_minor_ver ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION ); return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION ); } if( ssl->major_ver > ssl->conf->max_major_ver ) { ssl->major_ver = ssl->conf->max_major_ver; ssl->minor_ver = ssl->conf->max_minor_ver; } else if( ssl->minor_ver > ssl->conf->max_minor_ver ) ssl->minor_ver = ssl->conf->max_minor_ver; /* * Save client random (inc. Unix time) */ MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, random bytes", buf + 2, 32 ); memcpy( ssl->handshake->randbytes, buf + 2, 32 ); /* * Check the session ID length and save session ID */ sess_len = buf[34]; if( sess_len > sizeof( ssl->session_negotiate->id ) || sess_len + 34 + 2 > msg_len ) /* 2 for cipherlist length field */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, session id", buf + 35, sess_len ); ssl->session_negotiate->id_len = sess_len; memset( ssl->session_negotiate->id, 0, sizeof( ssl->session_negotiate->id ) ); memcpy( ssl->session_negotiate->id, buf + 35, ssl->session_negotiate->id_len ); /* * Check the cookie length and content */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { cookie_offset = 35 + sess_len; cookie_len = buf[cookie_offset]; if( cookie_offset + 1 + cookie_len + 2 > msg_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, cookie", buf + cookie_offset + 1, cookie_len ); #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) if( ssl->conf->f_cookie_check != NULL #if defined(MBEDTLS_SSL_RENEGOTIATION) && ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE #endif ) { if( ssl->conf->f_cookie_check( ssl->conf->p_cookie, buf + cookie_offset + 1, cookie_len, ssl->cli_id, ssl->cli_id_len ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "cookie verification failed" ) ); ssl->handshake->verify_cookie_len = 1; } else { MBEDTLS_SSL_DEBUG_MSG( 2, ( "cookie verification passed" ) ); ssl->handshake->verify_cookie_len = 0; } } else #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */ { /* We know we didn't send a cookie, so it should be empty */ if( cookie_len != 0 ) { /* This may be an attacker's probe, so don't send an alert */ MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "cookie verification skipped" ) ); } /* * Check the ciphersuitelist length (will be parsed later) */ ciph_offset = cookie_offset + 1 + cookie_len; } else #endif /* MBEDTLS_SSL_PROTO_DTLS */ ciph_offset = 35 + sess_len; ciph_len = ( buf[ciph_offset + 0] << 8 ) | ( buf[ciph_offset + 1] ); if( ciph_len < 2 || ciph_len + 2 + ciph_offset + 1 > msg_len || /* 1 for comp. alg. len */ ( ciph_len % 2 ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, ciphersuitelist", buf + ciph_offset + 2, ciph_len ); /* * Check the compression algorithms length and pick one */ comp_offset = ciph_offset + 2 + ciph_len; comp_len = buf[comp_offset]; if( comp_len < 1 || comp_len > 16 || comp_len + comp_offset + 1 > msg_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, compression", buf + comp_offset + 1, comp_len ); ssl->session_negotiate->compression = MBEDTLS_SSL_COMPRESS_NULL; #if defined(MBEDTLS_ZLIB_SUPPORT) for( i = 0; i < comp_len; ++i ) { if( buf[comp_offset + 1 + i] == MBEDTLS_SSL_COMPRESS_DEFLATE ) { ssl->session_negotiate->compression = MBEDTLS_SSL_COMPRESS_DEFLATE; break; } } #endif /* See comments in ssl_write_client_hello() */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) ssl->session_negotiate->compression = MBEDTLS_SSL_COMPRESS_NULL; #endif /* Do not parse the extensions if the protocol is SSLv3 */ #if defined(MBEDTLS_SSL_PROTO_SSL3) if( ( ssl->major_ver != 3 ) || ( ssl->minor_ver != 0 ) ) { #endif /* * Check the extension length */ ext_offset = comp_offset + 1 + comp_len; if( msg_len > ext_offset ) { if( msg_len < ext_offset + 2 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ext_len = ( buf[ext_offset + 0] << 8 ) | ( buf[ext_offset + 1] ); if( ( ext_len > 0 && ext_len < 4 ) || msg_len != ext_offset + 2 + ext_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } } else ext_len = 0; ext = buf + ext_offset + 2; MBEDTLS_SSL_DEBUG_BUF( 3, "client hello extensions", ext, ext_len ); while( ext_len != 0 ) { unsigned int ext_id; unsigned int ext_size; if ( ext_len < 4 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ext_id = ( ( ext[0] << 8 ) | ( ext[1] ) ); ext_size = ( ( ext[2] << 8 ) | ( ext[3] ) ); if( ext_size + 4 > ext_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } switch( ext_id ) { #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) case MBEDTLS_TLS_EXT_SERVERNAME: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found ServerName extension" ) ); if( ssl->conf->f_sni == NULL ) break; ret = ssl_parse_servername_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */ case MBEDTLS_TLS_EXT_RENEGOTIATION_INFO: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found renegotiation extension" ) ); #if defined(MBEDTLS_SSL_RENEGOTIATION) renegotiation_info_seen = 1; #endif ret = ssl_parse_renegotiation_info( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) case MBEDTLS_TLS_EXT_SIG_ALG: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found signature_algorithms extension" ) ); ret = ssl_parse_signature_algorithms_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); sig_hash_alg_ext_present = 1; break; #endif /* MBEDTLS_SSL_PROTO_TLS1_2 && MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */ #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) case MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found supported elliptic curves extension" ) ); ret = ssl_parse_supported_elliptic_curves( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; case MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found supported point formats extension" ) ); ssl->handshake->cli_exts |= MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT; ret = ssl_parse_supported_point_formats( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) case MBEDTLS_TLS_EXT_ECJPAKE_KKPP: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found ecjpake kkpp extension" ) ); ret = ssl_parse_ecjpake_kkpp( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) case MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found max fragment length extension" ) ); ret = ssl_parse_max_fragment_length_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ #if defined(MBEDTLS_SSL_TRUNCATED_HMAC) case MBEDTLS_TLS_EXT_TRUNCATED_HMAC: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found truncated hmac extension" ) ); ret = ssl_parse_truncated_hmac_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */ #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) case MBEDTLS_TLS_EXT_CID: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found CID extension" ) ); ret = ssl_parse_cid_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */ #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) case MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found encrypt then mac extension" ) ); ret = ssl_parse_encrypt_then_mac_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) case MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found extended master secret extension" ) ); ret = ssl_parse_extended_ms_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) case MBEDTLS_TLS_EXT_SESSION_TICKET: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found session ticket extension" ) ); ret = ssl_parse_session_ticket_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; #endif /* MBEDTLS_SSL_SESSION_TICKETS */ #if defined(MBEDTLS_SSL_ALPN) case MBEDTLS_TLS_EXT_ALPN: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found alpn extension" ) ); ret = ssl_parse_alpn_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; #endif /* MBEDTLS_SSL_SESSION_TICKETS */ default: MBEDTLS_SSL_DEBUG_MSG( 3, ( "unknown extension found: %d (ignoring)", ext_id ) ); } ext_len -= 4 + ext_size; ext += 4 + ext_size; if( ext_len > 0 && ext_len < 4 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } } #if defined(MBEDTLS_SSL_PROTO_SSL3) } #endif #if defined(MBEDTLS_SSL_FALLBACK_SCSV) for( i = 0, p = buf + ciph_offset + 2; i < ciph_len; i += 2, p += 2 ) { if( p[0] == (unsigned char)( ( MBEDTLS_SSL_FALLBACK_SCSV_VALUE >> 8 ) & 0xff ) && p[1] == (unsigned char)( ( MBEDTLS_SSL_FALLBACK_SCSV_VALUE ) & 0xff ) ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "received FALLBACK_SCSV" ) ); if( ssl->minor_ver < ssl->conf->max_minor_ver ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "inapropriate fallback" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_INAPROPRIATE_FALLBACK ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } break; } } #endif /* MBEDTLS_SSL_FALLBACK_SCSV */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) /* * Try to fall back to default hash SHA1 if the client * hasn't provided any preferred signature-hash combinations. */ if( sig_hash_alg_ext_present == 0 ) { mbedtls_md_type_t md_default = MBEDTLS_MD_SHA1; if( mbedtls_ssl_check_sig_hash( ssl, md_default ) != 0 ) md_default = MBEDTLS_MD_NONE; mbedtls_ssl_sig_hash_set_const_hash( &ssl->handshake->hash_algs, md_default ); } #endif /* MBEDTLS_SSL_PROTO_TLS1_2 && MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */ /* * Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV */ for( i = 0, p = buf + ciph_offset + 2; i < ciph_len; i += 2, p += 2 ) { if( p[0] == 0 && p[1] == MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "received TLS_EMPTY_RENEGOTIATION_INFO " ) ); #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "received RENEGOTIATION SCSV " "during renegotiation" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } #endif ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION; break; } } /* * Renegotiation security checks */ if( ssl->secure_renegotiation != MBEDTLS_SSL_SECURE_RENEGOTIATION && ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation, breaking off handshake" ) ); handshake_failure = 1; } #if defined(MBEDTLS_SSL_RENEGOTIATION) else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS && ssl->secure_renegotiation == MBEDTLS_SSL_SECURE_RENEGOTIATION && renegotiation_info_seen == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation_info extension missing (secure)" ) ); handshake_failure = 1; } else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS && ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION && ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation not allowed" ) ); handshake_failure = 1; } else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS && ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION && renegotiation_info_seen == 1 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation_info extension present (legacy)" ) ); handshake_failure = 1; } #endif /* MBEDTLS_SSL_RENEGOTIATION */ if( handshake_failure == 1 ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* * Search for a matching ciphersuite * (At the end because we need information from the EC-based extensions * and certificate from the SNI callback triggered by the SNI extension.) */ got_common_suite = 0; ciphersuites = ssl->conf->ciphersuite_list[ssl->minor_ver]; ciphersuite_info = NULL; #if defined(MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE) for( j = 0, p = buf + ciph_offset + 2; j < ciph_len; j += 2, p += 2 ) for( i = 0; ciphersuites[i] != 0; i++ ) #else for( i = 0; ciphersuites[i] != 0; i++ ) for( j = 0, p = buf + ciph_offset + 2; j < ciph_len; j += 2, p += 2 ) #endif { if( p[0] != ( ( ciphersuites[i] >> 8 ) & 0xFF ) || p[1] != ( ( ciphersuites[i] ) & 0xFF ) ) continue; got_common_suite = 1; if( ( ret = ssl_ciphersuite_match( ssl, ciphersuites[i], &ciphersuite_info ) ) != 0 ) return( ret ); if( ciphersuite_info != NULL ) goto have_ciphersuite; } if( got_common_suite ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "got ciphersuites in common, " "but none of them usable" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE ); } else { MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no ciphersuites in common" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN ); } have_ciphersuite: MBEDTLS_SSL_DEBUG_MSG( 2, ( "selected ciphersuite: %s", ciphersuite_info->name ) ); ssl->session_negotiate->ciphersuite = ciphersuites[i]; ssl->handshake->ciphersuite_info = ciphersuite_info; ssl->state++; #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) mbedtls_ssl_recv_flight_completed( ssl ); #endif /* Debugging-only output for testsuite */ #if defined(MBEDTLS_DEBUG_C) && \ defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { mbedtls_pk_type_t sig_alg = mbedtls_ssl_get_ciphersuite_sig_alg( ciphersuite_info ); if( sig_alg != MBEDTLS_PK_NONE ) { mbedtls_md_type_t md_alg = mbedtls_ssl_sig_hash_set_find( &ssl->handshake->hash_algs, sig_alg ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext: %d", mbedtls_ssl_hash_from_md_alg( md_alg ) ) ); } else { MBEDTLS_SSL_DEBUG_MSG( 3, ( "no hash algorithm for signature algorithm " "%d - should not happen", sig_alg ) ); } } #endif MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse client hello" ) ); return( 0 ); } #if defined(MBEDTLS_SSL_TRUNCATED_HMAC) static void ssl_write_truncated_hmac_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t *olen ) { unsigned char *p = buf; if( ssl->session_negotiate->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_DISABLED ) { *olen = 0; return; } MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding truncated hmac extension" ) ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_TRUNCATED_HMAC >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_TRUNCATED_HMAC ) & 0xFF ); *p++ = 0x00; *p++ = 0x00; *olen = 4; } #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */ #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) static void ssl_write_cid_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t *olen ) { unsigned char *p = buf; size_t ext_len; const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN; *olen = 0; /* Skip writing the extension if we don't want to use it or if * the client hasn't offered it. */ if( ssl->handshake->cid_in_use == MBEDTLS_SSL_CID_DISABLED ) return; /* ssl->own_cid_len is at most MBEDTLS_SSL_CID_IN_LEN_MAX * which is at most 255, so the increment cannot overflow. */ if( end < p || (size_t)( end - p ) < (unsigned)( ssl->own_cid_len + 5 ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) ); return; } MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding CID extension" ) ); /* * Quoting draft-ietf-tls-dtls-connection-id-05 * https://tools.ietf.org/html/draft-ietf-tls-dtls-connection-id-05 * * struct { * opaque cid<0..2^8-1>; * } ConnectionId; */ *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_CID >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_CID ) & 0xFF ); ext_len = (size_t) ssl->own_cid_len + 1; *p++ = (unsigned char)( ( ext_len >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( ext_len ) & 0xFF ); *p++ = (uint8_t) ssl->own_cid_len; memcpy( p, ssl->own_cid, ssl->own_cid_len ); *olen = ssl->own_cid_len + 5; } #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) static void ssl_write_encrypt_then_mac_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t *olen ) { unsigned char *p = buf; const mbedtls_ssl_ciphersuite_t *suite = NULL; const mbedtls_cipher_info_t *cipher = NULL; if( ssl->session_negotiate->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED || ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) { *olen = 0; return; } /* * RFC 7366: "If a server receives an encrypt-then-MAC request extension * from a client and then selects a stream or Authenticated Encryption * with Associated Data (AEAD) ciphersuite, it MUST NOT send an * encrypt-then-MAC response extension back to the client." */ if( ( suite = mbedtls_ssl_ciphersuite_from_id( ssl->session_negotiate->ciphersuite ) ) == NULL || ( cipher = mbedtls_cipher_info_from_type( suite->cipher ) ) == NULL || cipher->mode != MBEDTLS_MODE_CBC ) { *olen = 0; return; } MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding encrypt then mac extension" ) ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC ) & 0xFF ); *p++ = 0x00; *p++ = 0x00; *olen = 4; } #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) static void ssl_write_extended_ms_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t *olen ) { unsigned char *p = buf; if( ssl->handshake->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED || ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) { *olen = 0; return; } MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding extended master secret " "extension" ) ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET ) & 0xFF ); *p++ = 0x00; *p++ = 0x00; *olen = 4; } #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) static void ssl_write_session_ticket_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t *olen ) { unsigned char *p = buf; if( ssl->handshake->new_session_ticket == 0 ) { *olen = 0; return; } MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding session ticket extension" ) ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET ) & 0xFF ); *p++ = 0x00; *p++ = 0x00; *olen = 4; } #endif /* MBEDTLS_SSL_SESSION_TICKETS */ static void ssl_write_renegotiation_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t *olen ) { unsigned char *p = buf; if( ssl->secure_renegotiation != MBEDTLS_SSL_SECURE_RENEGOTIATION ) { *olen = 0; return; } MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, secure renegotiation extension" ) ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO ) & 0xFF ); #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ) { *p++ = 0x00; *p++ = ( ssl->verify_data_len * 2 + 1 ) & 0xFF; *p++ = ssl->verify_data_len * 2 & 0xFF; memcpy( p, ssl->peer_verify_data, ssl->verify_data_len ); p += ssl->verify_data_len; memcpy( p, ssl->own_verify_data, ssl->verify_data_len ); p += ssl->verify_data_len; } else #endif /* MBEDTLS_SSL_RENEGOTIATION */ { *p++ = 0x00; *p++ = 0x01; *p++ = 0x00; } *olen = p - buf; } #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) static void ssl_write_max_fragment_length_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t *olen ) { unsigned char *p = buf; if( ssl->session_negotiate->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE ) { *olen = 0; return; } MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, max_fragment_length extension" ) ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH ) & 0xFF ); *p++ = 0x00; *p++ = 1; *p++ = ssl->session_negotiate->mfl_code; *olen = 5; } #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) static void ssl_write_supported_point_formats_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t *olen ) { unsigned char *p = buf; ((void) ssl); if( ( ssl->handshake->cli_exts & MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT ) == 0 ) { *olen = 0; return; } MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, supported_point_formats extension" ) ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS ) & 0xFF ); *p++ = 0x00; *p++ = 2; *p++ = 1; *p++ = MBEDTLS_ECP_PF_UNCOMPRESSED; *olen = 6; } #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) static void ssl_write_ecjpake_kkpp_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t *olen ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned char *p = buf; const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN; size_t kkpp_len; *olen = 0; /* Skip costly computation if not needed */ if( ssl->handshake->ciphersuite_info->key_exchange != MBEDTLS_KEY_EXCHANGE_ECJPAKE ) return; MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, ecjpake kkpp extension" ) ); if( end - p < 4 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) ); return; } *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP ) & 0xFF ); ret = mbedtls_ecjpake_write_round_one( &ssl->handshake->ecjpake_ctx, p + 2, end - p - 2, &kkpp_len, ssl->conf->f_rng, ssl->conf->p_rng ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1 , "mbedtls_ecjpake_write_round_one", ret ); return; } *p++ = (unsigned char)( ( kkpp_len >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( kkpp_len ) & 0xFF ); *olen = kkpp_len + 4; } #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_SSL_ALPN ) static void ssl_write_alpn_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t *olen ) { if( ssl->alpn_chosen == NULL ) { *olen = 0; return; } MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding alpn extension" ) ); /* * 0 . 1 ext identifier * 2 . 3 ext length * 4 . 5 protocol list length * 6 . 6 protocol name length * 7 . 7+n protocol name */ buf[0] = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN >> 8 ) & 0xFF ); buf[1] = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN ) & 0xFF ); *olen = 7 + strlen( ssl->alpn_chosen ); buf[2] = (unsigned char)( ( ( *olen - 4 ) >> 8 ) & 0xFF ); buf[3] = (unsigned char)( ( ( *olen - 4 ) ) & 0xFF ); buf[4] = (unsigned char)( ( ( *olen - 6 ) >> 8 ) & 0xFF ); buf[5] = (unsigned char)( ( ( *olen - 6 ) ) & 0xFF ); buf[6] = (unsigned char)( ( ( *olen - 7 ) ) & 0xFF ); memcpy( buf + 7, ssl->alpn_chosen, *olen - 7 ); } #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C */ #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) static int ssl_write_hello_verify_request( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned char *p = ssl->out_msg + 4; unsigned char *cookie_len_byte; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write hello verify request" ) ); /* * struct { * ProtocolVersion server_version; * opaque cookie<0..2^8-1>; * } HelloVerifyRequest; */ /* The RFC is not clear on this point, but sending the actual negotiated * version looks like the most interoperable thing to do. */ mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver, ssl->conf->transport, p ); MBEDTLS_SSL_DEBUG_BUF( 3, "server version", p, 2 ); p += 2; /* If we get here, f_cookie_check is not null */ if( ssl->conf->f_cookie_write == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "inconsistent cookie callbacks" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } /* Skip length byte until we know the length */ cookie_len_byte = p++; if( ( ret = ssl->conf->f_cookie_write( ssl->conf->p_cookie, &p, ssl->out_buf + MBEDTLS_SSL_OUT_BUFFER_LEN, ssl->cli_id, ssl->cli_id_len ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "f_cookie_write", ret ); return( ret ); } *cookie_len_byte = (unsigned char)( p - ( cookie_len_byte + 1 ) ); MBEDTLS_SSL_DEBUG_BUF( 3, "cookie sent", cookie_len_byte + 1, *cookie_len_byte ); ssl->out_msglen = p - ssl->out_msg; ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST; ssl->state = MBEDTLS_SSL_SERVER_HELLO_VERIFY_REQUEST_SENT; if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret ); return( ret ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flight_transmit", ret ); return( ret ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write hello verify request" ) ); return( 0 ); } #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */ static int ssl_write_server_hello( mbedtls_ssl_context *ssl ) { #if defined(MBEDTLS_HAVE_TIME) mbedtls_time_t t; #endif int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t olen, ext_len = 0, n; unsigned char *buf, *p; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write server hello" ) ); #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ssl->handshake->verify_cookie_len != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "client hello was not authenticated" ) ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server hello" ) ); return( ssl_write_hello_verify_request( ssl ) ); } #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */ if( ssl->conf->f_rng == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "no RNG provided") ); return( MBEDTLS_ERR_SSL_NO_RNG ); } /* * 0 . 0 handshake type * 1 . 3 handshake length * 4 . 5 protocol version * 6 . 9 UNIX time() * 10 . 37 random bytes */ buf = ssl->out_msg; p = buf + 4; mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver, ssl->conf->transport, p ); p += 2; MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen version: [%d:%d]", buf[4], buf[5] ) ); #if defined(MBEDTLS_HAVE_TIME) t = mbedtls_time( NULL ); *p++ = (unsigned char)( t >> 24 ); *p++ = (unsigned char)( t >> 16 ); *p++ = (unsigned char)( t >> 8 ); *p++ = (unsigned char)( t ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, current time: %lu", t ) ); #else if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 4 ) ) != 0 ) return( ret ); p += 4; #endif /* MBEDTLS_HAVE_TIME */ if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 28 ) ) != 0 ) return( ret ); p += 28; memcpy( ssl->handshake->randbytes + 32, buf + 6, 32 ); MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, random bytes", buf + 6, 32 ); /* * Resume is 0 by default, see ssl_handshake_init(). * It may be already set to 1 by ssl_parse_session_ticket_ext(). * If not, try looking up session ID in our cache. */ if( ssl->handshake->resume == 0 && #if defined(MBEDTLS_SSL_RENEGOTIATION) ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE && #endif ssl->session_negotiate->id_len != 0 && ssl->conf->f_get_cache != NULL && ssl->conf->f_get_cache( ssl->conf->p_cache, ssl->session_negotiate ) == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "session successfully restored from cache" ) ); ssl->handshake->resume = 1; } if( ssl->handshake->resume == 0 ) { /* * New session, create a new session id, * unless we're about to issue a session ticket */ ssl->state++; #if defined(MBEDTLS_HAVE_TIME) ssl->session_negotiate->start = mbedtls_time( NULL ); #endif #if defined(MBEDTLS_SSL_SESSION_TICKETS) if( ssl->handshake->new_session_ticket != 0 ) { ssl->session_negotiate->id_len = n = 0; memset( ssl->session_negotiate->id, 0, 32 ); } else #endif /* MBEDTLS_SSL_SESSION_TICKETS */ { ssl->session_negotiate->id_len = n = 32; if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, ssl->session_negotiate->id, n ) ) != 0 ) return( ret ); } } else { /* * Resuming a session */ n = ssl->session_negotiate->id_len; ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC; if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret ); return( ret ); } } /* * 38 . 38 session id length * 39 . 38+n session id * 39+n . 40+n chosen ciphersuite * 41+n . 41+n chosen compression alg. * 42+n . 43+n extensions length * 44+n . 43+n+m extensions */ *p++ = (unsigned char) ssl->session_negotiate->id_len; memcpy( p, ssl->session_negotiate->id, ssl->session_negotiate->id_len ); p += ssl->session_negotiate->id_len; MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, session id len.: %d", n ) ); MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, session id", buf + 39, n ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "%s session has been resumed", ssl->handshake->resume ? "a" : "no" ) ); *p++ = (unsigned char)( ssl->session_negotiate->ciphersuite >> 8 ); *p++ = (unsigned char)( ssl->session_negotiate->ciphersuite ); *p++ = (unsigned char)( ssl->session_negotiate->compression ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %s", mbedtls_ssl_get_ciphersuite_name( ssl->session_negotiate->ciphersuite ) ) ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, compress alg.: 0x%02X", ssl->session_negotiate->compression ) ); /* Do not write the extensions if the protocol is SSLv3 */ #if defined(MBEDTLS_SSL_PROTO_SSL3) if( ( ssl->major_ver != 3 ) || ( ssl->minor_ver != 0 ) ) { #endif /* * First write extensions, then the total length */ ssl_write_renegotiation_ext( ssl, p + 2 + ext_len, &olen ); ext_len += olen; #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) ssl_write_max_fragment_length_ext( ssl, p + 2 + ext_len, &olen ); ext_len += olen; #endif #if defined(MBEDTLS_SSL_TRUNCATED_HMAC) ssl_write_truncated_hmac_ext( ssl, p + 2 + ext_len, &olen ); ext_len += olen; #endif #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) ssl_write_cid_ext( ssl, p + 2 + ext_len, &olen ); ext_len += olen; #endif #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) ssl_write_encrypt_then_mac_ext( ssl, p + 2 + ext_len, &olen ); ext_len += olen; #endif #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) ssl_write_extended_ms_ext( ssl, p + 2 + ext_len, &olen ); ext_len += olen; #endif #if defined(MBEDTLS_SSL_SESSION_TICKETS) ssl_write_session_ticket_ext( ssl, p + 2 + ext_len, &olen ); ext_len += olen; #endif #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) if ( mbedtls_ssl_ciphersuite_uses_ec( mbedtls_ssl_ciphersuite_from_id( ssl->session_negotiate->ciphersuite ) ) ) { ssl_write_supported_point_formats_ext( ssl, p + 2 + ext_len, &olen ); ext_len += olen; } #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) ssl_write_ecjpake_kkpp_ext( ssl, p + 2 + ext_len, &olen ); ext_len += olen; #endif #if defined(MBEDTLS_SSL_ALPN) ssl_write_alpn_ext( ssl, p + 2 + ext_len, &olen ); ext_len += olen; #endif MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, total extension length: %d", ext_len ) ); if( ext_len > 0 ) { *p++ = (unsigned char)( ( ext_len >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( ext_len ) & 0xFF ); p += ext_len; } #if defined(MBEDTLS_SSL_PROTO_SSL3) } #endif ssl->out_msglen = p - buf; ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_SERVER_HELLO; ret = mbedtls_ssl_write_handshake_msg( ssl ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server hello" ) ); return( ret ); } #if !defined(MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED) static int ssl_write_certificate_request( mbedtls_ssl_context *ssl ) { const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate request" ) ); if( !mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate request" ) ); ssl->state++; return( 0 ); } MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #else /* !MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */ static int ssl_write_certificate_request( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; uint16_t dn_size, total_dn_size; /* excluding length bytes */ size_t ct_len, sa_len; /* including length bytes */ unsigned char *buf, *p; const unsigned char * const end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN; const mbedtls_x509_crt *crt; int authmode; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate request" ) ); ssl->state++; #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) if( ssl->handshake->sni_authmode != MBEDTLS_SSL_VERIFY_UNSET ) authmode = ssl->handshake->sni_authmode; else #endif authmode = ssl->conf->authmode; if( !mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) || authmode == MBEDTLS_SSL_VERIFY_NONE ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate request" ) ); return( 0 ); } /* * 0 . 0 handshake type * 1 . 3 handshake length * 4 . 4 cert type count * 5 .. m-1 cert types * m .. m+1 sig alg length (TLS 1.2 only) * m+1 .. n-1 SignatureAndHashAlgorithms (TLS 1.2 only) * n .. n+1 length of all DNs * n+2 .. n+3 length of DN 1 * n+4 .. ... Distinguished Name #1 * ... .. ... length of DN 2, etc. */ buf = ssl->out_msg; p = buf + 4; /* * Supported certificate types * * ClientCertificateType certificate_types<1..2^8-1>; * enum { (255) } ClientCertificateType; */ ct_len = 0; #if defined(MBEDTLS_RSA_C) p[1 + ct_len++] = MBEDTLS_SSL_CERT_TYPE_RSA_SIGN; #endif #if defined(MBEDTLS_ECDSA_C) p[1 + ct_len++] = MBEDTLS_SSL_CERT_TYPE_ECDSA_SIGN; #endif p[0] = (unsigned char) ct_len++; p += ct_len; sa_len = 0; #if defined(MBEDTLS_SSL_PROTO_TLS1_2) /* * Add signature_algorithms for verify (TLS 1.2) * * SignatureAndHashAlgorithm supported_signature_algorithms<2..2^16-2>; * * struct { * HashAlgorithm hash; * SignatureAlgorithm signature; * } SignatureAndHashAlgorithm; * * enum { (255) } HashAlgorithm; * enum { (255) } SignatureAlgorithm; */ if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { const int *cur; /* * Supported signature algorithms */ for( cur = ssl->conf->sig_hashes; *cur != MBEDTLS_MD_NONE; cur++ ) { unsigned char hash = mbedtls_ssl_hash_from_md_alg( *cur ); if( MBEDTLS_SSL_HASH_NONE == hash || mbedtls_ssl_set_calc_verify_md( ssl, hash ) ) continue; #if defined(MBEDTLS_RSA_C) p[2 + sa_len++] = hash; p[2 + sa_len++] = MBEDTLS_SSL_SIG_RSA; #endif #if defined(MBEDTLS_ECDSA_C) p[2 + sa_len++] = hash; p[2 + sa_len++] = MBEDTLS_SSL_SIG_ECDSA; #endif } p[0] = (unsigned char)( sa_len >> 8 ); p[1] = (unsigned char)( sa_len ); sa_len += 2; p += sa_len; } #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ /* * DistinguishedName certificate_authorities<0..2^16-1>; * opaque DistinguishedName<1..2^16-1>; */ p += 2; total_dn_size = 0; if( ssl->conf->cert_req_ca_list == MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED ) { /* NOTE: If trusted certificates are provisioned * via a CA callback (configured through * `mbedtls_ssl_conf_ca_cb()`, then the * CertificateRequest is currently left empty. */ #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) if( ssl->handshake->sni_ca_chain != NULL ) crt = ssl->handshake->sni_ca_chain; else #endif crt = ssl->conf->ca_chain; while( crt != NULL && crt->version != 0 ) { /* It follows from RFC 5280 A.1 that this length * can be represented in at most 11 bits. */ dn_size = (uint16_t) crt->subject_raw.len; if( end < p || (size_t)( end - p ) < 2 + (size_t) dn_size ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "skipping CAs: buffer too short" ) ); break; } *p++ = (unsigned char)( dn_size >> 8 ); *p++ = (unsigned char)( dn_size ); memcpy( p, crt->subject_raw.p, dn_size ); p += dn_size; MBEDTLS_SSL_DEBUG_BUF( 3, "requested DN", p - dn_size, dn_size ); total_dn_size += 2 + dn_size; crt = crt->next; } } ssl->out_msglen = p - buf; ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_CERTIFICATE_REQUEST; ssl->out_msg[4 + ct_len + sa_len] = (unsigned char)( total_dn_size >> 8 ); ssl->out_msg[5 + ct_len + sa_len] = (unsigned char)( total_dn_size ); ret = mbedtls_ssl_write_handshake_msg( ssl ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write certificate request" ) ); return( ret ); } #endif /* MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) static int ssl_get_ecdh_params_from_cert( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; if( ! mbedtls_pk_can_do( mbedtls_ssl_own_key( ssl ), MBEDTLS_PK_ECKEY ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "server key not ECDH capable" ) ); return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH ); } if( ( ret = mbedtls_ecdh_get_params( &ssl->handshake->ecdh_ctx, mbedtls_pk_ec( *mbedtls_ssl_own_key( ssl ) ), MBEDTLS_ECDH_OURS ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ecdh_get_params" ), ret ); return( ret ); } return( 0 ); } #endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) && \ defined(MBEDTLS_SSL_ASYNC_PRIVATE) static int ssl_resume_server_key_exchange( mbedtls_ssl_context *ssl, size_t *signature_len ) { /* Append the signature to ssl->out_msg, leaving 2 bytes for the * signature length which will be added in ssl_write_server_key_exchange * after the call to ssl_prepare_server_key_exchange. * ssl_write_server_key_exchange also takes care of incrementing * ssl->out_msglen. */ unsigned char *sig_start = ssl->out_msg + ssl->out_msglen + 2; size_t sig_max_len = ( ssl->out_buf + MBEDTLS_SSL_OUT_CONTENT_LEN - sig_start ); int ret = ssl->conf->f_async_resume( ssl, sig_start, signature_len, sig_max_len ); if( ret != MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS ) { ssl->handshake->async_in_progress = 0; mbedtls_ssl_set_async_operation_data( ssl, NULL ); } MBEDTLS_SSL_DEBUG_RET( 2, "ssl_resume_server_key_exchange", ret ); return( ret ); } #endif /* defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) && defined(MBEDTLS_SSL_ASYNC_PRIVATE) */ /* Prepare the ServerKeyExchange message, up to and including * calculating the signature if any, but excluding formatting the * signature and sending the message. */ static int ssl_prepare_server_key_exchange( mbedtls_ssl_context *ssl, size_t *signature_len ) { const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PFS_ENABLED) #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) unsigned char *dig_signed = NULL; #endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */ #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PFS_ENABLED */ (void) ciphersuite_info; /* unused in some configurations */ #if !defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) (void) signature_len; #endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */ ssl->out_msglen = 4; /* header (type:1, length:3) to be written later */ /* * * Part 1: Provide key exchange parameters for chosen ciphersuite. * */ /* * - ECJPAKE key exchanges */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t len = 0; ret = mbedtls_ecjpake_write_round_two( &ssl->handshake->ecjpake_ctx, ssl->out_msg + ssl->out_msglen, MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen, &len, ssl->conf->f_rng, ssl->conf->p_rng ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_write_round_two", ret ); return( ret ); } ssl->out_msglen += len; } #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ /* * For (EC)DHE key exchanges with PSK, parameters are prefixed by support * identity hint (RFC 4279, Sec. 3). Until someone needs this feature, * we use empty support identity hints here. **/ #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ) { ssl->out_msg[ssl->out_msglen++] = 0x00; ssl->out_msg[ssl->out_msglen++] = 0x00; } #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */ /* * - DHE key exchanges */ #if defined(MBEDTLS_KEY_EXCHANGE_SOME_DHE_ENABLED) if( mbedtls_ssl_ciphersuite_uses_dhe( ciphersuite_info ) ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t len = 0; if( ssl->conf->dhm_P.p == NULL || ssl->conf->dhm_G.p == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "no DH parameters set" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } /* * Ephemeral DH parameters: * * struct { * opaque dh_p<1..2^16-1>; * opaque dh_g<1..2^16-1>; * opaque dh_Ys<1..2^16-1>; * } ServerDHParams; */ if( ( ret = mbedtls_dhm_set_group( &ssl->handshake->dhm_ctx, &ssl->conf->dhm_P, &ssl->conf->dhm_G ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_set_group", ret ); return( ret ); } if( ( ret = mbedtls_dhm_make_params( &ssl->handshake->dhm_ctx, (int) mbedtls_mpi_size( &ssl->handshake->dhm_ctx.P ), ssl->out_msg + ssl->out_msglen, &len, ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_make_params", ret ); return( ret ); } #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) dig_signed = ssl->out_msg + ssl->out_msglen; #endif ssl->out_msglen += len; MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: X ", &ssl->handshake->dhm_ctx.X ); MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: P ", &ssl->handshake->dhm_ctx.P ); MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: G ", &ssl->handshake->dhm_ctx.G ); MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GX", &ssl->handshake->dhm_ctx.GX ); } #endif /* MBEDTLS_KEY_EXCHANGE_SOME_DHE_ENABLED */ /* * - ECDHE key exchanges */ #if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDHE_ENABLED) if( mbedtls_ssl_ciphersuite_uses_ecdhe( ciphersuite_info ) ) { /* * Ephemeral ECDH parameters: * * struct { * ECParameters curve_params; * ECPoint public; * } ServerECDHParams; */ const mbedtls_ecp_curve_info **curve = NULL; const mbedtls_ecp_group_id *gid; int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t len = 0; /* Match our preference list against the offered curves */ for( gid = ssl->conf->curve_list; *gid != MBEDTLS_ECP_DP_NONE; gid++ ) for( curve = ssl->handshake->curves; *curve != NULL; curve++ ) if( (*curve)->grp_id == *gid ) goto curve_matching_done; curve_matching_done: if( curve == NULL || *curve == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "no matching curve for ECDHE" ) ); return( MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "ECDHE curve: %s", (*curve)->name ) ); if( ( ret = mbedtls_ecdh_setup( &ssl->handshake->ecdh_ctx, (*curve)->grp_id ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecp_group_load", ret ); return( ret ); } if( ( ret = mbedtls_ecdh_make_params( &ssl->handshake->ecdh_ctx, &len, ssl->out_msg + ssl->out_msglen, MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen, ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_make_params", ret ); return( ret ); } #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) dig_signed = ssl->out_msg + ssl->out_msglen; #endif ssl->out_msglen += len; MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx, MBEDTLS_DEBUG_ECDH_Q ); } #endif /* MBEDTLS_KEY_EXCHANGE_SOME_ECDHE_ENABLED */ /* * * Part 2: For key exchanges involving the server signing the * exchange parameters, compute and add the signature here. * */ #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) if( mbedtls_ssl_ciphersuite_uses_server_signature( ciphersuite_info ) ) { size_t dig_signed_len = ssl->out_msg + ssl->out_msglen - dig_signed; size_t hashlen = 0; unsigned char hash[MBEDTLS_MD_MAX_SIZE]; int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; /* * 2.1: Choose hash algorithm: * A: For TLS 1.2, obey signature-hash-algorithm extension * to choose appropriate hash. * B: For SSL3, TLS1.0, TLS1.1 and ECDHE_ECDSA, use SHA1 * (RFC 4492, Sec. 5.4) * C: Otherwise, use MD5 + SHA1 (RFC 4346, Sec. 7.4.3) */ mbedtls_md_type_t md_alg; #if defined(MBEDTLS_SSL_PROTO_TLS1_2) mbedtls_pk_type_t sig_alg = mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info ); if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { /* A: For TLS 1.2, obey signature-hash-algorithm extension * (RFC 5246, Sec. 7.4.1.4.1). */ if( sig_alg == MBEDTLS_PK_NONE || ( md_alg = mbedtls_ssl_sig_hash_set_find( &ssl->handshake->hash_algs, sig_alg ) ) == MBEDTLS_MD_NONE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); /* (... because we choose a cipher suite * only if there is a matching hash.) */ return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } } else #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA ) { /* B: Default hash SHA1 */ md_alg = MBEDTLS_MD_SHA1; } else #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \ MBEDTLS_SSL_PROTO_TLS1_1 */ { /* C: MD5 + SHA1 */ md_alg = MBEDTLS_MD_NONE; } MBEDTLS_SSL_DEBUG_MSG( 3, ( "pick hash algorithm %d for signing", md_alg ) ); /* * 2.2: Compute the hash to be signed */ #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) if( md_alg == MBEDTLS_MD_NONE ) { hashlen = 36; ret = mbedtls_ssl_get_key_exchange_md_ssl_tls( ssl, hash, dig_signed, dig_signed_len ); if( ret != 0 ) return( ret ); } else #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \ MBEDTLS_SSL_PROTO_TLS1_1 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_2) if( md_alg != MBEDTLS_MD_NONE ) { ret = mbedtls_ssl_get_key_exchange_md_tls1_2( ssl, hash, &hashlen, dig_signed, dig_signed_len, md_alg ); if( ret != 0 ) return( ret ); } else #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \ MBEDTLS_SSL_PROTO_TLS1_2 */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } MBEDTLS_SSL_DEBUG_BUF( 3, "parameters hash", hash, hashlen ); /* * 2.3: Compute and add the signature */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { /* * For TLS 1.2, we need to specify signature and hash algorithm * explicitly through a prefix to the signature. * * struct { * HashAlgorithm hash; * SignatureAlgorithm signature; * } SignatureAndHashAlgorithm; * * struct { * SignatureAndHashAlgorithm algorithm; * opaque signature<0..2^16-1>; * } DigitallySigned; * */ ssl->out_msg[ssl->out_msglen++] = mbedtls_ssl_hash_from_md_alg( md_alg ); ssl->out_msg[ssl->out_msglen++] = mbedtls_ssl_sig_from_pk_alg( sig_alg ); } #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ #if defined(MBEDTLS_SSL_ASYNC_PRIVATE) if( ssl->conf->f_async_sign_start != NULL ) { ret = ssl->conf->f_async_sign_start( ssl, mbedtls_ssl_own_cert( ssl ), md_alg, hash, hashlen ); switch( ret ) { case MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH: /* act as if f_async_sign was null */ break; case 0: ssl->handshake->async_in_progress = 1; return( ssl_resume_server_key_exchange( ssl, signature_len ) ); case MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS: ssl->handshake->async_in_progress = 1; return( MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS ); default: MBEDTLS_SSL_DEBUG_RET( 1, "f_async_sign_start", ret ); return( ret ); } } #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ if( mbedtls_ssl_own_key( ssl ) == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no private key" ) ); return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED ); } /* Append the signature to ssl->out_msg, leaving 2 bytes for the * signature length which will be added in ssl_write_server_key_exchange * after the call to ssl_prepare_server_key_exchange. * ssl_write_server_key_exchange also takes care of incrementing * ssl->out_msglen. */ if( ( ret = mbedtls_pk_sign( mbedtls_ssl_own_key( ssl ), md_alg, hash, hashlen, ssl->out_msg + ssl->out_msglen + 2, signature_len, ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_sign", ret ); return( ret ); } } #endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */ return( 0 ); } /* Prepare the ServerKeyExchange message and send it. For ciphersuites * that do not include a ServerKeyExchange message, do nothing. Either * way, if successful, move on to the next step in the SSL state * machine. */ static int ssl_write_server_key_exchange( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t signature_len = 0; #if defined(MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED) const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; #endif /* MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED */ MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write server key exchange" ) ); #if defined(MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED) /* Extract static ECDH parameters and abort if ServerKeyExchange * is not needed. */ if( mbedtls_ssl_ciphersuite_no_pfs( ciphersuite_info ) ) { /* For suites involving ECDH, extract DH parameters * from certificate at this point. */ #if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDH_ENABLED) if( mbedtls_ssl_ciphersuite_uses_ecdh( ciphersuite_info ) ) { ssl_get_ecdh_params_from_cert( ssl ); } #endif /* MBEDTLS_KEY_EXCHANGE_SOME_ECDH_ENABLED */ /* Key exchanges not involving ephemeral keys don't use * ServerKeyExchange, so end here. */ MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write server key exchange" ) ); ssl->state++; return( 0 ); } #endif /* MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) && \ defined(MBEDTLS_SSL_ASYNC_PRIVATE) /* If we have already prepared the message and there is an ongoing * signature operation, resume signing. */ if( ssl->handshake->async_in_progress != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "resuming signature operation" ) ); ret = ssl_resume_server_key_exchange( ssl, &signature_len ); } else #endif /* defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) && defined(MBEDTLS_SSL_ASYNC_PRIVATE) */ { /* ServerKeyExchange is needed. Prepare the message. */ ret = ssl_prepare_server_key_exchange( ssl, &signature_len ); } if( ret != 0 ) { /* If we're starting to write a new message, set ssl->out_msglen * to 0. But if we're resuming after an asynchronous message, * out_msglen is the amount of data written so far and mst be * preserved. */ if( ret == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS ) MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server key exchange (pending)" ) ); else ssl->out_msglen = 0; return( ret ); } /* If there is a signature, write its length. * ssl_prepare_server_key_exchange already wrote the signature * itself at its proper place in the output buffer. */ #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) if( signature_len != 0 ) { ssl->out_msg[ssl->out_msglen++] = (unsigned char)( signature_len >> 8 ); ssl->out_msg[ssl->out_msglen++] = (unsigned char)( signature_len ); MBEDTLS_SSL_DEBUG_BUF( 3, "my signature", ssl->out_msg + ssl->out_msglen, signature_len ); /* Skip over the already-written signature */ ssl->out_msglen += signature_len; } #endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */ /* Add header and send. */ ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE; ssl->state++; if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server key exchange" ) ); return( 0 ); } static int ssl_write_server_hello_done( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write server hello done" ) ); ssl->out_msglen = 4; ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_SERVER_HELLO_DONE; ssl->state++; #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) mbedtls_ssl_send_flight_completed( ssl ); #endif if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret ); return( ret ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flight_transmit", ret ); return( ret ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server hello done" ) ); return( 0 ); } #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) static int ssl_parse_client_dh_public( mbedtls_ssl_context *ssl, unsigned char **p, const unsigned char *end ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; size_t n; /* * Receive G^Y mod P, premaster = (G^Y)^X mod P */ if( *p + 2 > end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } n = ( (*p)[0] << 8 ) | (*p)[1]; *p += 2; if( *p + n > end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } if( ( ret = mbedtls_dhm_read_public( &ssl->handshake->dhm_ctx, *p, n ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_read_public", ret ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP ); } *p += n; MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GY", &ssl->handshake->dhm_ctx.GY ); return( ret ); } #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) #if defined(MBEDTLS_SSL_ASYNC_PRIVATE) static int ssl_resume_decrypt_pms( mbedtls_ssl_context *ssl, unsigned char *peer_pms, size_t *peer_pmslen, size_t peer_pmssize ) { int ret = ssl->conf->f_async_resume( ssl, peer_pms, peer_pmslen, peer_pmssize ); if( ret != MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS ) { ssl->handshake->async_in_progress = 0; mbedtls_ssl_set_async_operation_data( ssl, NULL ); } MBEDTLS_SSL_DEBUG_RET( 2, "ssl_decrypt_encrypted_pms", ret ); return( ret ); } #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ static int ssl_decrypt_encrypted_pms( mbedtls_ssl_context *ssl, const unsigned char *p, const unsigned char *end, unsigned char *peer_pms, size_t *peer_pmslen, size_t peer_pmssize ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; mbedtls_pk_context *private_key = mbedtls_ssl_own_key( ssl ); mbedtls_pk_context *public_key = &mbedtls_ssl_own_cert( ssl )->pk; size_t len = mbedtls_pk_get_len( public_key ); #if defined(MBEDTLS_SSL_ASYNC_PRIVATE) /* If we have already started decoding the message and there is an ongoing * decryption operation, resume signing. */ if( ssl->handshake->async_in_progress != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "resuming decryption operation" ) ); return( ssl_resume_decrypt_pms( ssl, peer_pms, peer_pmslen, peer_pmssize ) ); } #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ /* * Prepare to decrypt the premaster using own private RSA key */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0 ) { if ( p + 2 > end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } if( *p++ != ( ( len >> 8 ) & 0xFF ) || *p++ != ( ( len ) & 0xFF ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } } #endif if( p + len != end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } /* * Decrypt the premaster secret */ #if defined(MBEDTLS_SSL_ASYNC_PRIVATE) if( ssl->conf->f_async_decrypt_start != NULL ) { ret = ssl->conf->f_async_decrypt_start( ssl, mbedtls_ssl_own_cert( ssl ), p, len ); switch( ret ) { case MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH: /* act as if f_async_decrypt_start was null */ break; case 0: ssl->handshake->async_in_progress = 1; return( ssl_resume_decrypt_pms( ssl, peer_pms, peer_pmslen, peer_pmssize ) ); case MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS: ssl->handshake->async_in_progress = 1; return( MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS ); default: MBEDTLS_SSL_DEBUG_RET( 1, "f_async_decrypt_start", ret ); return( ret ); } } #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ if( ! mbedtls_pk_can_do( private_key, MBEDTLS_PK_RSA ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no RSA private key" ) ); return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED ); } ret = mbedtls_pk_decrypt( private_key, p, len, peer_pms, peer_pmslen, peer_pmssize, ssl->conf->f_rng, ssl->conf->p_rng ); return( ret ); } static int ssl_parse_encrypted_pms( mbedtls_ssl_context *ssl, const unsigned char *p, const unsigned char *end, size_t pms_offset ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned char *pms = ssl->handshake->premaster + pms_offset; unsigned char ver[2]; unsigned char fake_pms[48], peer_pms[48]; unsigned char mask; size_t i, peer_pmslen; unsigned int diff; /* In case of a failure in decryption, the decryption may write less than * 2 bytes of output, but we always read the first two bytes. It doesn't * matter in the end because diff will be nonzero in that case due to * peer_pmslen being less than 48, and we only care whether diff is 0. * But do initialize peer_pms for robustness anyway. This also makes * memory analyzers happy (don't access uninitialized memory, even * if it's an unsigned char). */ peer_pms[0] = peer_pms[1] = ~0; ret = ssl_decrypt_encrypted_pms( ssl, p, end, peer_pms, &peer_pmslen, sizeof( peer_pms ) ); #if defined(MBEDTLS_SSL_ASYNC_PRIVATE) if ( ret == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS ) return( ret ); #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ mbedtls_ssl_write_version( ssl->handshake->max_major_ver, ssl->handshake->max_minor_ver, ssl->conf->transport, ver ); /* Avoid data-dependent branches while checking for invalid * padding, to protect against timing-based Bleichenbacher-type * attacks. */ diff = (unsigned int) ret; diff |= peer_pmslen ^ 48; diff |= peer_pms[0] ^ ver[0]; diff |= peer_pms[1] ^ ver[1]; /* mask = diff ? 0xff : 0x00 using bit operations to avoid branches */ /* MSVC has a warning about unary minus on unsigned, but this is * well-defined and precisely what we want to do here */ #if defined(_MSC_VER) #pragma warning( push ) #pragma warning( disable : 4146 ) #endif mask = - ( ( diff | - diff ) >> ( sizeof( unsigned int ) * 8 - 1 ) ); #if defined(_MSC_VER) #pragma warning( pop ) #endif /* * Protection against Bleichenbacher's attack: invalid PKCS#1 v1.5 padding * must not cause the connection to end immediately; instead, send a * bad_record_mac later in the handshake. * To protect against timing-based variants of the attack, we must * not have any branch that depends on whether the decryption was * successful. In particular, always generate the fake premaster secret, * regardless of whether it will ultimately influence the output or not. */ ret = ssl->conf->f_rng( ssl->conf->p_rng, fake_pms, sizeof( fake_pms ) ); if( ret != 0 ) { /* It's ok to abort on an RNG failure, since this does not reveal * anything about the RSA decryption. */ return( ret ); } #if defined(MBEDTLS_SSL_DEBUG_ALL) if( diff != 0 ) MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); #endif if( sizeof( ssl->handshake->premaster ) < pms_offset || sizeof( ssl->handshake->premaster ) - pms_offset < 48 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } ssl->handshake->pmslen = 48; /* Set pms to either the true or the fake PMS, without * data-dependent branches. */ for( i = 0; i < ssl->handshake->pmslen; i++ ) pms[i] = ( mask & fake_pms[i] ) | ( (~mask) & peer_pms[i] ); return( 0 ); } #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) static int ssl_parse_client_psk_identity( mbedtls_ssl_context *ssl, unsigned char **p, const unsigned char *end ) { int ret = 0; uint16_t n; if( ssl_conf_has_psk_or_cb( ssl->conf ) == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no pre-shared key" ) ); return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED ); } /* * Receive client pre-shared key identity name */ if( end - *p < 2 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } n = ( (*p)[0] << 8 ) | (*p)[1]; *p += 2; if( n == 0 || n > end - *p ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } if( ssl->conf->f_psk != NULL ) { if( ssl->conf->f_psk( ssl->conf->p_psk, ssl, *p, n ) != 0 ) ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY; } else { /* Identity is not a big secret since clients send it in the clear, * but treat it carefully anyway, just in case */ if( n != ssl->conf->psk_identity_len || mbedtls_ssl_safer_memcmp( ssl->conf->psk_identity, *p, n ) != 0 ) { ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY; } } if( ret == MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY ) { MBEDTLS_SSL_DEBUG_BUF( 3, "Unknown PSK identity", *p, n ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY ); return( MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY ); } *p += n; return( 0 ); } #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */ static int ssl_parse_client_key_exchange( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; const mbedtls_ssl_ciphersuite_t *ciphersuite_info; unsigned char *p, *end; ciphersuite_info = ssl->handshake->ciphersuite_info; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse client key exchange" ) ); #if defined(MBEDTLS_SSL_ASYNC_PRIVATE) && \ ( defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) ) if( ( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA ) && ( ssl->handshake->async_in_progress != 0 ) ) { /* We've already read a record and there is an asynchronous * operation in progress to decrypt it. So skip reading the * record. */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "will resume decryption of previously-read record" ) ); } else #endif if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); return( ret ); } p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ); end = ssl->in_msg + ssl->in_hslen; if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } if( ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_KEY_EXCHANGE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA ) { if( ( ret = ssl_parse_client_dh_public( ssl, &p, end ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_dh_public" ), ret ); return( ret ); } if( p != end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx, ssl->handshake->premaster, MBEDTLS_PREMASTER_SIZE, &ssl->handshake->pmslen, ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS ); } MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K ); } else #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA ) { if( ( ret = mbedtls_ecdh_read_public( &ssl->handshake->ecdh_ctx, p, end - p) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_read_public", ret ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP ); } MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx, MBEDTLS_DEBUG_ECDH_QP ); if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx, &ssl->handshake->pmslen, ssl->handshake->premaster, MBEDTLS_MPI_MAX_SIZE, ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_calc_secret", ret ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS ); } MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx, MBEDTLS_DEBUG_ECDH_Z ); } else #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ) { if( ( ret = ssl_parse_client_psk_identity( ssl, &p, end ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_psk_identity" ), ret ); return( ret ); } if( p != end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } #if defined(MBEDTLS_USE_PSA_CRYPTO) /* For opaque PSKs, we perform the PSK-to-MS derivation atomatically * and skip the intermediate PMS. */ if( ssl_use_opaque_psk( ssl ) == 1 ) MBEDTLS_SSL_DEBUG_MSG( 1, ( "skip PMS generation for opaque PSK" ) ); else #endif /* MBEDTLS_USE_PSA_CRYPTO */ if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl, ciphersuite_info->key_exchange ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret ); return( ret ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ) { #if defined(MBEDTLS_SSL_ASYNC_PRIVATE) if ( ssl->handshake->async_in_progress != 0 ) { /* There is an asynchronous operation in progress to * decrypt the encrypted premaster secret, so skip * directly to resuming this operation. */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "PSK identity already parsed" ) ); /* Update p to skip the PSK identity. ssl_parse_encrypted_pms * won't actually use it, but maintain p anyway for robustness. */ p += ssl->conf->psk_identity_len + 2; } else #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ if( ( ret = ssl_parse_client_psk_identity( ssl, &p, end ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_psk_identity" ), ret ); return( ret ); } #if defined(MBEDTLS_USE_PSA_CRYPTO) /* Opaque PSKs are currently only supported for PSK-only. */ if( ssl_use_opaque_psk( ssl ) == 1 ) return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); #endif if( ( ret = ssl_parse_encrypted_pms( ssl, p, end, 2 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_encrypted_pms" ), ret ); return( ret ); } if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl, ciphersuite_info->key_exchange ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret ); return( ret ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ) { if( ( ret = ssl_parse_client_psk_identity( ssl, &p, end ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_psk_identity" ), ret ); return( ret ); } if( ( ret = ssl_parse_client_dh_public( ssl, &p, end ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_dh_public" ), ret ); return( ret ); } #if defined(MBEDTLS_USE_PSA_CRYPTO) /* Opaque PSKs are currently only supported for PSK-only. */ if( ssl_use_opaque_psk( ssl ) == 1 ) return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); #endif if( p != end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl, ciphersuite_info->key_exchange ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret ); return( ret ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ) { if( ( ret = ssl_parse_client_psk_identity( ssl, &p, end ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_psk_identity" ), ret ); return( ret ); } if( ( ret = mbedtls_ecdh_read_public( &ssl->handshake->ecdh_ctx, p, end - p ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_read_public", ret ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP ); } #if defined(MBEDTLS_USE_PSA_CRYPTO) /* Opaque PSKs are currently only supported for PSK-only. */ if( ssl_use_opaque_psk( ssl ) == 1 ) return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); #endif MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx, MBEDTLS_DEBUG_ECDH_QP ); if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl, ciphersuite_info->key_exchange ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret ); return( ret ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA ) { if( ( ret = ssl_parse_encrypted_pms( ssl, p, end, 0 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_parse_encrypted_pms_secret" ), ret ); return( ret ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ) { ret = mbedtls_ecjpake_read_round_two( &ssl->handshake->ecjpake_ctx, p, end - p ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_two", ret ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } ret = mbedtls_ecjpake_derive_secret( &ssl->handshake->ecjpake_ctx, ssl->handshake->premaster, 32, &ssl->handshake->pmslen, ssl->conf->f_rng, ssl->conf->p_rng ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_derive_secret", ret ); return( ret ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret ); return( ret ); } ssl->state++; MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse client key exchange" ) ); return( 0 ); } #if !defined(MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED) static int ssl_parse_certificate_verify( mbedtls_ssl_context *ssl ) { const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate verify" ) ); if( !mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate verify" ) ); ssl->state++; return( 0 ); } MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #else /* !MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */ static int ssl_parse_certificate_verify( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; size_t i, sig_len; unsigned char hash[48]; unsigned char *hash_start = hash; size_t hashlen; #if defined(MBEDTLS_SSL_PROTO_TLS1_2) mbedtls_pk_type_t pk_alg; #endif mbedtls_md_type_t md_alg; const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; mbedtls_pk_context * peer_pk; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate verify" ) ); if( !mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate verify" ) ); ssl->state++; return( 0 ); } #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) if( ssl->session_negotiate->peer_cert == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate verify" ) ); ssl->state++; return( 0 ); } #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ if( ssl->session_negotiate->peer_cert_digest == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate verify" ) ); ssl->state++; return( 0 ); } #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ /* Read the message without adding it to the checksum */ ret = mbedtls_ssl_read_record( ssl, 0 /* no checksum update */ ); if( 0 != ret ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ssl_read_record" ), ret ); return( ret ); } ssl->state++; /* Process the message contents */ if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE || ssl->in_msg[0] != MBEDTLS_SSL_HS_CERTIFICATE_VERIFY ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate verify message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY ); } i = mbedtls_ssl_hs_hdr_len( ssl ); #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) peer_pk = &ssl->handshake->peer_pubkey; #else /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ if( ssl->session_negotiate->peer_cert == NULL ) { /* Should never happen */ return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } peer_pk = &ssl->session_negotiate->peer_cert->pk; #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ /* * struct { * SignatureAndHashAlgorithm algorithm; -- TLS 1.2 only * opaque signature<0..2^16-1>; * } DigitallySigned; */ #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 ) { md_alg = MBEDTLS_MD_NONE; hashlen = 36; /* For ECDSA, use SHA-1, not MD-5 + SHA-1 */ if( mbedtls_pk_can_do( peer_pk, MBEDTLS_PK_ECDSA ) ) { hash_start += 16; hashlen -= 16; md_alg = MBEDTLS_MD_SHA1; } } else #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { if( i + 2 > ssl->in_hslen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate verify message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY ); } /* * Hash */ md_alg = mbedtls_ssl_md_alg_from_hash( ssl->in_msg[i] ); if( md_alg == MBEDTLS_MD_NONE || mbedtls_ssl_set_calc_verify_md( ssl, ssl->in_msg[i] ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "peer not adhering to requested sig_alg" " for verify message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY ); } #if !defined(MBEDTLS_MD_SHA1) if( MBEDTLS_MD_SHA1 == md_alg ) hash_start += 16; #endif /* Info from md_alg will be used instead */ hashlen = 0; i++; /* * Signature */ if( ( pk_alg = mbedtls_ssl_pk_alg_from_sig( ssl->in_msg[i] ) ) == MBEDTLS_PK_NONE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "peer not adhering to requested sig_alg" " for verify message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY ); } /* * Check the certificate's key type matches the signature alg */ if( !mbedtls_pk_can_do( peer_pk, pk_alg ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "sig_alg doesn't match cert key" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY ); } i++; } else #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } if( i + 2 > ssl->in_hslen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate verify message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY ); } sig_len = ( ssl->in_msg[i] << 8 ) | ssl->in_msg[i+1]; i += 2; if( i + sig_len != ssl->in_hslen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate verify message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY ); } /* Calculate hash and verify signature */ { size_t dummy_hlen; ssl->handshake->calc_verify( ssl, hash, &dummy_hlen ); } if( ( ret = mbedtls_pk_verify( peer_pk, md_alg, hash_start, hashlen, ssl->in_msg + i, sig_len ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_verify", ret ); return( ret ); } mbedtls_ssl_update_handshake_status( ssl ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate verify" ) ); return( ret ); } #endif /* MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) static int ssl_write_new_session_ticket( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t tlen; uint32_t lifetime; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write new session ticket" ) ); ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_NEW_SESSION_TICKET; /* * struct { * uint32 ticket_lifetime_hint; * opaque ticket<0..2^16-1>; * } NewSessionTicket; * * 4 . 7 ticket_lifetime_hint (0 = unspecified) * 8 . 9 ticket_len (n) * 10 . 9+n ticket content */ if( ( ret = ssl->conf->f_ticket_write( ssl->conf->p_ticket, ssl->session_negotiate, ssl->out_msg + 10, ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN, &tlen, &lifetime ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_ticket_write", ret ); tlen = 0; } ssl->out_msg[4] = ( lifetime >> 24 ) & 0xFF; ssl->out_msg[5] = ( lifetime >> 16 ) & 0xFF; ssl->out_msg[6] = ( lifetime >> 8 ) & 0xFF; ssl->out_msg[7] = ( lifetime ) & 0xFF; ssl->out_msg[8] = (unsigned char)( ( tlen >> 8 ) & 0xFF ); ssl->out_msg[9] = (unsigned char)( ( tlen ) & 0xFF ); ssl->out_msglen = 10 + tlen; /* * Morally equivalent to updating ssl->state, but NewSessionTicket and * ChangeCipherSpec share the same state. */ ssl->handshake->new_session_ticket = 0; if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write new session ticket" ) ); return( 0 ); } #endif /* MBEDTLS_SSL_SESSION_TICKETS */ /* * SSL handshake -- server side -- single step */ int mbedtls_ssl_handshake_server_step( mbedtls_ssl_context *ssl ) { int ret = 0; if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER || ssl->handshake == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "server state: %d", ssl->state ) ); if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 ) return( ret ); #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING ) { if( ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 ) return( ret ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ switch( ssl->state ) { case MBEDTLS_SSL_HELLO_REQUEST: ssl->state = MBEDTLS_SSL_CLIENT_HELLO; break; /* * <== ClientHello */ case MBEDTLS_SSL_CLIENT_HELLO: ret = ssl_parse_client_hello( ssl ); break; #if defined(MBEDTLS_SSL_PROTO_DTLS) case MBEDTLS_SSL_SERVER_HELLO_VERIFY_REQUEST_SENT: return( MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED ); #endif /* * ==> ServerHello * Certificate * ( ServerKeyExchange ) * ( CertificateRequest ) * ServerHelloDone */ case MBEDTLS_SSL_SERVER_HELLO: ret = ssl_write_server_hello( ssl ); break; case MBEDTLS_SSL_SERVER_CERTIFICATE: ret = mbedtls_ssl_write_certificate( ssl ); break; case MBEDTLS_SSL_SERVER_KEY_EXCHANGE: ret = ssl_write_server_key_exchange( ssl ); break; case MBEDTLS_SSL_CERTIFICATE_REQUEST: ret = ssl_write_certificate_request( ssl ); break; case MBEDTLS_SSL_SERVER_HELLO_DONE: ret = ssl_write_server_hello_done( ssl ); break; /* * <== ( Certificate/Alert ) * ClientKeyExchange * ( CertificateVerify ) * ChangeCipherSpec * Finished */ case MBEDTLS_SSL_CLIENT_CERTIFICATE: ret = mbedtls_ssl_parse_certificate( ssl ); break; case MBEDTLS_SSL_CLIENT_KEY_EXCHANGE: ret = ssl_parse_client_key_exchange( ssl ); break; case MBEDTLS_SSL_CERTIFICATE_VERIFY: ret = ssl_parse_certificate_verify( ssl ); break; case MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC: ret = mbedtls_ssl_parse_change_cipher_spec( ssl ); break; case MBEDTLS_SSL_CLIENT_FINISHED: ret = mbedtls_ssl_parse_finished( ssl ); break; /* * ==> ( NewSessionTicket ) * ChangeCipherSpec * Finished */ case MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC: #if defined(MBEDTLS_SSL_SESSION_TICKETS) if( ssl->handshake->new_session_ticket != 0 ) ret = ssl_write_new_session_ticket( ssl ); else #endif ret = mbedtls_ssl_write_change_cipher_spec( ssl ); break; case MBEDTLS_SSL_SERVER_FINISHED: ret = mbedtls_ssl_write_finished( ssl ); break; case MBEDTLS_SSL_FLUSH_BUFFERS: MBEDTLS_SSL_DEBUG_MSG( 2, ( "handshake: done" ) ); ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP; break; case MBEDTLS_SSL_HANDSHAKE_WRAPUP: mbedtls_ssl_handshake_wrapup( ssl ); break; default: MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid state %d", ssl->state ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } return( ret ); } #endif /* MBEDTLS_SSL_SRV_C */
mc-server/polarssl
library/ssl_srv.c
C
gpl-2.0
158,375
/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */ /* Rosegarden A MIDI and audio sequencer and musical notation editor. Copyright 2000-2018 the Rosegarden development team. Other copyrights also apply to some parts of this work. Please see the AUTHORS file and individual file headers for details. 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. See the file COPYING included with this distribution for more information. */ #define RG_MODULE_STRING "[TrackButtons]" #include "TrackButtons.h" #include "TrackLabel.h" #include "TrackVUMeter.h" #include "misc/Debug.h" #include "misc/Strings.h" #include "base/AudioPluginInstance.h" #include "base/Composition.h" #include "base/Device.h" #include "base/Instrument.h" #include "base/InstrumentStaticSignals.h" #include "base/MidiProgram.h" #include "base/Studio.h" #include "base/Track.h" #include "commands/segment/RenameTrackCommand.h" #include "document/RosegardenDocument.h" #include "document/CommandHistory.h" #include "gui/application/RosegardenMainWindow.h" #include "gui/general/GUIPalette.h" #include "gui/general/IconLoader.h" #include "gui/seqmanager/SequenceManager.h" #include "gui/widgets/LedButton.h" #include "sound/AudioFileManager.h" #include "sound/ControlBlock.h" #include "sound/PluginIdentifier.h" #include "sequencer/RosegardenSequencer.h" #include <QApplication> #include <QLayout> #include <QMessageBox> #include <QCursor> #include <QFrame> #include <QIcon> #include <QLabel> #include <QObject> #include <QPixmap> #include <QMenu> #include <QSignalMapper> #include <QString> #include <QTimer> #include <QWidget> #include <QStackedWidget> #include <QToolTip> namespace Rosegarden { // Constants const int TrackButtons::m_borderGap = 1; const int TrackButtons::m_buttonGap = 8; const int TrackButtons::m_vuWidth = 20; const int TrackButtons::m_vuSpacing = 2; TrackButtons::TrackButtons(RosegardenDocument* doc, int trackCellHeight, int trackLabelWidth, bool showTrackLabels, int overallHeight, QWidget* parent) : QFrame(parent), m_doc(doc), m_layout(new QVBoxLayout(this)), m_recordSigMapper(new QSignalMapper(this)), m_muteSigMapper(new QSignalMapper(this)), m_soloSigMapper(new QSignalMapper(this)), m_clickedSigMapper(new QSignalMapper(this)), m_instListSigMapper(new QSignalMapper(this)), m_tracks(doc->getComposition().getNbTracks()), // m_offset(4), m_cellSize(trackCellHeight), m_trackLabelWidth(trackLabelWidth), m_popupTrackPos(0), m_lastSelected(-1) { setFrameStyle(Plain); QPalette pal = palette(); pal.setColor(backgroundRole(), QColor(0xDD, 0xDD, 0xDD)); pal.setColor(foregroundRole(), Qt::black); setPalette(pal); // when we create the widget, what are we looking at? if (showTrackLabels) { m_labelDisplayMode = TrackLabel::ShowTrack; } else { m_labelDisplayMode = TrackLabel::ShowInstrument; } m_layout->setMargin(0); // Set the spacing between vertical elements m_layout->setSpacing(m_borderGap); // Now draw the buttons and labels and meters // makeButtons(); m_layout->addStretch(20); connect(m_recordSigMapper, SIGNAL(mapped(int)), this, SLOT(slotToggleRecord(int))); connect(m_muteSigMapper, SIGNAL(mapped(int)), this, SLOT(slotToggleMute(int))); connect(m_soloSigMapper, SIGNAL(mapped(int)), this, SLOT(slotToggleSolo(int))); // connect signal mappers connect(m_instListSigMapper, SIGNAL(mapped(int)), this, SLOT(slotInstrumentMenu(int))); connect(m_clickedSigMapper, SIGNAL(mapped(int)), this, SLOT(slotTrackSelected(int))); // We have to force the height for the moment // setMinimumHeight(overallHeight); m_doc->getComposition().addObserver(this); // We do not care about documentChanged() because if the // document is changing, we are going away. A new TrackButtons // is created for each new document. //connect(RosegardenMainWindow::self(), // SIGNAL(documentChanged(RosegardenDocument *)), // SLOT(slotNewDocument(RosegardenDocument *))); } TrackButtons::~TrackButtons() { // CRASH! Probably m_doc is gone... // Probably don't need to disconnect as we only go away when the // doc and composition do. shared_ptr would help here. // m_doc->getComposition().removeObserver(this); } void TrackButtons::updateUI(Track *track) { if (!track) return; int pos = track->getPosition(); if (pos < 0 || pos >= m_tracks) return; // *** Archive Background QFrame *hbox = m_trackHBoxes.at(pos); if (track->isArchived()) { // Go with the dark gray background. QPalette palette = hbox->palette(); palette.setColor(hbox->backgroundRole(), QColor(0x88, 0x88, 0x88)); hbox->setPalette(palette); } else { // Go with the parent's background color. QColor parentBackground = palette().color(backgroundRole()); QPalette palette = hbox->palette(); palette.setColor(hbox->backgroundRole(), parentBackground); hbox->setPalette(palette); } // *** Mute LED if (track->isMuted()) { m_muteLeds[pos]->off(); } else { m_muteLeds[pos]->on(); } // *** Record LED Instrument *ins = m_doc->getStudio().getInstrumentById(track->getInstrument()); m_recordLeds[pos]->setColor(getRecordLedColour(ins)); // Note: setRecord() used to be used to do this. But that would // set the track in the composition to record as well as setting // the button on the UI. This seems better and works fine. bool recording = m_doc->getComposition().isTrackRecording(track->getId()); setRecordButton(pos, recording); // *** Solo LED // ??? An Led::setState(bool) would be handy. m_soloLeds[pos]->setState(track->isSolo() ? Led::On : Led::Off); // *** Track Label TrackLabel *label = m_trackLabels[pos]; if (!label) return; // In case the tracks have been moved around, update the mapping. label->setId(track->getId()); setButtonMapping(label, track->getId()); label->setPosition(pos); if (track->getLabel() == "") { if (ins && ins->getType() == Instrument::Audio) { label->setTrackName(tr("<untitled audio>")); } else { label->setTrackName(tr("<untitled>")); } } else { label->setTrackName(strtoqstr(track->getLabel())); label->setShortName(strtoqstr(track->getShortLabel())); } initInstrumentNames(ins, label); label->updateLabel(); } void TrackButtons::makeButtons() { if (!m_doc) return; //RG_DEBUG << "makeButtons()"; // Create a horizontal box filled with widgets for each track for (int i = 0; i < m_tracks; ++i) { Track *track = m_doc->getComposition().getTrackByPosition(i); if (!track) continue; QFrame *trackHBox = makeButton(track); if (trackHBox) { trackHBox->setObjectName("TrackButtonFrame"); m_layout->addWidget(trackHBox); m_trackHBoxes.push_back(trackHBox); } } populateButtons(); } void TrackButtons::setButtonMapping(TrackLabel* trackLabel, TrackId trackId) { m_clickedSigMapper->setMapping(trackLabel, trackId); m_instListSigMapper->setMapping(trackLabel, trackId); } void TrackButtons::initInstrumentNames(Instrument *ins, TrackLabel *label) { if (!label) return; if (ins) { label->setPresentationName(ins->getLocalizedPresentationName()); if (ins->sendsProgramChange()) { label->setProgramChangeName( QObject::tr(ins->getProgramName().c_str())); } else { label->setProgramChangeName(""); } } else { label->setPresentationName(tr("<no instrument>")); } } void TrackButtons::populateButtons() { //RG_DEBUG << "populateButtons()"; // For each track, copy info from Track object to the widgets for (int i = 0; i < m_tracks; ++i) { Track *track = m_doc->getComposition().getTrackByPosition(i); if (!track) continue; updateUI(track); } } void TrackButtons::slotToggleMute(int pos) { //RG_DEBUG << "TrackButtons::slotToggleMute( position =" << pos << ")"; if (!m_doc) return; if (pos < 0 || pos >= m_tracks) return; Composition &comp = m_doc->getComposition(); Track *track = comp.getTrackByPosition(pos); if (!track) return; // Toggle the mute state track->setMuted(!track->isMuted()); // Notify observers comp.notifyTrackChanged(track); m_doc->slotDocumentModified(); } void TrackButtons::toggleSolo() { if (!m_doc) return; Composition &comp = m_doc->getComposition(); int pos = comp.getTrackPositionById(comp.getSelectedTrack()); if (pos == -1) return; slotToggleSolo(pos); } void TrackButtons::slotToggleSolo(int pos) { //RG_DEBUG << "slotToggleSolo( position =" << pos << ")"; if (!m_doc) return; if (pos < 0 || pos >= m_tracks) return; Composition &comp = m_doc->getComposition(); Track *track = comp.getTrackByPosition(pos); if (!track) return; bool state = !track->isSolo(); // If we're setting solo on this track and shift isn't being held down, // clear solo on all tracks (canceling mode). If shift is being held // down, multiple tracks can be put into solo (latching mode). if (state && QApplication::keyboardModifiers() != Qt::ShiftModifier) { // For each track for (int i = 0; i < m_tracks; ++i) { // Except the one that is being toggled. if (i == pos) continue; Track *track2 = comp.getTrackByPosition(i); if (!track2) continue; if (track2->isSolo()) { // Clear solo track2->setSolo(false); comp.notifyTrackChanged(track2); } } } // Toggle the solo state track->setSolo(state); // Notify observers comp.notifyTrackChanged(track); m_doc->slotDocumentModified(); } void TrackButtons::removeButtons(int position) { //RG_DEBUG << "removeButtons() - deleting track button at position:" << position; if (position < 0 || position >= m_tracks) { RG_DEBUG << "%%%%%%%%% BIG PROBLEM : TrackButtons::removeButtons() was passed a non-existing index\n"; return; } std::vector<TrackLabel*>::iterator tit = m_trackLabels.begin(); tit += position; m_trackLabels.erase(tit); std::vector<TrackVUMeter*>::iterator vit = m_trackMeters.begin(); vit += position; m_trackMeters.erase(vit); std::vector<LedButton*>::iterator mit = m_muteLeds.begin(); mit += position; m_muteLeds.erase(mit); mit = m_recordLeds.begin(); mit += position; m_recordLeds.erase(mit); m_soloLeds.erase(m_soloLeds.begin() + position); // Delete all child widgets (button, led, label...) delete m_trackHBoxes[position]; m_trackHBoxes[position] = nullptr; std::vector<QFrame*>::iterator it = m_trackHBoxes.begin(); it += position; m_trackHBoxes.erase(it); } void TrackButtons::slotUpdateTracks() { //RG_DEBUG << "slotUpdateTracks()"; #if 0 static QTime t; RG_DEBUG << " elapsed: " << t.restart(); #endif if (!m_doc) return; Composition &comp = m_doc->getComposition(); const int newNbTracks = comp.getNbTracks(); if (newNbTracks < 0) { RG_WARNING << "slotUpdateTracks(): WARNING: New number of tracks was negative:" << newNbTracks; return; } //RG_DEBUG << "TrackButtons::slotUpdateTracks > newNbTracks = " << newNbTracks; // If a track or tracks were deleted if (newNbTracks < m_tracks) { // For each deleted track, remove a button from the end. for (int i = m_tracks; i > newNbTracks; --i) removeButtons(i - 1); } else if (newNbTracks > m_tracks) { // if added // For each added track for (int i = m_tracks; i < newNbTracks; ++i) { Track *track = m_doc->getComposition().getTrackByPosition(i); if (track) { // Make a new button QFrame *trackHBox = makeButton(track); if (trackHBox) { trackHBox->show(); // Add the new button to the layout. m_layout->insertWidget(i, trackHBox); m_trackHBoxes.push_back(trackHBox); } } else RG_DEBUG << "TrackButtons::slotUpdateTracks - can't find TrackId for position " << i; } } m_tracks = newNbTracks; if (m_tracks != (int)m_trackHBoxes.size()) RG_DEBUG << "WARNING TrackButtons::slotUpdateTracks(): m_trackHBoxes.size() != m_tracks"; if (m_tracks != (int)m_trackLabels.size()) RG_DEBUG << "WARNING TrackButtons::slotUpdateTracks(): m_trackLabels.size() != m_tracks"; // For each track for (int i = 0; i < m_tracks; ++i) { Track *track = comp.getTrackByPosition(i); if (!track) continue; // *** Set Track Size *** // Track height can change when the user moves segments around and // they overlap. m_trackHBoxes[i]->setMinimumSize(labelWidth(), trackHeight(track->getId())); m_trackHBoxes[i]->setFixedHeight(trackHeight(track->getId())); } populateButtons(); // This is necessary to update the widgets's sizeHint to reflect any change in child widget sizes // Make the TrackButtons QFrame big enough to hold all the track buttons. // Some may have grown taller due to segments that overlap. // Note: This appears to no longer be needed. But it doesn't hurt. adjustSize(); } void TrackButtons::slotToggleRecord(int position) { //RG_DEBUG << "TrackButtons::slotToggleRecord(" << position << ")"; if (position < 0 || position >= m_tracks) return; if (!m_doc) return; Composition &comp = m_doc->getComposition(); Track *track = comp.getTrackByPosition(position); if (!track) return; // Toggle bool state = !comp.isTrackRecording(track->getId()); // Update the Track comp.setTrackRecording(track->getId(), state); comp.notifyTrackChanged(track); m_doc->checkAudioPath(track); } void TrackButtons::setRecordButton(int position, bool record) { if (position < 0 || position >= m_tracks) return; m_recordLeds[position]->setState(record ? Led::On : Led::Off); } void TrackButtons::selectTrack(int position) { if (position < 0 || position >= m_tracks) return; // No sense doing anything if the selection isn't changing if (position == m_lastSelected) return; // Unselect the previously selected if (m_lastSelected >= 0 && m_lastSelected < m_tracks) { m_trackLabels[m_lastSelected]->setSelected(false); } // Select the newly selected m_trackLabels[position]->setSelected(true); m_lastSelected = position; } #if 0 // unused std::vector<int> TrackButtons::getHighlightedTracks() { std::vector<int> retList; for (int i = 0; i < m_trackLabels.size(); ++i) { if (m_trackLabels[i]->isSelected()) retList.push_back(i); } return retList; } #endif void TrackButtons::slotRenameTrack(QString longLabel, QString shortLabel, TrackId trackId) { if (!m_doc) return; Track *track = m_doc->getComposition().getTrackById(trackId); if (!track) return; TrackLabel *label = m_trackLabels[track->getPosition()]; // If neither label is changing, skip it if (label->getTrackName() == longLabel && QString::fromStdString(track->getShortLabel()) == shortLabel) return; // Rename the track CommandHistory::getInstance()->addCommand( new RenameTrackCommand(&m_doc->getComposition(), trackId, longLabel, shortLabel)); } void TrackButtons::slotSetTrackMeter(float value, int position) { if (position < 0 || position >= m_tracks) return; m_trackMeters[position]->setLevel(value); } void TrackButtons::slotSetMetersByInstrument(float value, InstrumentId id) { Composition &comp = m_doc->getComposition(); for (int i = 0; i < m_tracks; ++i) { Track *track = comp.getTrackByPosition(i); if (track && track->getInstrument() == id) { m_trackMeters[i]->setLevel(value); } } } void TrackButtons::slotInstrumentMenu(int trackId) { //RG_DEBUG << "TrackButtons::slotInstrumentMenu( trackId =" << trackId << ")"; Composition &comp = m_doc->getComposition(); const int position = comp.getTrackById(trackId)->getPosition(); Track *track = comp.getTrackByPosition(position); Instrument *instrument = nullptr; if (track != nullptr) { instrument = m_doc->getStudio().getInstrumentById( track->getInstrument()); } // *** Force The Track Label To Show The Presentation Name *** // E.g. "General MIDI Device #1" m_trackLabels[position]->forcePresentationName(true); m_trackLabels[position]->updateLabel(); // *** Launch The Popup *** // Yes, well as we might've changed the Device name in the // Device/Bank dialog then we reload the whole menu here. QMenu instrumentPopup(this); populateInstrumentPopup(instrument, &instrumentPopup); // Store the popup item position for slotInstrumentSelected(). m_popupTrackPos = position; instrumentPopup.exec(QCursor::pos()); // *** Restore The Track Label *** // Turn off the presentation name m_trackLabels[position]->forcePresentationName(false); m_trackLabels[position]->updateLabel(); } // ??? Break this stuff off into an InstrumentPopup class. This class is too // big. void TrackButtons::populateInstrumentPopup(Instrument *thisTrackInstr, QMenu* instrumentPopup) { // pixmaps for icons to show connection states as variously colored boxes // ??? Factor out the icon-related stuff to make this routine clearer. // getIcon(Instrument *) would be ideal, but might not be easy. // getIcon(Device *) would also be needed. static QPixmap connectedPixmap, unconnectedPixmap, connectedUsedPixmap, unconnectedUsedPixmap, connectedSelectedPixmap, unconnectedSelectedPixmap; static bool havePixmaps = false; if (!havePixmaps) { IconLoader il; connectedPixmap = il.loadPixmap("connected"); connectedUsedPixmap = il.loadPixmap("connected-used"); connectedSelectedPixmap = il.loadPixmap("connected-selected"); unconnectedPixmap = il.loadPixmap("unconnected"); unconnectedUsedPixmap = il.loadPixmap("unconnected-used"); unconnectedSelectedPixmap = il.loadPixmap("unconnected-selected"); havePixmaps = true; } Composition &comp = m_doc->getComposition(); // clear the popup instrumentPopup->clear(); QMenu *currentSubMenu = nullptr; // position index int count = 0; int currentDevId = -1; // Get the list Studio &studio = m_doc->getStudio(); InstrumentList list = studio.getPresentationInstruments(); // For each instrument for (InstrumentList::iterator it = list.begin(); it != list.end(); ++it) { if (!(*it)) continue; // sanity check // get the Localized instrument name, with the string hackery performed // in Instrument QString iname((*it)->getLocalizedPresentationName()); // translate the program name // // Note we are converting the string from std to Q back to std then to // C. This is obviously ridiculous, but the fact that we have programName // here at all makes me think it exists as some kind of necessary hack // to coax tr() into behaving nicely. I decided to change it as little // as possible to get it to compile, and not refactor this down to the // simplest way to call tr() on a C string. QString programName(strtoqstr((*it)->getProgramName())); programName = QObject::tr(programName.toStdString().c_str()); Device *device = (*it)->getDevice(); DeviceId devId = device->getId(); bool connectedIcon = false; // Determine the proper program name and whether it is connected if ((*it)->getType() == Instrument::SoftSynth) { programName = ""; AudioPluginInstance *plugin = (*it)->getPlugin(Instrument::SYNTH_PLUGIN_POSITION); if (plugin) { // we don't translate any plugin program names or other texts programName = strtoqstr(plugin->getDisplayName()); connectedIcon = (plugin->getIdentifier() != ""); } } else if ((*it)->getType() == Instrument::Audio) { connectedIcon = true; } else { QString conn = RosegardenSequencer::getInstance()-> getConnection(devId); connectedIcon = (conn != ""); } // These two are for selecting the correct icon to display. bool instrUsedByMe = false; bool instrUsedByAnyone = false; if (thisTrackInstr && thisTrackInstr->getId() == (*it)->getId()) { instrUsedByMe = true; instrUsedByAnyone = true; } // If we have switched to a new device, we'll create a new submenu if (devId != (DeviceId)(currentDevId)) { currentDevId = int(devId); // For selecting the correct icon to display. bool deviceUsedByAnyone = false; if (instrUsedByMe) deviceUsedByAnyone = true; else { for (Composition::trackcontainer::iterator tit = comp.getTracks().begin(); tit != comp.getTracks().end(); ++tit) { if (tit->second->getInstrument() == (*it)->getId()) { instrUsedByAnyone = true; deviceUsedByAnyone = true; break; } Instrument *instr = studio.getInstrumentById(tit->second->getInstrument()); if (instr && (instr->getDevice()->getId() == devId)) { deviceUsedByAnyone = true; } } } QIcon icon (connectedIcon ? (deviceUsedByAnyone ? connectedUsedPixmap : connectedPixmap) : (deviceUsedByAnyone ? unconnectedUsedPixmap : unconnectedPixmap)); // Create a submenu for this device QMenu *subMenu = new QMenu(instrumentPopup); subMenu->setMouseTracking(true); subMenu->setIcon(icon); // Not needed so long as AA_DontShowIconsInMenus is false. //subMenu->menuAction()->setIconVisibleInMenu(true); // Menu title QString deviceName = QObject::tr(device->getName().c_str()); subMenu->setTitle(deviceName); // QObject name subMenu->setObjectName(deviceName); // Add the submenu to the popup menu instrumentPopup->addMenu(subMenu); // Connect the submenu to slotInstrumentSelected() connect(subMenu, SIGNAL(triggered(QAction*)), this, SLOT(slotInstrumentSelected(QAction*))); currentSubMenu = subMenu; } else if (!instrUsedByMe) { // Search the tracks to see if anyone else is using this // instrument for (Composition::trackcontainer::iterator tit = comp.getTracks().begin(); tit != comp.getTracks().end(); ++tit) { if (tit->second->getInstrument() == (*it)->getId()) { instrUsedByAnyone = true; break; } } } QIcon icon (connectedIcon ? (instrUsedByAnyone ? instrUsedByMe ? connectedSelectedPixmap : connectedUsedPixmap : connectedPixmap) : (instrUsedByAnyone ? instrUsedByMe ? unconnectedSelectedPixmap : unconnectedUsedPixmap : unconnectedPixmap)); // Create an action for this instrument QAction* action = new QAction(instrumentPopup); action->setIcon(icon); // Not needed so long as AA_DontShowIconsInMenus is false. //action->setIconVisibleInMenu(true); // Action text if (programName != "") iname += " (" + programName + ")"; action->setText(iname); // Item index used to find the proper instrument once the user makes // a selection from the menu. action->setData(QVariant(count)); // QObject object name. action->setObjectName(iname + QString(count)); // Add the action to the current submenu if (currentSubMenu) currentSubMenu->addAction(action); // Next item index count++; } } void TrackButtons::slotInstrumentSelected(QAction* action) { // The action data field has the instrument index. slotInstrumentSelected(action->data().toInt()); } void TrackButtons::selectInstrument(Track *track, Instrument *instrument) { // Inform the rest of the system of the instrument change. // ??? This routine needs to go for two reasons: // // 1. TrackParameterBox calls this. UI to UI connections should be // avoided. It would be better to copy/paste this over to TPB // to avoid the connection. But then we have double-maintenance. // See reason 2. // // 2. The UI shouldn't know so much about the other objects in the // system. The following updates should be done by their // respective objects. // // A "TrackStaticSignals::instrumentChanged(Track *, Instrument *)" // notification is probably the best way to get rid of this routine. // It could be emitted from Track::setInstrument(). Normally emitting // from setters is bad, but in this case, it is necessary. We need // to know about every single change when it occurs. // Then ControlBlockSignalHandler (new class to avoid deriving // ControlBlock from QObject), InstrumentSignalHandler (new class to // handle signals for all Instrument instances), and // SequenceManager (already derives from QObject, might want to // consider a new SequenceManagerSignalHandler to avoid additional // dependency on QObject) can connect and do what needs to be done in // response. Rationale for this over doc modified is that we // can't simply refresh everything (Instrument::sendChannelSetup() // sends out data), and it is expensive to detect what has actually // changed (we would have to cache the Track->Instrument mapping and // check it for changes). const TrackId trackId = track->getId(); // *** ControlBlock ControlBlock::getInstance()-> setInstrumentForTrack(trackId, instrument->getId()); // *** Send out BS/PC // Make sure the Device is in sync with the Instrument's settings. instrument->sendChannelSetup(); // *** SequenceManager // In case the sequencer is currently playing, we need to regenerate // all the events with the new channel number. Composition &comp = m_doc->getComposition(); SequenceManager *sequenceManager = m_doc->getSequenceManager(); // For each segment in the composition for (Composition::iterator i = comp.begin(); i != comp.end(); ++i) { Segment *segment = (*i); // If this Segment is on this Track, let SequenceManager know // that the Instrument has changed. // Segments on this track are now playing on a new // instrument, so they're no longer ready (making them // ready is done just-in-time elsewhere), nor is thru // channel ready. if (segment->getTrack() == trackId) sequenceManager->segmentInstrumentChanged(segment); } } void TrackButtons::slotInstrumentSelected(int instrumentIndex) { //RG_DEBUG << "slotInstrumentSelected(): instrumentIndex =" << instrumentIndex; Instrument *instrument = m_doc->getStudio().getInstrumentFromList(instrumentIndex); //RG_DEBUG << "slotInstrumentSelected(): instrument " << inst; if (!instrument) { RG_WARNING << "slotInstrumentSelected(): WARNING: Can't find Instrument"; return; } Composition &comp = m_doc->getComposition(); Track *track = comp.getTrackByPosition(m_popupTrackPos); if (!track) { RG_WARNING << "slotInstrumentSelected(): WARNING: Can't find Track"; return; } // No change? Bail. if (instrument->getId() == track->getInstrument()) return; // Select the new instrument for the track. // ??? This sends a trackChanged() notification. It shouldn't. We should // send one here. track->setInstrument(instrument->getId()); // ??? This is what we should do. //comp.notifyTrackChanged(track); m_doc->slotDocumentModified(); // Notify IPB, ControlBlock, and SequenceManager. selectInstrument(track, instrument); } void TrackButtons::changeLabelDisplayMode(TrackLabel::DisplayMode mode) { // Set new mode m_labelDisplayMode = mode; // For each track, set the display mode and update. for (int i = 0; i < m_tracks; i++) { m_trackLabels[i]->setDisplayMode(mode); m_trackLabels[i]->updateLabel(); } } void TrackButtons::slotSynchroniseWithComposition() { //RG_DEBUG << "slotSynchroniseWithComposition()"; Composition &comp = m_doc->getComposition(); for (int i = 0; i < m_tracks; i++) { updateUI(comp.getTrackByPosition(i)); } } #if 0 void TrackButtons::slotLabelSelected(int position) { Track *track = m_doc->getComposition().getTrackByPosition(position); if (track) { emit trackSelected(track->getId()); } } #endif void TrackButtons::slotTPBInstrumentSelected(TrackId trackId, int instrumentIndex) { //RG_DEBUG << "TrackButtons::slotTPBInstrumentSelected( trackId =" << trackId << ", instrumentIndex =" << instrumentIndex << ")"; // Set the position for slotInstrumentSelected(). // ??? This isn't good. Should have a selectTrack() that takes the // track position and the instrument index. slotInstrumentSelected() // could call it. m_popupTrackPos = m_doc->getComposition().getTrackById(trackId)->getPosition(); slotInstrumentSelected(instrumentIndex); } int TrackButtons::labelWidth() { return m_trackLabelWidth - ((m_cellSize - m_buttonGap) * 2 + m_vuSpacing * 2 + m_vuWidth); } int TrackButtons::trackHeight(TrackId trackId) { int multiple = m_doc-> getComposition().getMaxContemporaneousSegmentsOnTrack(trackId); if (multiple == 0) multiple = 1; return m_cellSize * multiple - m_borderGap; } QFrame* TrackButtons::makeButton(Track *track) { if (track == nullptr) return nullptr; TrackId trackId = track->getId(); // *** Horizontal Box *** QFrame *trackHBox = new QFrame(this); QHBoxLayout *hblayout = new QHBoxLayout(trackHBox); trackHBox->setLayout(hblayout); hblayout->setMargin(0); hblayout->setSpacing(0); trackHBox->setMinimumSize(labelWidth(), trackHeight(trackId)); trackHBox->setFixedHeight(trackHeight(trackId)); trackHBox->setFrameShape(QFrame::StyledPanel); trackHBox->setFrameShadow(QFrame::Raised); // We will be changing the background color, so turn on auto-fill. trackHBox->setAutoFillBackground(true); // Insert a little gap hblayout->addSpacing(m_vuSpacing); // *** VU Meter *** TrackVUMeter *vuMeter = new TrackVUMeter(trackHBox, VUMeter::PeakHold, m_vuWidth, m_buttonGap, track->getPosition()); m_trackMeters.push_back(vuMeter); hblayout->addWidget(vuMeter); // Insert a little gap hblayout->addSpacing(m_vuSpacing); // *** Mute LED *** LedButton *mute = new LedButton( GUIPalette::getColour(GUIPalette::MuteTrackLED), trackHBox); mute->setToolTip(tr("Mute track")); hblayout->addWidget(mute); connect(mute, SIGNAL(stateChanged(bool)), m_muteSigMapper, SLOT(map())); m_muteSigMapper->setMapping(mute, track->getPosition()); m_muteLeds.push_back(mute); mute->setFixedSize(m_cellSize - m_buttonGap, m_cellSize - m_buttonGap); // *** Record LED *** Rosegarden::Instrument *ins = m_doc->getStudio().getInstrumentById(track->getInstrument()); LedButton *record = new LedButton(getRecordLedColour(ins), trackHBox); record->setToolTip(tr("Record on this track")); hblayout->addWidget(record); connect(record, SIGNAL(stateChanged(bool)), m_recordSigMapper, SLOT(map())); m_recordSigMapper->setMapping(record, track->getPosition()); m_recordLeds.push_back(record); record->setFixedSize(m_cellSize - m_buttonGap, m_cellSize - m_buttonGap); // *** Solo LED *** LedButton *solo = new LedButton( GUIPalette::getColour(GUIPalette::SoloTrackLED), trackHBox); solo->setToolTip(tr("Solo track")); hblayout->addWidget(solo); connect(solo, SIGNAL(stateChanged(bool)), m_soloSigMapper, SLOT(map())); m_soloSigMapper->setMapping(solo, track->getPosition()); m_soloLeds.push_back(solo); solo->setFixedSize(m_cellSize - m_buttonGap, m_cellSize - m_buttonGap); // *** Track Label *** TrackLabel *trackLabel = new TrackLabel(trackId, track->getPosition(), trackHBox); hblayout->addWidget(trackLabel); hblayout->addSpacing(m_vuSpacing); trackLabel->setDisplayMode(m_labelDisplayMode); trackLabel->setFixedSize(labelWidth(), m_cellSize - m_buttonGap); trackLabel->setFixedHeight(m_cellSize - m_buttonGap); trackLabel->setIndent(7); connect(trackLabel, &TrackLabel::renameTrack, this, &TrackButtons::slotRenameTrack); m_trackLabels.push_back(trackLabel); // Connect it setButtonMapping(trackLabel, trackId); connect(trackLabel, SIGNAL(changeToInstrumentList()), m_instListSigMapper, SLOT(map())); connect(trackLabel, SIGNAL(clicked()), m_clickedSigMapper, SLOT(map())); return trackHBox; } QColor TrackButtons::getRecordLedColour(Instrument *ins) { if (!ins) return Qt::white; switch (ins->getType()) { case Instrument::Audio: return GUIPalette::getColour(GUIPalette::RecordAudioTrackLED); case Instrument::SoftSynth: return GUIPalette::getColour(GUIPalette::RecordSoftSynthTrackLED); case Instrument::Midi: return GUIPalette::getColour(GUIPalette::RecordMIDITrackLED); case Instrument::InvalidInstrument: default: RG_DEBUG << "TrackButtons::slotUpdateTracks() - invalid instrument type, this is probably a BUG!"; return Qt::green; } } void TrackButtons::tracksAdded(const Composition *, std::vector<TrackId> &/*trackIds*/) { //RG_DEBUG << "TrackButtons::tracksAdded()"; // ??? This is a bit heavy-handed as it just adds a track button, then // recreates all the track buttons. We might be able to just add the // one that is needed. slotUpdateTracks(); } void TrackButtons::trackChanged(const Composition *, Track* track) { //RG_DEBUG << "trackChanged()"; //RG_DEBUG << " Position:" << track->getPosition(); //RG_DEBUG << " Armed:" << track->isArmed(); updateUI(track); } void TrackButtons::tracksDeleted(const Composition *, std::vector<TrackId> &/*trackIds*/) { //RG_DEBUG << "TrackButtons::tracksDeleted()"; // ??? This is a bit heavy-handed as it just deletes a track button, // then recreates all the track buttons. We might be able to just // delete the one that is going away. slotUpdateTracks(); } void TrackButtons::trackSelectionChanged(const Composition *, TrackId trackId) { //RG_DEBUG << "TrackButtons::trackSelectionChanged()" << trackId; Track *track = m_doc->getComposition().getTrackById(trackId); selectTrack(track->getPosition()); } void TrackButtons::segmentRemoved(const Composition *, Segment *) { // If recording causes the track heights to change, this makes sure // they go back if needed when recording stops. slotUpdateTracks(); } void TrackButtons::slotTrackSelected(int trackId) { // Select the track. m_doc->getComposition().setSelectedTrack(trackId); // Old notification mechanism // ??? This should be replaced with emitDocumentModified() below. m_doc->getComposition().notifyTrackSelectionChanged(trackId); // Older mechanism. Keeping this until we can completely replace it // with emitDocumentModified() below. emit trackSelected(trackId); // New notification mechanism. // This should replace all others. m_doc->emitDocumentModified(); } void TrackButtons::slotDocumentModified(bool) { // Full and immediate update. // ??? Note that updates probably happen elsewhere. This will result // in duplicate updates. All other updates should be removed and // this should be the only update. slotUpdateTracks(); } }
bownie/RosegardenW
gui/editors/segment/TrackButtons.cpp
C++
gpl-2.0
38,763
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Navigation; namespace SupCarLocator.ViewModel { class PageViewModelBase : BaseViewModel { protected NavigationContext NavigationContext; protected NavigationService NavigationService; public virtual void OnNavigatedTo(NavigationContext navigationContext, NavigationService navigationService) { NavigationContext = navigationContext; NavigationService = navigationService; } } }
Dioud/SupCarLocator
SupCarLocator/SupCarLocator/ViewModel/PageViewModelBase.cs
C#
gpl-2.0
605
/* * xHCI host controller driver * * Copyright (C) 2008 Intel Corp. * * Author: Sarah Sharp * Some code borrowed from the Linux EHCI driver. * * 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. * * 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. */ /* * Ring initialization rules: * 1. Each segment is initialized to zero, except for link TRBs. * 2. Ring cycle state = 0. This represents Producer Cycle State (PCS) or * Consumer Cycle State (CCS), depending on ring function. * 3. Enqueue pointer = dequeue pointer = address of first TRB in the segment. * * Ring behavior rules: * 1. A ring is empty if enqueue == dequeue. This means there will always be at * least one free TRB in the ring. This is useful if you want to turn that * into a link TRB and expand the ring. * 2. When incrementing an enqueue or dequeue pointer, if the next TRB is a * link TRB, then load the pointer with the address in the link TRB. If the * link TRB had its toggle bit set, you may need to update the ring cycle * state (see cycle bit rules). You may have to do this multiple times * until you reach a non-link TRB. * 3. A ring is full if enqueue++ (for the definition of increment above) * equals the dequeue pointer. * * Cycle bit rules: * 1. When a consumer increments a dequeue pointer and encounters a toggle bit * in a link TRB, it must toggle the ring cycle state. * 2. When a producer increments an enqueue pointer and encounters a toggle bit * in a link TRB, it must toggle the ring cycle state. * * Producer rules: * 1. Check if ring is full before you enqueue. * 2. Write the ring cycle state to the cycle bit in the TRB you're enqueuing. * Update enqueue pointer between each write (which may update the ring * cycle state). * 3. Notify consumer. If SW is producer, it rings the doorbell for command * and endpoint rings. If HC is the producer for the event ring, * and it generates an interrupt according to interrupt modulation rules. * * Consumer rules: * 1. Check if TRB belongs to you. If the cycle bit == your ring cycle state, * the TRB is owned by the consumer. * 2. Update dequeue pointer (which may update the ring cycle state) and * continue processing TRBs until you reach a TRB which is not owned by you. * 3. Notify the producer. SW is the consumer for the event ring, and it * updates event ring dequeue pointer. HC is the consumer for the command and * endpoint rings; it generates events on the event ring for these. */ #include <linux/scatterlist.h> #include <linux/slab.h> #include "xhci.h" static int handle_cmd_in_cmd_wait_list(struct xhci_hcd *xhci, struct xhci_virt_device *virt_dev, struct xhci_event_cmd *event); /* * Returns zero if the TRB isn't in this segment, otherwise it returns the DMA * address of the TRB. */ dma_addr_t xhci_trb_virt_to_dma(struct xhci_segment *seg, union xhci_trb *trb) { unsigned long segment_offset; if (!seg || !trb || trb < seg->trbs) return 0; /* offset in TRBs */ segment_offset = trb - seg->trbs; if (segment_offset > TRBS_PER_SEGMENT) return 0; return seg->dma + (segment_offset * sizeof(*trb)); } /* Does this link TRB point to the first segment in a ring, * or was the previous TRB the last TRB on the last segment in the ERST? */ static bool last_trb_on_last_seg(struct xhci_hcd *xhci, struct xhci_ring *ring, struct xhci_segment *seg, union xhci_trb *trb) { if (ring == xhci->event_ring) return (trb == &seg->trbs[TRBS_PER_SEGMENT]) && (seg->next == xhci->event_ring->first_seg); else return le32_to_cpu(trb->link.control) & LINK_TOGGLE; } /* Is this TRB a link TRB or was the last TRB the last TRB in this event ring * segment? I.e. would the updated event TRB pointer step off the end of the * event seg? */ static int last_trb(struct xhci_hcd *xhci, struct xhci_ring *ring, struct xhci_segment *seg, union xhci_trb *trb) { if (ring == xhci->event_ring) return trb == &seg->trbs[TRBS_PER_SEGMENT]; else return TRB_TYPE_LINK_LE32(trb->link.control); } static int enqueue_is_link_trb(struct xhci_ring *ring) { struct xhci_link_trb *link = &ring->enqueue->link; return TRB_TYPE_LINK_LE32(link->control); } /* Updates trb to point to the next TRB in the ring, and updates seg if the next * TRB is in a new segment. This does not skip over link TRBs, and it does not * effect the ring dequeue or enqueue pointers. */ static void next_trb(struct xhci_hcd *xhci, struct xhci_ring *ring, struct xhci_segment **seg, union xhci_trb **trb) { if (last_trb(xhci, ring, *seg, *trb)) { *seg = (*seg)->next; *trb = ((*seg)->trbs); } else { (*trb)++; } } /* * See Cycle bit rules. SW is the consumer for the event ring only. * Don't make a ring full of link TRBs. That would be dumb and this would loop. */ static void inc_deq(struct xhci_hcd *xhci, struct xhci_ring *ring) { union xhci_trb *next; unsigned long long addr; ring->deq_updates++; /* If this is not event ring, there is one more usable TRB */ if (ring->type != TYPE_EVENT && !last_trb(xhci, ring, ring->deq_seg, ring->dequeue)) ring->num_trbs_free++; next = ++(ring->dequeue); /* Update the dequeue pointer further if that was a link TRB or we're at * the end of an event ring segment (which doesn't have link TRBS) */ while (last_trb(xhci, ring, ring->deq_seg, next)) { if (ring->type == TYPE_EVENT && last_trb_on_last_seg(xhci, ring, ring->deq_seg, next)) { ring->cycle_state = (ring->cycle_state ? 0 : 1); } ring->deq_seg = ring->deq_seg->next; ring->dequeue = ring->deq_seg->trbs; next = ring->dequeue; } addr = (unsigned long long) xhci_trb_virt_to_dma(ring->deq_seg, ring->dequeue); } /* * See Cycle bit rules. SW is the consumer for the event ring only. * Don't make a ring full of link TRBs. That would be dumb and this would loop. * * If we've just enqueued a TRB that is in the middle of a TD (meaning the * chain bit is set), then set the chain bit in all the following link TRBs. * If we've enqueued the last TRB in a TD, make sure the following link TRBs * have their chain bit cleared (so that each Link TRB is a separate TD). * * Section 6.4.4.1 of the 0.95 spec says link TRBs cannot have the chain bit * set, but other sections talk about dealing with the chain bit set. This was * fixed in the 0.96 specification errata, but we have to assume that all 0.95 * xHCI hardware can't handle the chain bit being cleared on a link TRB. * * @more_trbs_coming: Will you enqueue more TRBs before calling * prepare_transfer()? */ static void inc_enq(struct xhci_hcd *xhci, struct xhci_ring *ring, bool more_trbs_coming) { u32 chain; union xhci_trb *next; unsigned long long addr; chain = le32_to_cpu(ring->enqueue->generic.field[3]) & TRB_CHAIN; /* If this is not event ring, there is one less usable TRB */ if (ring->type != TYPE_EVENT && !last_trb(xhci, ring, ring->enq_seg, ring->enqueue)) ring->num_trbs_free--; next = ++(ring->enqueue); ring->enq_updates++; /* Update the dequeue pointer further if that was a link TRB or we're at * the end of an event ring segment (which doesn't have link TRBS) */ while (last_trb(xhci, ring, ring->enq_seg, next)) { if (ring->type != TYPE_EVENT) { /* * If the caller doesn't plan on enqueueing more * TDs before ringing the doorbell, then we * don't want to give the link TRB to the * hardware just yet. We'll give the link TRB * back in prepare_ring() just before we enqueue * the TD at the top of the ring. */ if (!chain && !more_trbs_coming) break; /* If we're not dealing with 0.95 hardware or * isoc rings on AMD 0.96 host, * carry over the chain bit of the previous TRB * (which may mean the chain bit is cleared). */ if (!(ring->type == TYPE_ISOC && (xhci->quirks & XHCI_AMD_0x96_HOST)) && !xhci_link_trb_quirk(xhci)) { next->link.control &= cpu_to_le32(~TRB_CHAIN); next->link.control |= cpu_to_le32(chain); } /* Give this link TRB to the hardware */ wmb(); next->link.control ^= cpu_to_le32(TRB_CYCLE); /* Toggle the cycle bit after the last ring segment. */ if (last_trb_on_last_seg(xhci, ring, ring->enq_seg, next)) { ring->cycle_state = (ring->cycle_state ? 0 : 1); } } ring->enq_seg = ring->enq_seg->next; ring->enqueue = ring->enq_seg->trbs; next = ring->enqueue; } addr = (unsigned long long) xhci_trb_virt_to_dma(ring->enq_seg, ring->enqueue); } /* * Check to see if there's room to enqueue num_trbs on the ring and make sure * enqueue pointer will not advance into dequeue segment. See rules above. */ static inline int room_on_ring(struct xhci_hcd *xhci, struct xhci_ring *ring, unsigned int num_trbs) { int num_trbs_in_deq_seg; if (ring->num_trbs_free < num_trbs) return 0; if (ring->type != TYPE_COMMAND && ring->type != TYPE_EVENT) { num_trbs_in_deq_seg = ring->dequeue - ring->deq_seg->trbs; if (ring->num_trbs_free < num_trbs + num_trbs_in_deq_seg) return 0; } return 1; } /* Ring the host controller doorbell after placing a command on the ring */ void xhci_ring_cmd_db(struct xhci_hcd *xhci) { xhci_dbg(xhci, "// Ding dong!\n"); xhci_writel(xhci, DB_VALUE_HOST, &xhci->dba->doorbell[0]); /* Flush PCI posted writes */ xhci_readl(xhci, &xhci->dba->doorbell[0]); } void xhci_ring_ep_doorbell(struct xhci_hcd *xhci, unsigned int slot_id, unsigned int ep_index, unsigned int stream_id) { __le32 __iomem *db_addr = &xhci->dba->doorbell[slot_id]; struct xhci_virt_ep *ep = &xhci->devs[slot_id]->eps[ep_index]; unsigned int ep_state = ep->ep_state; /* Don't ring the doorbell for this endpoint if there are pending * cancellations because we don't want to interrupt processing. * We don't want to restart any stream rings if there's a set dequeue * pointer command pending because the device can choose to start any * stream once the endpoint is on the HW schedule. * FIXME - check all the stream rings for pending cancellations. */ if ((ep_state & EP_HALT_PENDING) || (ep_state & SET_DEQ_PENDING) || (ep_state & EP_HALTED)) return; xhci_writel(xhci, DB_VALUE(ep_index, stream_id), db_addr); /* The CPU has better things to do at this point than wait for a * write-posting flush. It'll get there soon enough. */ } /* Ring the doorbell for any rings with pending URBs */ static void ring_doorbell_for_active_rings(struct xhci_hcd *xhci, unsigned int slot_id, unsigned int ep_index) { unsigned int stream_id; struct xhci_virt_ep *ep; ep = &xhci->devs[slot_id]->eps[ep_index]; /* A ring has pending URBs if its TD list is not empty */ if (!(ep->ep_state & EP_HAS_STREAMS)) { if (!(list_empty(&ep->ring->td_list))) xhci_ring_ep_doorbell(xhci, slot_id, ep_index, 0); return; } for (stream_id = 1; stream_id < ep->stream_info->num_streams; stream_id++) { struct xhci_stream_info *stream_info = ep->stream_info; if (!list_empty(&stream_info->stream_rings[stream_id]->td_list)) xhci_ring_ep_doorbell(xhci, slot_id, ep_index, stream_id); } } /* * Find the segment that trb is in. Start searching in start_seg. * If we must move past a segment that has a link TRB with a toggle cycle state * bit set, then we will toggle the value pointed at by cycle_state. */ static struct xhci_segment *find_trb_seg( struct xhci_segment *start_seg, union xhci_trb *trb, int *cycle_state) { struct xhci_segment *cur_seg = start_seg; struct xhci_generic_trb *generic_trb; while (cur_seg->trbs > trb || &cur_seg->trbs[TRBS_PER_SEGMENT - 1] < trb) { generic_trb = &cur_seg->trbs[TRBS_PER_SEGMENT - 1].generic; if (generic_trb->field[3] & cpu_to_le32(LINK_TOGGLE)) *cycle_state ^= 0x1; cur_seg = cur_seg->next; if (cur_seg == start_seg) /* Looped over the entire list. Oops! */ return NULL; } return cur_seg; } static struct xhci_ring *xhci_triad_to_transfer_ring(struct xhci_hcd *xhci, unsigned int slot_id, unsigned int ep_index, unsigned int stream_id) { struct xhci_virt_ep *ep; ep = &xhci->devs[slot_id]->eps[ep_index]; /* Common case: no streams */ if (!(ep->ep_state & EP_HAS_STREAMS)) return ep->ring; if (stream_id == 0) { xhci_warn(xhci, "WARN: Slot ID %u, ep index %u has streams, " "but URB has no stream ID.\n", slot_id, ep_index); return NULL; } if (stream_id < ep->stream_info->num_streams) return ep->stream_info->stream_rings[stream_id]; xhci_warn(xhci, "WARN: Slot ID %u, ep index %u has " "stream IDs 1 to %u allocated, " "but stream ID %u is requested.\n", slot_id, ep_index, ep->stream_info->num_streams - 1, stream_id); return NULL; } /* Get the right ring for the given URB. * If the endpoint supports streams, boundary check the URB's stream ID. * If the endpoint doesn't support streams, return the singular endpoint ring. */ static struct xhci_ring *xhci_urb_to_transfer_ring(struct xhci_hcd *xhci, struct urb *urb) { return xhci_triad_to_transfer_ring(xhci, urb->dev->slot_id, xhci_get_endpoint_index(&urb->ep->desc), urb->stream_id); } /* * Move the xHC's endpoint ring dequeue pointer past cur_td. * Record the new state of the xHC's endpoint ring dequeue segment, * dequeue pointer, and new consumer cycle state in state. * Update our internal representation of the ring's dequeue pointer. * * We do this in three jumps: * - First we update our new ring state to be the same as when the xHC stopped. * - Then we traverse the ring to find the segment that contains * the last TRB in the TD. We toggle the xHC's new cycle state when we pass * any link TRBs with the toggle cycle bit set. * - Finally we move the dequeue state one TRB further, toggling the cycle bit * if we've moved it past a link TRB with the toggle cycle bit set. * * Some of the uses of xhci_generic_trb are grotty, but if they're done * with correct __le32 accesses they should work fine. Only users of this are * in here. */ void xhci_find_new_dequeue_state(struct xhci_hcd *xhci, unsigned int slot_id, unsigned int ep_index, unsigned int stream_id, struct xhci_td *cur_td, struct xhci_dequeue_state *state) { struct xhci_virt_device *dev = xhci->devs[slot_id]; struct xhci_ring *ep_ring; struct xhci_generic_trb *trb; struct xhci_ep_ctx *ep_ctx; dma_addr_t addr; ep_ring = xhci_triad_to_transfer_ring(xhci, slot_id, ep_index, stream_id); if (!ep_ring) { xhci_warn(xhci, "WARN can't find new dequeue state " "for invalid stream ID %u.\n", stream_id); return; } state->new_cycle_state = 0; xhci_dbg(xhci, "Finding segment containing stopped TRB.\n"); state->new_deq_seg = find_trb_seg(cur_td->start_seg, dev->eps[ep_index].stopped_trb, &state->new_cycle_state); if (!state->new_deq_seg) { WARN_ON(1); return; } /* Dig out the cycle state saved by the xHC during the stop ep cmd */ xhci_dbg(xhci, "Finding endpoint context\n"); ep_ctx = xhci_get_ep_ctx(xhci, dev->out_ctx, ep_index); state->new_cycle_state = 0x1 & le64_to_cpu(ep_ctx->deq); state->new_deq_ptr = cur_td->last_trb; xhci_dbg(xhci, "Finding segment containing last TRB in TD.\n"); state->new_deq_seg = find_trb_seg(state->new_deq_seg, state->new_deq_ptr, &state->new_cycle_state); if (!state->new_deq_seg) { WARN_ON(1); return; } trb = &state->new_deq_ptr->generic; if (TRB_TYPE_LINK_LE32(trb->field[3]) && (trb->field[3] & cpu_to_le32(LINK_TOGGLE))) state->new_cycle_state ^= 0x1; next_trb(xhci, ep_ring, &state->new_deq_seg, &state->new_deq_ptr); /* * If there is only one segment in a ring, find_trb_seg()'s while loop * will not run, and it will return before it has a chance to see if it * needs to toggle the cycle bit. It can't tell if the stalled transfer * ended just before the link TRB on a one-segment ring, or if the TD * wrapped around the top of the ring, because it doesn't have the TD in * question. Look for the one-segment case where stalled TRB's address * is greater than the new dequeue pointer address. */ if (ep_ring->first_seg == ep_ring->first_seg->next && state->new_deq_ptr < dev->eps[ep_index].stopped_trb) state->new_cycle_state ^= 0x1; xhci_dbg(xhci, "Cycle state = 0x%x\n", state->new_cycle_state); /* Don't update the ring cycle state for the producer (us). */ xhci_dbg(xhci, "New dequeue segment = %p (virtual)\n", state->new_deq_seg); addr = xhci_trb_virt_to_dma(state->new_deq_seg, state->new_deq_ptr); xhci_dbg(xhci, "New dequeue pointer = 0x%llx (DMA)\n", (unsigned long long) addr); } /* flip_cycle means flip the cycle bit of all but the first and last TRB. * (The last TRB actually points to the ring enqueue pointer, which is not part * of this TD.) This is used to remove partially enqueued isoc TDs from a ring. */ static void td_to_noop(struct xhci_hcd *xhci, struct xhci_ring *ep_ring, struct xhci_td *cur_td, bool flip_cycle) { struct xhci_segment *cur_seg; union xhci_trb *cur_trb; for (cur_seg = cur_td->start_seg, cur_trb = cur_td->first_trb; true; next_trb(xhci, ep_ring, &cur_seg, &cur_trb)) { if (TRB_TYPE_LINK_LE32(cur_trb->generic.field[3])) { /* Unchain any chained Link TRBs, but * leave the pointers intact. */ cur_trb->generic.field[3] &= cpu_to_le32(~TRB_CHAIN); /* Flip the cycle bit (link TRBs can't be the first * or last TRB). */ if (flip_cycle) cur_trb->generic.field[3] ^= cpu_to_le32(TRB_CYCLE); xhci_dbg(xhci, "Cancel (unchain) link TRB\n"); xhci_dbg(xhci, "Address = %p (0x%llx dma); " "in seg %p (0x%llx dma)\n", cur_trb, (unsigned long long)xhci_trb_virt_to_dma(cur_seg, cur_trb), cur_seg, (unsigned long long)cur_seg->dma); } else { cur_trb->generic.field[0] = 0; cur_trb->generic.field[1] = 0; cur_trb->generic.field[2] = 0; /* Preserve only the cycle bit of this TRB */ cur_trb->generic.field[3] &= cpu_to_le32(TRB_CYCLE); /* Flip the cycle bit except on the first or last TRB */ if (flip_cycle && cur_trb != cur_td->first_trb && cur_trb != cur_td->last_trb) cur_trb->generic.field[3] ^= cpu_to_le32(TRB_CYCLE); cur_trb->generic.field[3] |= cpu_to_le32( TRB_TYPE(TRB_TR_NOOP)); xhci_dbg(xhci, "TRB to noop at offset 0x%llx\n", (unsigned long long) xhci_trb_virt_to_dma(cur_seg, cur_trb)); } if (cur_trb == cur_td->last_trb) break; } } static int queue_set_tr_deq(struct xhci_hcd *xhci, int slot_id, unsigned int ep_index, unsigned int stream_id, struct xhci_segment *deq_seg, union xhci_trb *deq_ptr, u32 cycle_state); void xhci_queue_new_dequeue_state(struct xhci_hcd *xhci, unsigned int slot_id, unsigned int ep_index, unsigned int stream_id, struct xhci_dequeue_state *deq_state) { struct xhci_virt_ep *ep = &xhci->devs[slot_id]->eps[ep_index]; xhci_dbg(xhci, "Set TR Deq Ptr cmd, new deq seg = %p (0x%llx dma), " "new deq ptr = %p (0x%llx dma), new cycle = %u\n", deq_state->new_deq_seg, (unsigned long long)deq_state->new_deq_seg->dma, deq_state->new_deq_ptr, (unsigned long long)xhci_trb_virt_to_dma(deq_state->new_deq_seg, deq_state->new_deq_ptr), deq_state->new_cycle_state); queue_set_tr_deq(xhci, slot_id, ep_index, stream_id, deq_state->new_deq_seg, deq_state->new_deq_ptr, (u32) deq_state->new_cycle_state); /* Stop the TD queueing code from ringing the doorbell until * this command completes. The HC won't set the dequeue pointer * if the ring is running, and ringing the doorbell starts the * ring running. */ ep->ep_state |= SET_DEQ_PENDING; } static void xhci_stop_watchdog_timer_in_irq(struct xhci_hcd *xhci, struct xhci_virt_ep *ep) { ep->ep_state &= ~EP_HALT_PENDING; /* Can't del_timer_sync in interrupt, so we attempt to cancel. If the * timer is running on another CPU, we don't decrement stop_cmds_pending * (since we didn't successfully stop the watchdog timer). */ if (del_timer(&ep->stop_cmd_timer)) ep->stop_cmds_pending--; } /* Must be called with xhci->lock held in interrupt context */ static void xhci_giveback_urb_in_irq(struct xhci_hcd *xhci, struct xhci_td *cur_td, int status, char *adjective) { struct usb_hcd *hcd; struct urb *urb; struct urb_priv *urb_priv; urb = cur_td->urb; urb_priv = urb->hcpriv; urb_priv->td_cnt++; hcd = bus_to_hcd(urb->dev->bus); /* Only giveback urb when this is the last td in urb */ if (urb_priv->td_cnt == urb_priv->length) { if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS) { xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs--; if (xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs == 0) { if (xhci->quirks & XHCI_AMD_PLL_FIX) usb_amd_quirk_pll_enable(); } } usb_hcd_unlink_urb_from_ep(hcd, urb); spin_unlock(&xhci->lock); usb_hcd_giveback_urb(hcd, urb, status); xhci_urb_free_priv(xhci, urb_priv); spin_lock(&xhci->lock); } } /* * When we get a command completion for a Stop Endpoint Command, we need to * unlink any cancelled TDs from the ring. There are two ways to do that: * * 1. If the HW was in the middle of processing the TD that needs to be * cancelled, then we must move the ring's dequeue pointer past the last TRB * in the TD with a Set Dequeue Pointer Command. * 2. Otherwise, we turn all the TRBs in the TD into No-op TRBs (with the chain * bit cleared) so that the HW will skip over them. */ static void handle_stopped_endpoint(struct xhci_hcd *xhci, union xhci_trb *trb, struct xhci_event_cmd *event) { unsigned int slot_id; unsigned int ep_index; struct xhci_virt_device *virt_dev; struct xhci_ring *ep_ring; struct xhci_virt_ep *ep; struct list_head *entry; struct xhci_td *cur_td = NULL; struct xhci_td *last_unlinked_td; struct xhci_dequeue_state deq_state; if (unlikely(TRB_TO_SUSPEND_PORT( le32_to_cpu(xhci->cmd_ring->dequeue->generic.field[3])))) { slot_id = TRB_TO_SLOT_ID( le32_to_cpu(xhci->cmd_ring->dequeue->generic.field[3])); virt_dev = xhci->devs[slot_id]; if (virt_dev) handle_cmd_in_cmd_wait_list(xhci, virt_dev, event); else xhci_warn(xhci, "Stop endpoint command " "completion for disabled slot %u\n", slot_id); return; } memset(&deq_state, 0, sizeof(deq_state)); slot_id = TRB_TO_SLOT_ID(le32_to_cpu(trb->generic.field[3])); ep_index = TRB_TO_EP_INDEX(le32_to_cpu(trb->generic.field[3])); ep = &xhci->devs[slot_id]->eps[ep_index]; if (list_empty(&ep->cancelled_td_list)) { xhci_stop_watchdog_timer_in_irq(xhci, ep); ep->stopped_td = NULL; ep->stopped_trb = NULL; ring_doorbell_for_active_rings(xhci, slot_id, ep_index); return; } /* Fix up the ep ring first, so HW stops executing cancelled TDs. * We have the xHCI lock, so nothing can modify this list until we drop * it. We're also in the event handler, so we can't get re-interrupted * if another Stop Endpoint command completes */ list_for_each(entry, &ep->cancelled_td_list) { cur_td = list_entry(entry, struct xhci_td, cancelled_td_list); xhci_dbg(xhci, "Removing canceled TD starting at 0x%llx (dma).\n", (unsigned long long)xhci_trb_virt_to_dma( cur_td->start_seg, cur_td->first_trb)); ep_ring = xhci_urb_to_transfer_ring(xhci, cur_td->urb); if (!ep_ring) { /* This shouldn't happen unless a driver is mucking * with the stream ID after submission. This will * leave the TD on the hardware ring, and the hardware * will try to execute it, and may access a buffer * that has already been freed. In the best case, the * hardware will execute it, and the event handler will * ignore the completion event for that TD, since it was * removed from the td_list for that endpoint. In * short, don't muck with the stream ID after * submission. */ xhci_warn(xhci, "WARN Cancelled URB %p " "has invalid stream ID %u.\n", cur_td->urb, cur_td->urb->stream_id); goto remove_finished_td; } /* * If we stopped on the TD we need to cancel, then we have to * move the xHC endpoint ring dequeue pointer past this TD. */ if (cur_td == ep->stopped_td) xhci_find_new_dequeue_state(xhci, slot_id, ep_index, cur_td->urb->stream_id, cur_td, &deq_state); else td_to_noop(xhci, ep_ring, cur_td, false); remove_finished_td: /* * The event handler won't see a completion for this TD anymore, * so remove it from the endpoint ring's TD list. Keep it in * the cancelled TD list for URB completion later. */ list_del_init(&cur_td->td_list); } last_unlinked_td = cur_td; xhci_stop_watchdog_timer_in_irq(xhci, ep); /* If necessary, queue a Set Transfer Ring Dequeue Pointer command */ if (deq_state.new_deq_ptr && deq_state.new_deq_seg) { xhci_queue_new_dequeue_state(xhci, slot_id, ep_index, ep->stopped_td->urb->stream_id, &deq_state); xhci_ring_cmd_db(xhci); } else { /* Otherwise ring the doorbell(s) to restart queued transfers */ ring_doorbell_for_active_rings(xhci, slot_id, ep_index); } ep->stopped_td = NULL; ep->stopped_trb = NULL; /* * Drop the lock and complete the URBs in the cancelled TD list. * New TDs to be cancelled might be added to the end of the list before * we can complete all the URBs for the TDs we already unlinked. * So stop when we've completed the URB for the last TD we unlinked. */ do { cur_td = list_entry(ep->cancelled_td_list.next, struct xhci_td, cancelled_td_list); list_del_init(&cur_td->cancelled_td_list); /* Clean up the cancelled URB */ /* Doesn't matter what we pass for status, since the core will * just overwrite it (because the URB has been unlinked). */ xhci_giveback_urb_in_irq(xhci, cur_td, 0, "cancelled"); /* Stop processing the cancelled list if the watchdog timer is * running. */ if (xhci->xhc_state & XHCI_STATE_DYING) return; } while (cur_td != last_unlinked_td); /* Return to the event handler with xhci->lock re-acquired */ } /* Watchdog timer function for when a stop endpoint command fails to complete. * In this case, we assume the host controller is broken or dying or dead. The * host may still be completing some other events, so we have to be careful to * let the event ring handler and the URB dequeueing/enqueueing functions know * through xhci->state. * * The timer may also fire if the host takes a very long time to respond to the * command, and the stop endpoint command completion handler cannot delete the * timer before the timer function is called. Another endpoint cancellation may * sneak in before the timer function can grab the lock, and that may queue * another stop endpoint command and add the timer back. So we cannot use a * simple flag to say whether there is a pending stop endpoint command for a * particular endpoint. * * Instead we use a combination of that flag and a counter for the number of * pending stop endpoint commands. If the timer is the tail end of the last * stop endpoint command, and the endpoint's command is still pending, we assume * the host is dying. */ void xhci_stop_endpoint_command_watchdog(unsigned long arg) { struct xhci_hcd *xhci; struct xhci_virt_ep *ep; struct xhci_virt_ep *temp_ep; struct xhci_ring *ring; struct xhci_td *cur_td; int ret, i, j; unsigned long flags; ep = (struct xhci_virt_ep *) arg; xhci = ep->xhci; spin_lock_irqsave(&xhci->lock, flags); ep->stop_cmds_pending--; if (xhci->xhc_state & XHCI_STATE_DYING) { xhci_dbg(xhci, "Stop EP timer ran, but another timer marked " "xHCI as DYING, exiting.\n"); spin_unlock_irqrestore(&xhci->lock, flags); return; } if (!(ep->stop_cmds_pending == 0 && (ep->ep_state & EP_HALT_PENDING))) { xhci_dbg(xhci, "Stop EP timer ran, but no command pending, " "exiting.\n"); spin_unlock_irqrestore(&xhci->lock, flags); return; } xhci_warn(xhci, "xHCI host not responding to stop endpoint command.\n"); xhci_warn(xhci, "Assuming host is dying, halting host.\n"); /* Oops, HC is dead or dying or at least not responding to the stop * endpoint command. */ xhci->xhc_state |= XHCI_STATE_DYING; /* Disable interrupts from the host controller and start halting it */ xhci_quiesce(xhci); spin_unlock_irqrestore(&xhci->lock, flags); ret = xhci_halt(xhci); spin_lock_irqsave(&xhci->lock, flags); if (ret < 0) { /* This is bad; the host is not responding to commands and it's * not allowing itself to be halted. At least interrupts are * disabled. If we call usb_hc_died(), it will attempt to * disconnect all device drivers under this host. Those * disconnect() methods will wait for all URBs to be unlinked, * so we must complete them. */ xhci_warn(xhci, "Non-responsive xHCI host is not halting.\n"); xhci_warn(xhci, "Completing active URBs anyway.\n"); /* We could turn all TDs on the rings to no-ops. This won't * help if the host has cached part of the ring, and is slow if * we want to preserve the cycle bit. Skip it and hope the host * doesn't touch the memory. */ } for (i = 0; i < MAX_HC_SLOTS; i++) { if (!xhci->devs[i]) continue; for (j = 0; j < 31; j++) { temp_ep = &xhci->devs[i]->eps[j]; ring = temp_ep->ring; if (!ring) continue; xhci_dbg(xhci, "Killing URBs for slot ID %u, " "ep index %u\n", i, j); while (!list_empty(&ring->td_list)) { cur_td = list_first_entry(&ring->td_list, struct xhci_td, td_list); list_del_init(&cur_td->td_list); if (!list_empty(&cur_td->cancelled_td_list)) list_del_init(&cur_td->cancelled_td_list); xhci_giveback_urb_in_irq(xhci, cur_td, -ESHUTDOWN, "killed"); } while (!list_empty(&temp_ep->cancelled_td_list)) { cur_td = list_first_entry( &temp_ep->cancelled_td_list, struct xhci_td, cancelled_td_list); list_del_init(&cur_td->cancelled_td_list); xhci_giveback_urb_in_irq(xhci, cur_td, -ESHUTDOWN, "killed"); } } } spin_unlock_irqrestore(&xhci->lock, flags); xhci_dbg(xhci, "Calling usb_hc_died()\n"); usb_hc_died(xhci_to_hcd(xhci)->primary_hcd); xhci_dbg(xhci, "xHCI host controller is dead.\n"); } static void update_ring_for_set_deq_completion(struct xhci_hcd *xhci, struct xhci_virt_device *dev, struct xhci_ring *ep_ring, unsigned int ep_index) { union xhci_trb *dequeue_temp; int num_trbs_free_temp; bool revert = false; num_trbs_free_temp = ep_ring->num_trbs_free; dequeue_temp = ep_ring->dequeue; while (ep_ring->dequeue != dev->eps[ep_index].queued_deq_ptr) { /* We have more usable TRBs */ ep_ring->num_trbs_free++; ep_ring->dequeue++; if (last_trb(xhci, ep_ring, ep_ring->deq_seg, ep_ring->dequeue)) { if (ep_ring->dequeue == dev->eps[ep_index].queued_deq_ptr) break; ep_ring->deq_seg = ep_ring->deq_seg->next; ep_ring->dequeue = ep_ring->deq_seg->trbs; } if (ep_ring->dequeue == dequeue_temp) { revert = true; break; } } if (revert) { xhci_dbg(xhci, "Unable to find new dequeue pointer\n"); ep_ring->num_trbs_free = num_trbs_free_temp; } } /* * When we get a completion for a Set Transfer Ring Dequeue Pointer command, * we need to clear the set deq pending flag in the endpoint ring state, so that * the TD queueing code can ring the doorbell again. We also need to ring the * endpoint doorbell to restart the ring, but only if there aren't more * cancellations pending. */ static void handle_set_deq_completion(struct xhci_hcd *xhci, struct xhci_event_cmd *event, union xhci_trb *trb) { unsigned int slot_id; unsigned int ep_index; unsigned int stream_id; struct xhci_ring *ep_ring; struct xhci_virt_device *dev; struct xhci_ep_ctx *ep_ctx; struct xhci_slot_ctx *slot_ctx; slot_id = TRB_TO_SLOT_ID(le32_to_cpu(trb->generic.field[3])); ep_index = TRB_TO_EP_INDEX(le32_to_cpu(trb->generic.field[3])); stream_id = TRB_TO_STREAM_ID(le32_to_cpu(trb->generic.field[2])); dev = xhci->devs[slot_id]; ep_ring = xhci_stream_id_to_ring(dev, ep_index, stream_id); if (!ep_ring) { xhci_warn(xhci, "WARN Set TR deq ptr command for " "freed stream ID %u\n", stream_id); /* XXX: Harmless??? */ dev->eps[ep_index].ep_state &= ~SET_DEQ_PENDING; return; } ep_ctx = xhci_get_ep_ctx(xhci, dev->out_ctx, ep_index); slot_ctx = xhci_get_slot_ctx(xhci, dev->out_ctx); if (GET_COMP_CODE(le32_to_cpu(event->status)) != COMP_SUCCESS) { unsigned int ep_state; unsigned int slot_state; switch (GET_COMP_CODE(le32_to_cpu(event->status))) { case COMP_TRB_ERR: xhci_warn(xhci, "WARN Set TR Deq Ptr cmd invalid because " "of stream ID configuration\n"); break; case COMP_CTX_STATE: xhci_warn(xhci, "WARN Set TR Deq Ptr cmd failed due " "to incorrect slot or ep state.\n"); ep_state = le32_to_cpu(ep_ctx->ep_info); ep_state &= EP_STATE_MASK; slot_state = le32_to_cpu(slot_ctx->dev_state); slot_state = GET_SLOT_STATE(slot_state); xhci_dbg(xhci, "Slot state = %u, EP state = %u\n", slot_state, ep_state); break; case COMP_EBADSLT: xhci_warn(xhci, "WARN Set TR Deq Ptr cmd failed because " "slot %u was not enabled.\n", slot_id); break; default: xhci_warn(xhci, "WARN Set TR Deq Ptr cmd with unknown " "completion code of %u.\n", GET_COMP_CODE(le32_to_cpu(event->status))); break; } /* OK what do we do now? The endpoint state is hosed, and we * should never get to this point if the synchronization between * queueing, and endpoint state are correct. This might happen * if the device gets disconnected after we've finished * cancelling URBs, which might not be an error... */ } else { xhci_dbg(xhci, "Successful Set TR Deq Ptr cmd, deq = @%08llx\n", le64_to_cpu(ep_ctx->deq)); if (xhci_trb_virt_to_dma(dev->eps[ep_index].queued_deq_seg, dev->eps[ep_index].queued_deq_ptr) == (le64_to_cpu(ep_ctx->deq) & ~(EP_CTX_CYCLE_MASK))) { /* Update the ring's dequeue segment and dequeue pointer * to reflect the new position. */ update_ring_for_set_deq_completion(xhci, dev, ep_ring, ep_index); } else { xhci_warn(xhci, "Mismatch between completed Set TR Deq " "Ptr command & xHCI internal state.\n"); xhci_warn(xhci, "ep deq seg = %p, deq ptr = %p\n", dev->eps[ep_index].queued_deq_seg, dev->eps[ep_index].queued_deq_ptr); } } dev->eps[ep_index].ep_state &= ~SET_DEQ_PENDING; dev->eps[ep_index].queued_deq_seg = NULL; dev->eps[ep_index].queued_deq_ptr = NULL; /* Restart any rings with pending URBs */ ring_doorbell_for_active_rings(xhci, slot_id, ep_index); } static void handle_reset_ep_completion(struct xhci_hcd *xhci, struct xhci_event_cmd *event, union xhci_trb *trb) { int slot_id; unsigned int ep_index; slot_id = TRB_TO_SLOT_ID(le32_to_cpu(trb->generic.field[3])); ep_index = TRB_TO_EP_INDEX(le32_to_cpu(trb->generic.field[3])); /* This command will only fail if the endpoint wasn't halted, * but we don't care. */ xhci_dbg(xhci, "Ignoring reset ep completion code of %u\n", GET_COMP_CODE(le32_to_cpu(event->status))); /* HW with the reset endpoint quirk needs to have a configure endpoint * command complete before the endpoint can be used. Queue that here * because the HW can't handle two commands being queued in a row. */ if (xhci->quirks & XHCI_RESET_EP_QUIRK) { xhci_dbg(xhci, "Queueing configure endpoint command\n"); xhci_queue_configure_endpoint(xhci, xhci->devs[slot_id]->in_ctx->dma, slot_id, false); xhci_ring_cmd_db(xhci); } else { /* Clear our internal halted state and restart the ring(s) */ xhci->devs[slot_id]->eps[ep_index].ep_state &= ~EP_HALTED; ring_doorbell_for_active_rings(xhci, slot_id, ep_index); } } /* Check to see if a command in the device's command queue matches this one. * Signal the completion or free the command, and return 1. Return 0 if the * completed command isn't at the head of the command list. */ static int handle_cmd_in_cmd_wait_list(struct xhci_hcd *xhci, struct xhci_virt_device *virt_dev, struct xhci_event_cmd *event) { struct xhci_command *command; if (list_empty(&virt_dev->cmd_list)) return 0; command = list_entry(virt_dev->cmd_list.next, struct xhci_command, cmd_list); if (xhci->cmd_ring->dequeue != command->command_trb) return 0; command->status = GET_COMP_CODE(le32_to_cpu(event->status)); list_del(&command->cmd_list); if (command->completion) complete(command->completion); else xhci_free_command(xhci, command); return 1; } static void handle_cmd_completion(struct xhci_hcd *xhci, struct xhci_event_cmd *event) { int slot_id = TRB_TO_SLOT_ID(le32_to_cpu(event->flags)); u64 cmd_dma; dma_addr_t cmd_dequeue_dma; struct xhci_input_control_ctx *ctrl_ctx; struct xhci_virt_device *virt_dev; unsigned int ep_index; struct xhci_ring *ep_ring; unsigned int ep_state; cmd_dma = le64_to_cpu(event->cmd_trb); cmd_dequeue_dma = xhci_trb_virt_to_dma(xhci->cmd_ring->deq_seg, xhci->cmd_ring->dequeue); /* Is the command ring deq ptr out of sync with the deq seg ptr? */ if (cmd_dequeue_dma == 0) { xhci->error_bitmask |= 1 << 4; return; } /* Does the DMA address match our internal dequeue pointer address? */ if (cmd_dma != (u64) cmd_dequeue_dma) { xhci->error_bitmask |= 1 << 5; return; } switch (le32_to_cpu(xhci->cmd_ring->dequeue->generic.field[3]) & TRB_TYPE_BITMASK) { case TRB_TYPE(TRB_ENABLE_SLOT): if (GET_COMP_CODE(le32_to_cpu(event->status)) == COMP_SUCCESS) xhci->slot_id = slot_id; else xhci->slot_id = 0; complete(&xhci->addr_dev); break; case TRB_TYPE(TRB_DISABLE_SLOT): if (xhci->devs[slot_id]) { if (xhci->quirks & XHCI_EP_LIMIT_QUIRK) /* Delete default control endpoint resources */ xhci_free_device_endpoint_resources(xhci, xhci->devs[slot_id], true); xhci_free_virt_device(xhci, slot_id); } break; case TRB_TYPE(TRB_CONFIG_EP): virt_dev = xhci->devs[slot_id]; if (handle_cmd_in_cmd_wait_list(xhci, virt_dev, event)) break; /* * Configure endpoint commands can come from the USB core * configuration or alt setting changes, or because the HW * needed an extra configure endpoint command after a reset * endpoint command or streams were being configured. * If the command was for a halted endpoint, the xHCI driver * is not waiting on the configure endpoint command. */ ctrl_ctx = xhci_get_input_control_ctx(xhci, virt_dev->in_ctx); /* Input ctx add_flags are the endpoint index plus one */ ep_index = xhci_last_valid_endpoint(le32_to_cpu(ctrl_ctx->add_flags)) - 1; /* A usb_set_interface() call directly after clearing a halted * condition may race on this quirky hardware. Not worth * worrying about, since this is prototype hardware. Not sure * if this will work for streams, but streams support was * untested on this prototype. */ if (xhci->quirks & XHCI_RESET_EP_QUIRK && ep_index != (unsigned int) -1 && le32_to_cpu(ctrl_ctx->add_flags) - SLOT_FLAG == le32_to_cpu(ctrl_ctx->drop_flags)) { ep_ring = xhci->devs[slot_id]->eps[ep_index].ring; ep_state = xhci->devs[slot_id]->eps[ep_index].ep_state; if (!(ep_state & EP_HALTED)) goto bandwidth_change; xhci_dbg(xhci, "Completed config ep cmd - " "last ep index = %d, state = %d\n", ep_index, ep_state); /* Clear internal halted state and restart ring(s) */ xhci->devs[slot_id]->eps[ep_index].ep_state &= ~EP_HALTED; ring_doorbell_for_active_rings(xhci, slot_id, ep_index); break; } bandwidth_change: xhci_dbg(xhci, "Completed config ep cmd\n"); xhci->devs[slot_id]->cmd_status = GET_COMP_CODE(le32_to_cpu(event->status)); complete(&xhci->devs[slot_id]->cmd_completion); break; case TRB_TYPE(TRB_EVAL_CONTEXT): virt_dev = xhci->devs[slot_id]; if (handle_cmd_in_cmd_wait_list(xhci, virt_dev, event)) break; xhci->devs[slot_id]->cmd_status = GET_COMP_CODE(le32_to_cpu(event->status)); complete(&xhci->devs[slot_id]->cmd_completion); break; case TRB_TYPE(TRB_ADDR_DEV): xhci->devs[slot_id]->cmd_status = GET_COMP_CODE(le32_to_cpu(event->status)); complete(&xhci->addr_dev); break; case TRB_TYPE(TRB_STOP_RING): handle_stopped_endpoint(xhci, xhci->cmd_ring->dequeue, event); break; case TRB_TYPE(TRB_SET_DEQ): handle_set_deq_completion(xhci, event, xhci->cmd_ring->dequeue); break; case TRB_TYPE(TRB_CMD_NOOP): break; case TRB_TYPE(TRB_RESET_EP): handle_reset_ep_completion(xhci, event, xhci->cmd_ring->dequeue); break; case TRB_TYPE(TRB_RESET_DEV): xhci_dbg(xhci, "Completed reset device command.\n"); slot_id = TRB_TO_SLOT_ID( le32_to_cpu(xhci->cmd_ring->dequeue->generic.field[3])); virt_dev = xhci->devs[slot_id]; if (virt_dev) handle_cmd_in_cmd_wait_list(xhci, virt_dev, event); else xhci_warn(xhci, "Reset device command completion " "for disabled slot %u\n", slot_id); break; case TRB_TYPE(TRB_NEC_GET_FW): if (!(xhci->quirks & XHCI_NEC_HOST)) { xhci->error_bitmask |= 1 << 6; break; } xhci_dbg(xhci, "NEC firmware version %2x.%02x\n", NEC_FW_MAJOR(le32_to_cpu(event->status)), NEC_FW_MINOR(le32_to_cpu(event->status))); break; default: /* Skip over unknown commands on the event ring */ xhci->error_bitmask |= 1 << 6; break; } inc_deq(xhci, xhci->cmd_ring); } static void handle_vendor_event(struct xhci_hcd *xhci, union xhci_trb *event) { u32 trb_type; trb_type = TRB_FIELD_TO_TYPE(le32_to_cpu(event->generic.field[3])); xhci_dbg(xhci, "Vendor specific event TRB type = %u\n", trb_type); if (trb_type == TRB_NEC_CMD_COMP && (xhci->quirks & XHCI_NEC_HOST)) handle_cmd_completion(xhci, &event->event_cmd); } /* @port_id: the one-based port ID from the hardware (indexed from array of all * port registers -- USB 3.0 and USB 2.0). * * Returns a zero-based port number, which is suitable for indexing into each of * the split roothubs' port arrays and bus state arrays. * Add one to it in order to call xhci_find_slot_id_by_port. */ static unsigned int find_faked_portnum_from_hw_portnum(struct usb_hcd *hcd, struct xhci_hcd *xhci, u32 port_id) { unsigned int i; unsigned int num_similar_speed_ports = 0; /* port_id from the hardware is 1-based, but port_array[], usb3_ports[], * and usb2_ports are 0-based indexes. Count the number of similar * speed ports, up to 1 port before this port. */ for (i = 0; i < (port_id - 1); i++) { u8 port_speed = xhci->port_array[i]; /* * Skip ports that don't have known speeds, or have duplicate * Extended Capabilities port speed entries. */ if (port_speed == 0 || port_speed == DUPLICATE_ENTRY) continue; /* * USB 3.0 ports are always under a USB 3.0 hub. USB 2.0 and * 1.1 ports are under the USB 2.0 hub. If the port speed * matches the device speed, it's a similar speed port. */ if ((port_speed == 0x03) == (hcd->speed == HCD_USB3)) num_similar_speed_ports++; } return num_similar_speed_ports; } static void handle_device_notification(struct xhci_hcd *xhci, union xhci_trb *event) { u32 slot_id; struct usb_device *udev; slot_id = TRB_TO_SLOT_ID(event->generic.field[3]); if (!xhci->devs[slot_id]) { xhci_warn(xhci, "Device Notification event for " "unused slot %u\n", slot_id); return; } xhci_dbg(xhci, "Device Wake Notification event for slot ID %u\n", slot_id); udev = xhci->devs[slot_id]->udev; if (udev && udev->parent) usb_wakeup_notification(udev->parent, udev->portnum); } static void handle_port_status(struct xhci_hcd *xhci, union xhci_trb *event) { struct usb_hcd *hcd; u32 port_id; u32 temp, temp1; int max_ports; int slot_id; unsigned int faked_port_index; u8 major_revision; struct xhci_bus_state *bus_state; __le32 __iomem **port_array; bool bogus_port_status = false; /* Port status change events always have a successful completion code */ if (GET_COMP_CODE(le32_to_cpu(event->generic.field[2])) != COMP_SUCCESS) { xhci_warn(xhci, "WARN: xHC returned failed port status event\n"); xhci->error_bitmask |= 1 << 8; } port_id = GET_PORT_ID(le32_to_cpu(event->generic.field[0])); xhci_dbg(xhci, "Port Status Change Event for port %d\n", port_id); max_ports = HCS_MAX_PORTS(xhci->hcs_params1); if ((port_id <= 0) || (port_id > max_ports)) { xhci_warn(xhci, "Invalid port id %d\n", port_id); bogus_port_status = true; goto cleanup; } /* Figure out which usb_hcd this port is attached to: * is it a USB 3.0 port or a USB 2.0/1.1 port? */ major_revision = xhci->port_array[port_id - 1]; if (major_revision == 0) { xhci_warn(xhci, "Event for port %u not in " "Extended Capabilities, ignoring.\n", port_id); bogus_port_status = true; goto cleanup; } if (major_revision == DUPLICATE_ENTRY) { xhci_warn(xhci, "Event for port %u duplicated in" "Extended Capabilities, ignoring.\n", port_id); bogus_port_status = true; goto cleanup; } /* * Hardware port IDs reported by a Port Status Change Event include USB * 3.0 and USB 2.0 ports. We want to check if the port has reported a * resume event, but we first need to translate the hardware port ID * into the index into the ports on the correct split roothub, and the * correct bus_state structure. */ /* Find the right roothub. */ hcd = xhci_to_hcd(xhci); if ((major_revision == 0x03) != (hcd->speed == HCD_USB3)) hcd = xhci->shared_hcd; bus_state = &xhci->bus_state[hcd_index(hcd)]; if (hcd->speed == HCD_USB3) port_array = xhci->usb3_ports; else port_array = xhci->usb2_ports; /* Find the faked port hub number */ faked_port_index = find_faked_portnum_from_hw_portnum(hcd, xhci, port_id); temp = xhci_readl(xhci, port_array[faked_port_index]); if (hcd->state == HC_STATE_SUSPENDED) { xhci_dbg(xhci, "resume root hub\n"); usb_hcd_resume_root_hub(hcd); } if ((temp & PORT_PLC) && (temp & PORT_PLS_MASK) == XDEV_RESUME) { xhci_dbg(xhci, "port resume event for port %d\n", port_id); temp1 = xhci_readl(xhci, &xhci->op_regs->command); if (!(temp1 & CMD_RUN)) { xhci_warn(xhci, "xHC is not running.\n"); goto cleanup; } if (DEV_SUPERSPEED(temp)) { xhci_dbg(xhci, "remote wake SS port %d\n", port_id); /* Set a flag to say the port signaled remote wakeup, * so we can tell the difference between the end of * device and host initiated resume. */ bus_state->port_remote_wakeup |= 1 << faked_port_index; xhci_test_and_clear_bit(xhci, port_array, faked_port_index, PORT_PLC); xhci_set_link_state(xhci, port_array, faked_port_index, XDEV_U0); /* Need to wait until the next link state change * indicates the device is actually in U0. */ bogus_port_status = true; goto cleanup; } else { xhci_dbg(xhci, "resume HS port %d\n", port_id); bus_state->resume_done[faked_port_index] = jiffies + msecs_to_jiffies(20); mod_timer(&hcd->rh_timer, bus_state->resume_done[faked_port_index]); /* Do the rest in GetPortStatus */ } } if ((temp & PORT_PLC) && (temp & PORT_PLS_MASK) == XDEV_U0 && DEV_SUPERSPEED(temp)) { xhci_dbg(xhci, "resume SS port %d finished\n", port_id); /* We've just brought the device into U0 through either the * Resume state after a device remote wakeup, or through the * U3Exit state after a host-initiated resume. If it's a device * initiated remote wake, don't pass up the link state change, * so the roothub behavior is consistent with external * USB 3.0 hub behavior. */ slot_id = xhci_find_slot_id_by_port(hcd, xhci, faked_port_index + 1); if (slot_id && xhci->devs[slot_id]) xhci_ring_device(xhci, slot_id); if (bus_state->port_remote_wakeup && (1 << faked_port_index)) { bus_state->port_remote_wakeup &= ~(1 << faked_port_index); xhci_test_and_clear_bit(xhci, port_array, faked_port_index, PORT_PLC); usb_wakeup_notification(hcd->self.root_hub, faked_port_index + 1); bogus_port_status = true; goto cleanup; } } if (hcd->speed != HCD_USB3) xhci_test_and_clear_bit(xhci, port_array, faked_port_index, PORT_PLC); cleanup: /* Update event ring dequeue pointer before dropping the lock */ inc_deq(xhci, xhci->event_ring); /* Don't make the USB core poll the roothub if we got a bad port status * change event. Besides, at that point we can't tell which roothub * (USB 2.0 or USB 3.0) to kick. */ if (bogus_port_status) return; spin_unlock(&xhci->lock); /* Pass this up to the core */ usb_hcd_poll_rh_status(hcd); spin_lock(&xhci->lock); } /* * This TD is defined by the TRBs starting at start_trb in start_seg and ending * at end_trb, which may be in another segment. If the suspect DMA address is a * TRB in this TD, this function returns that TRB's segment. Otherwise it * returns 0. */ struct xhci_segment *trb_in_td(struct xhci_segment *start_seg, union xhci_trb *start_trb, union xhci_trb *end_trb, dma_addr_t suspect_dma) { dma_addr_t start_dma; dma_addr_t end_seg_dma; dma_addr_t end_trb_dma; struct xhci_segment *cur_seg; start_dma = xhci_trb_virt_to_dma(start_seg, start_trb); cur_seg = start_seg; do { if (start_dma == 0) return NULL; /* We may get an event for a Link TRB in the middle of a TD */ end_seg_dma = xhci_trb_virt_to_dma(cur_seg, &cur_seg->trbs[TRBS_PER_SEGMENT - 1]); /* If the end TRB isn't in this segment, this is set to 0 */ end_trb_dma = xhci_trb_virt_to_dma(cur_seg, end_trb); if (end_trb_dma > 0) { /* The end TRB is in this segment, so suspect should be here */ if (start_dma <= end_trb_dma) { if (suspect_dma >= start_dma && suspect_dma <= end_trb_dma) return cur_seg; } else { /* Case for one segment with * a TD wrapped around to the top */ if ((suspect_dma >= start_dma && suspect_dma <= end_seg_dma) || (suspect_dma >= cur_seg->dma && suspect_dma <= end_trb_dma)) return cur_seg; } return NULL; } else { /* Might still be somewhere in this segment */ if (suspect_dma >= start_dma && suspect_dma <= end_seg_dma) return cur_seg; } cur_seg = cur_seg->next; start_dma = xhci_trb_virt_to_dma(cur_seg, &cur_seg->trbs[0]); } while (cur_seg != start_seg); return NULL; } static void xhci_cleanup_halted_endpoint(struct xhci_hcd *xhci, unsigned int slot_id, unsigned int ep_index, unsigned int stream_id, struct xhci_td *td, union xhci_trb *event_trb) { struct xhci_virt_ep *ep = &xhci->devs[slot_id]->eps[ep_index]; ep->ep_state |= EP_HALTED; ep->stopped_td = td; ep->stopped_trb = event_trb; ep->stopped_stream = stream_id; xhci_queue_reset_ep(xhci, slot_id, ep_index); xhci_cleanup_stalled_ring(xhci, td->urb->dev, ep_index); ep->stopped_td = NULL; ep->stopped_trb = NULL; ep->stopped_stream = 0; xhci_ring_cmd_db(xhci); } /* Check if an error has halted the endpoint ring. The class driver will * cleanup the halt for a non-default control endpoint if we indicate a stall. * However, a babble and other errors also halt the endpoint ring, and the class * driver won't clear the halt in that case, so we need to issue a Set Transfer * Ring Dequeue Pointer command manually. */ static int xhci_requires_manual_halt_cleanup(struct xhci_hcd *xhci, struct xhci_ep_ctx *ep_ctx, unsigned int trb_comp_code) { /* TRB completion codes that may require a manual halt cleanup */ if (trb_comp_code == COMP_TX_ERR || trb_comp_code == COMP_BABBLE || trb_comp_code == COMP_SPLIT_ERR) /* The 0.96 spec says a babbling control endpoint * is not halted. The 0.96 spec says it is. Some HW * claims to be 0.95 compliant, but it halts the control * endpoint anyway. Check if a babble halted the * endpoint. */ if ((ep_ctx->ep_info & cpu_to_le32(EP_STATE_MASK)) == cpu_to_le32(EP_STATE_HALTED)) return 1; return 0; } int xhci_is_vendor_info_code(struct xhci_hcd *xhci, unsigned int trb_comp_code) { if (trb_comp_code >= 224 && trb_comp_code <= 255) { /* Vendor defined "informational" completion code, * treat as not-an-error. */ xhci_dbg(xhci, "Vendor defined info completion code %u\n", trb_comp_code); xhci_dbg(xhci, "Treating code as success.\n"); return 1; } return 0; } /* * Finish the td processing, remove the td from td list; * Return 1 if the urb can be given back. */ static int finish_td(struct xhci_hcd *xhci, struct xhci_td *td, union xhci_trb *event_trb, struct xhci_transfer_event *event, struct xhci_virt_ep *ep, int *status, bool skip) { struct xhci_virt_device *xdev; struct xhci_ring *ep_ring; unsigned int slot_id; int ep_index; struct urb *urb = NULL; struct xhci_ep_ctx *ep_ctx; int ret = 0; struct urb_priv *urb_priv; u32 trb_comp_code; slot_id = TRB_TO_SLOT_ID(le32_to_cpu(event->flags)); xdev = xhci->devs[slot_id]; ep_index = TRB_TO_EP_ID(le32_to_cpu(event->flags)) - 1; ep_ring = xhci_dma_to_transfer_ring(ep, le64_to_cpu(event->buffer)); ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index); trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len)); if (skip) goto td_cleanup; if (trb_comp_code == COMP_STOP_INVAL || trb_comp_code == COMP_STOP) { /* The Endpoint Stop Command completion will take care of any * stopped TDs. A stopped TD may be restarted, so don't update * the ring dequeue pointer or take this TD off any lists yet. */ ep->stopped_td = td; ep->stopped_trb = event_trb; return 0; } else { if (trb_comp_code == COMP_STALL) { /* The transfer is completed from the driver's * perspective, but we need to issue a set dequeue * command for this stalled endpoint to move the dequeue * pointer past the TD. We can't do that here because * the halt condition must be cleared first. Let the * USB class driver clear the stall later. */ ep->stopped_td = td; ep->stopped_trb = event_trb; ep->stopped_stream = ep_ring->stream_id; } else if (xhci_requires_manual_halt_cleanup(xhci, ep_ctx, trb_comp_code)) { /* Other types of errors halt the endpoint, but the * class driver doesn't call usb_reset_endpoint() unless * the error is -EPIPE. Clear the halted status in the * xHCI hardware manually. */ xhci_cleanup_halted_endpoint(xhci, slot_id, ep_index, ep_ring->stream_id, td, event_trb); } else { /* Update ring dequeue pointer */ while (ep_ring->dequeue != td->last_trb) inc_deq(xhci, ep_ring); inc_deq(xhci, ep_ring); } td_cleanup: /* Clean up the endpoint's TD list */ urb = td->urb; urb_priv = urb->hcpriv; /* Do one last check of the actual transfer length. * If the host controller said we transferred more data than * the buffer length, urb->actual_length will be a very big * number (since it's unsigned). Play it safe and say we didn't * transfer anything. */ if (urb->actual_length > urb->transfer_buffer_length) { xhci_warn(xhci, "URB transfer length is wrong, " "xHC issue? req. len = %u, " "act. len = %u\n", urb->transfer_buffer_length, urb->actual_length); urb->actual_length = 0; if (td->urb->transfer_flags & URB_SHORT_NOT_OK) *status = -EREMOTEIO; else *status = 0; } list_del_init(&td->td_list); /* Was this TD slated to be cancelled but completed anyway? */ if (!list_empty(&td->cancelled_td_list)) list_del_init(&td->cancelled_td_list); urb_priv->td_cnt++; /* Giveback the urb when all the tds are completed */ if (urb_priv->td_cnt == urb_priv->length) { ret = 1; if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS) { xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs--; if (xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs == 0) { if (xhci->quirks & XHCI_AMD_PLL_FIX) usb_amd_quirk_pll_enable(); } } } } return ret; } /* * Process control tds, update urb status and actual_length. */ static int process_ctrl_td(struct xhci_hcd *xhci, struct xhci_td *td, union xhci_trb *event_trb, struct xhci_transfer_event *event, struct xhci_virt_ep *ep, int *status) { struct xhci_virt_device *xdev; struct xhci_ring *ep_ring; unsigned int slot_id; int ep_index; struct xhci_ep_ctx *ep_ctx; u32 trb_comp_code; slot_id = TRB_TO_SLOT_ID(le32_to_cpu(event->flags)); xdev = xhci->devs[slot_id]; ep_index = TRB_TO_EP_ID(le32_to_cpu(event->flags)) - 1; ep_ring = xhci_dma_to_transfer_ring(ep, le64_to_cpu(event->buffer)); ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index); trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len)); switch (trb_comp_code) { case COMP_SUCCESS: if (event_trb == ep_ring->dequeue) { xhci_warn(xhci, "WARN: Success on ctrl setup TRB " "without IOC set??\n"); *status = -ESHUTDOWN; } else if (event_trb != td->last_trb) { xhci_warn(xhci, "WARN: Success on ctrl data TRB " "without IOC set??\n"); *status = -ESHUTDOWN; } else { *status = 0; } break; case COMP_SHORT_TX: if (td->urb->transfer_flags & URB_SHORT_NOT_OK) *status = -EREMOTEIO; else *status = 0; break; case COMP_STOP_INVAL: case COMP_STOP: return finish_td(xhci, td, event_trb, event, ep, status, false); default: if (!xhci_requires_manual_halt_cleanup(xhci, ep_ctx, trb_comp_code)) break; xhci_dbg(xhci, "TRB error code %u, " "halted endpoint index = %u\n", trb_comp_code, ep_index); /* else fall through */ case COMP_STALL: /* Did we transfer part of the data (middle) phase? */ if (event_trb != ep_ring->dequeue && event_trb != td->last_trb) td->urb->actual_length = td->urb->transfer_buffer_length - TRB_LEN(le32_to_cpu(event->transfer_len)); else td->urb->actual_length = 0; xhci_cleanup_halted_endpoint(xhci, slot_id, ep_index, 0, td, event_trb); return finish_td(xhci, td, event_trb, event, ep, status, true); } /* * Did we transfer any data, despite the errors that might have * happened? I.e. did we get past the setup stage? */ if (event_trb != ep_ring->dequeue) { /* The event was for the status stage */ if (event_trb == td->last_trb) { if (td->urb->actual_length != 0) { /* Don't overwrite a previously set error code */ if ((*status == -EINPROGRESS || *status == 0) && (td->urb->transfer_flags & URB_SHORT_NOT_OK)) /* Did we already see a short data * stage? */ *status = -EREMOTEIO; } else { td->urb->actual_length = td->urb->transfer_buffer_length; } } else { /* Maybe the event was for the data stage? */ td->urb->actual_length = td->urb->transfer_buffer_length - TRB_LEN(le32_to_cpu(event->transfer_len)); xhci_dbg(xhci, "Waiting for status " "stage event\n"); return 0; } } return finish_td(xhci, td, event_trb, event, ep, status, false); } /* * Process isochronous tds, update urb packet status and actual_length. */ static int process_isoc_td(struct xhci_hcd *xhci, struct xhci_td *td, union xhci_trb *event_trb, struct xhci_transfer_event *event, struct xhci_virt_ep *ep, int *status) { struct xhci_ring *ep_ring; struct urb_priv *urb_priv; int idx; int len = 0; union xhci_trb *cur_trb; struct xhci_segment *cur_seg; struct usb_iso_packet_descriptor *frame; u32 trb_comp_code; bool skip_td = false; ep_ring = xhci_dma_to_transfer_ring(ep, le64_to_cpu(event->buffer)); trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len)); urb_priv = td->urb->hcpriv; idx = urb_priv->td_cnt; frame = &td->urb->iso_frame_desc[idx]; /* handle completion code */ switch (trb_comp_code) { case COMP_SUCCESS: frame->status = 0; break; case COMP_SHORT_TX: frame->status = td->urb->transfer_flags & URB_SHORT_NOT_OK ? -EREMOTEIO : 0; break; case COMP_BW_OVER: frame->status = -ECOMM; skip_td = true; break; case COMP_BUFF_OVER: case COMP_BABBLE: frame->status = -EOVERFLOW; skip_td = true; break; case COMP_DEV_ERR: case COMP_STALL: frame->status = -EPROTO; skip_td = true; break; case COMP_STOP: case COMP_STOP_INVAL: break; default: frame->status = -1; break; } if (trb_comp_code == COMP_SUCCESS || skip_td) { frame->actual_length = frame->length; td->urb->actual_length += frame->length; } else { for (cur_trb = ep_ring->dequeue, cur_seg = ep_ring->deq_seg; cur_trb != event_trb; next_trb(xhci, ep_ring, &cur_seg, &cur_trb)) { if (!TRB_TYPE_NOOP_LE32(cur_trb->generic.field[3]) && !TRB_TYPE_LINK_LE32(cur_trb->generic.field[3])) len += TRB_LEN(le32_to_cpu(cur_trb->generic.field[2])); } len += TRB_LEN(le32_to_cpu(cur_trb->generic.field[2])) - TRB_LEN(le32_to_cpu(event->transfer_len)); if (trb_comp_code != COMP_STOP_INVAL) { frame->actual_length = len; td->urb->actual_length += len; } } return finish_td(xhci, td, event_trb, event, ep, status, false); } static int skip_isoc_td(struct xhci_hcd *xhci, struct xhci_td *td, struct xhci_transfer_event *event, struct xhci_virt_ep *ep, int *status) { struct xhci_ring *ep_ring; struct urb_priv *urb_priv; struct usb_iso_packet_descriptor *frame; int idx; ep_ring = xhci_dma_to_transfer_ring(ep, le64_to_cpu(event->buffer)); urb_priv = td->urb->hcpriv; idx = urb_priv->td_cnt; frame = &td->urb->iso_frame_desc[idx]; /* The transfer is partly done. */ frame->status = -EXDEV; /* calc actual length */ frame->actual_length = 0; /* Update ring dequeue pointer */ while (ep_ring->dequeue != td->last_trb) inc_deq(xhci, ep_ring); inc_deq(xhci, ep_ring); return finish_td(xhci, td, NULL, event, ep, status, true); } /* * Process bulk and interrupt tds, update urb status and actual_length. */ static int process_bulk_intr_td(struct xhci_hcd *xhci, struct xhci_td *td, union xhci_trb *event_trb, struct xhci_transfer_event *event, struct xhci_virt_ep *ep, int *status) { struct xhci_ring *ep_ring; union xhci_trb *cur_trb; struct xhci_segment *cur_seg; u32 trb_comp_code; ep_ring = xhci_dma_to_transfer_ring(ep, le64_to_cpu(event->buffer)); trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len)); switch (trb_comp_code) { case COMP_SUCCESS: /* Double check that the HW transferred everything. */ if (event_trb != td->last_trb) { xhci_warn(xhci, "WARN Successful completion " "on short TX\n"); if (td->urb->transfer_flags & URB_SHORT_NOT_OK) *status = -EREMOTEIO; else *status = 0; } else { *status = 0; } break; case COMP_SHORT_TX: if (td->urb->transfer_flags & URB_SHORT_NOT_OK) *status = -EREMOTEIO; else *status = 0; break; default: /* Others already handled above */ break; } if (trb_comp_code == COMP_SHORT_TX) xhci_dbg(xhci, "ep %#x - asked for %d bytes, " "%d bytes untransferred\n", td->urb->ep->desc.bEndpointAddress, td->urb->transfer_buffer_length, TRB_LEN(le32_to_cpu(event->transfer_len))); /* Fast path - was this the last TRB in the TD for this URB? */ if (event_trb == td->last_trb) { if (TRB_LEN(le32_to_cpu(event->transfer_len)) != 0) { td->urb->actual_length = td->urb->transfer_buffer_length - TRB_LEN(le32_to_cpu(event->transfer_len)); if (td->urb->transfer_buffer_length < td->urb->actual_length) { xhci_warn(xhci, "HC gave bad length " "of %d bytes left\n", TRB_LEN(le32_to_cpu(event->transfer_len))); td->urb->actual_length = 0; if (td->urb->transfer_flags & URB_SHORT_NOT_OK) *status = -EREMOTEIO; else *status = 0; } /* Don't overwrite a previously set error code */ if (*status == -EINPROGRESS) { if (td->urb->transfer_flags & URB_SHORT_NOT_OK) *status = -EREMOTEIO; else *status = 0; } } else { td->urb->actual_length = td->urb->transfer_buffer_length; /* Ignore a short packet completion if the * untransferred length was zero. */ if (*status == -EREMOTEIO) *status = 0; } } else { /* Slow path - walk the list, starting from the dequeue * pointer, to get the actual length transferred. */ td->urb->actual_length = 0; for (cur_trb = ep_ring->dequeue, cur_seg = ep_ring->deq_seg; cur_trb != event_trb; next_trb(xhci, ep_ring, &cur_seg, &cur_trb)) { if (!TRB_TYPE_NOOP_LE32(cur_trb->generic.field[3]) && !TRB_TYPE_LINK_LE32(cur_trb->generic.field[3])) td->urb->actual_length += TRB_LEN(le32_to_cpu(cur_trb->generic.field[2])); } /* If the ring didn't stop on a Link or No-op TRB, add * in the actual bytes transferred from the Normal TRB */ if (trb_comp_code != COMP_STOP_INVAL) td->urb->actual_length += TRB_LEN(le32_to_cpu(cur_trb->generic.field[2])) - TRB_LEN(le32_to_cpu(event->transfer_len)); } return finish_td(xhci, td, event_trb, event, ep, status, false); } /* * If this function returns an error condition, it means it got a Transfer * event with a corrupted Slot ID, Endpoint ID, or TRB DMA address. * At this point, the host controller is probably hosed and should be reset. */ static int handle_tx_event(struct xhci_hcd *xhci, struct xhci_transfer_event *event) { struct xhci_virt_device *xdev; struct xhci_virt_ep *ep; struct xhci_ring *ep_ring; unsigned int slot_id; int ep_index; struct xhci_td *td = NULL; dma_addr_t event_dma; struct xhci_segment *event_seg; union xhci_trb *event_trb; struct urb *urb = NULL; int status = -EINPROGRESS; struct urb_priv *urb_priv; struct xhci_ep_ctx *ep_ctx; struct list_head *tmp; u32 trb_comp_code; int ret = 0; int td_num = 0; slot_id = TRB_TO_SLOT_ID(le32_to_cpu(event->flags)); xdev = xhci->devs[slot_id]; if (!xdev) { xhci_err(xhci, "ERROR Transfer event pointed to bad slot\n"); xhci_err(xhci, "@%016llx %08x %08x %08x %08x\n", (unsigned long long) xhci_trb_virt_to_dma( xhci->event_ring->deq_seg, xhci->event_ring->dequeue), lower_32_bits(le64_to_cpu(event->buffer)), upper_32_bits(le64_to_cpu(event->buffer)), le32_to_cpu(event->transfer_len), le32_to_cpu(event->flags)); xhci_dbg(xhci, "Event ring:\n"); xhci_debug_segment(xhci, xhci->event_ring->deq_seg); return -ENODEV; } /* Endpoint ID is 1 based, our index is zero based */ ep_index = TRB_TO_EP_ID(le32_to_cpu(event->flags)) - 1; ep = &xdev->eps[ep_index]; ep_ring = xhci_dma_to_transfer_ring(ep, le64_to_cpu(event->buffer)); ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index); if (!ep_ring || (le32_to_cpu(ep_ctx->ep_info) & EP_STATE_MASK) == EP_STATE_DISABLED) { xhci_err(xhci, "ERROR Transfer event for disabled endpoint " "or incorrect stream ring\n"); xhci_err(xhci, "@%016llx %08x %08x %08x %08x\n", (unsigned long long) xhci_trb_virt_to_dma( xhci->event_ring->deq_seg, xhci->event_ring->dequeue), lower_32_bits(le64_to_cpu(event->buffer)), upper_32_bits(le64_to_cpu(event->buffer)), le32_to_cpu(event->transfer_len), le32_to_cpu(event->flags)); xhci_dbg(xhci, "Event ring:\n"); xhci_debug_segment(xhci, xhci->event_ring->deq_seg); return -ENODEV; } /* Count current td numbers if ep->skip is set */ if (ep->skip) { list_for_each(tmp, &ep_ring->td_list) td_num++; } event_dma = le64_to_cpu(event->buffer); trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len)); /* Look for common error cases */ switch (trb_comp_code) { /* Skip codes that require special handling depending on * transfer type */ case COMP_SUCCESS: case COMP_SHORT_TX: break; case COMP_STOP: xhci_dbg(xhci, "Stopped on Transfer TRB\n"); break; case COMP_STOP_INVAL: xhci_dbg(xhci, "Stopped on No-op or Link TRB\n"); break; case COMP_STALL: xhci_dbg(xhci, "Stalled endpoint\n"); ep->ep_state |= EP_HALTED; status = -EPIPE; break; case COMP_TRB_ERR: xhci_warn(xhci, "WARN: TRB error on endpoint\n"); status = -EILSEQ; break; case COMP_SPLIT_ERR: case COMP_TX_ERR: xhci_dbg(xhci, "Transfer error on endpoint\n"); status = -EPROTO; break; case COMP_BABBLE: xhci_dbg(xhci, "Babble error on endpoint\n"); status = -EOVERFLOW; break; case COMP_DB_ERR: xhci_warn(xhci, "WARN: HC couldn't access mem fast enough\n"); status = -ENOSR; break; case COMP_BW_OVER: xhci_warn(xhci, "WARN: bandwidth overrun event on endpoint\n"); break; case COMP_BUFF_OVER: xhci_warn(xhci, "WARN: buffer overrun event on endpoint\n"); break; case COMP_UNDERRUN: /* * When the Isoch ring is empty, the xHC will generate * a Ring Overrun Event for IN Isoch endpoint or Ring * Underrun Event for OUT Isoch endpoint. */ xhci_dbg(xhci, "underrun event on endpoint\n"); if (!list_empty(&ep_ring->td_list)) xhci_dbg(xhci, "Underrun Event for slot %d ep %d " "still with TDs queued?\n", TRB_TO_SLOT_ID(le32_to_cpu(event->flags)), ep_index); goto cleanup; case COMP_OVERRUN: xhci_dbg(xhci, "overrun event on endpoint\n"); if (!list_empty(&ep_ring->td_list)) xhci_dbg(xhci, "Overrun Event for slot %d ep %d " "still with TDs queued?\n", TRB_TO_SLOT_ID(le32_to_cpu(event->flags)), ep_index); goto cleanup; case COMP_DEV_ERR: xhci_warn(xhci, "WARN: detect an incompatible device"); status = -EPROTO; break; case COMP_MISSED_INT: /* * When encounter missed service error, one or more isoc tds * may be missed by xHC. * Set skip flag of the ep_ring; Complete the missed tds as * short transfer when process the ep_ring next time. */ ep->skip = true; xhci_dbg(xhci, "Miss service interval error, set skip flag\n"); goto cleanup; default: if (xhci_is_vendor_info_code(xhci, trb_comp_code)) { status = 0; break; } xhci_warn(xhci, "ERROR Unknown event condition, HC probably " "busted\n"); goto cleanup; } do { /* This TRB should be in the TD at the head of this ring's * TD list. */ if (list_empty(&ep_ring->td_list)) { xhci_warn(xhci, "WARN Event TRB for slot %d ep %d " "with no TDs queued?\n", TRB_TO_SLOT_ID(le32_to_cpu(event->flags)), ep_index); xhci_dbg(xhci, "Event TRB with TRB type ID %u\n", (le32_to_cpu(event->flags) & TRB_TYPE_BITMASK)>>10); xhci_print_trb_offsets(xhci, (union xhci_trb *) event); if (ep->skip) { ep->skip = false; xhci_dbg(xhci, "td_list is empty while skip " "flag set. Clear skip flag.\n"); } ret = 0; goto cleanup; } /* We've skipped all the TDs on the ep ring when ep->skip set */ if (ep->skip && td_num == 0) { ep->skip = false; xhci_dbg(xhci, "All tds on the ep_ring skipped. " "Clear skip flag.\n"); ret = 0; goto cleanup; } td = list_entry(ep_ring->td_list.next, struct xhci_td, td_list); if (ep->skip) td_num--; /* Is this a TRB in the currently executing TD? */ event_seg = trb_in_td(ep_ring->deq_seg, ep_ring->dequeue, td->last_trb, event_dma); /* * Skip the Force Stopped Event. The event_trb(event_dma) of FSE * is not in the current TD pointed by ep_ring->dequeue because * that the hardware dequeue pointer still at the previous TRB * of the current TD. The previous TRB maybe a Link TD or the * last TRB of the previous TD. The command completion handle * will take care the rest. */ if (!event_seg && (trb_comp_code == COMP_STOP || trb_comp_code == COMP_STOP_INVAL)) { ret = 0; goto cleanup; } if (!event_seg) { if (!ep->skip || !usb_endpoint_xfer_isoc(&td->urb->ep->desc)) { /* Some host controllers give a spurious * successful event after a short transfer. * Ignore it. */ if ((xhci->quirks & XHCI_SPURIOUS_SUCCESS) && ep_ring->last_td_was_short) { ep_ring->last_td_was_short = false; ret = 0; goto cleanup; } /* HC is busted, give up! */ xhci_err(xhci, "ERROR Transfer event TRB DMA ptr not " "part of current TD\n"); return -ESHUTDOWN; } ret = skip_isoc_td(xhci, td, event, ep, &status); goto cleanup; } if (trb_comp_code == COMP_SHORT_TX) ep_ring->last_td_was_short = true; else ep_ring->last_td_was_short = false; if (ep->skip) { xhci_dbg(xhci, "Found td. Clear skip flag.\n"); ep->skip = false; } event_trb = &event_seg->trbs[(event_dma - event_seg->dma) / sizeof(*event_trb)]; /* * No-op TRB should not trigger interrupts. * If event_trb is a no-op TRB, it means the * corresponding TD has been cancelled. Just ignore * the TD. */ if (TRB_TYPE_NOOP_LE32(event_trb->generic.field[3])) { xhci_dbg(xhci, "event_trb is a no-op TRB. Skip it\n"); goto cleanup; } /* Now update the urb's actual_length and give back to * the core */ if (usb_endpoint_xfer_control(&td->urb->ep->desc)) ret = process_ctrl_td(xhci, td, event_trb, event, ep, &status); else if (usb_endpoint_xfer_isoc(&td->urb->ep->desc)) ret = process_isoc_td(xhci, td, event_trb, event, ep, &status); else ret = process_bulk_intr_td(xhci, td, event_trb, event, ep, &status); cleanup: /* * Do not update event ring dequeue pointer if ep->skip is set. * Will roll back to continue process missed tds. */ if (trb_comp_code == COMP_MISSED_INT || !ep->skip) { inc_deq(xhci, xhci->event_ring); } if (ret) { urb = td->urb; urb_priv = urb->hcpriv; /* Leave the TD around for the reset endpoint function * to use(but only if it's not a control endpoint, * since we already queued the Set TR dequeue pointer * command for stalled control endpoints). */ if (usb_endpoint_xfer_control(&urb->ep->desc) || (trb_comp_code != COMP_STALL && trb_comp_code != COMP_BABBLE)) xhci_urb_free_priv(xhci, urb_priv); usb_hcd_unlink_urb_from_ep(bus_to_hcd(urb->dev->bus), urb); if ((urb->actual_length != urb->transfer_buffer_length && (urb->transfer_flags & URB_SHORT_NOT_OK)) || (status != 0 && !usb_endpoint_xfer_isoc(&urb->ep->desc))) xhci_dbg(xhci, "Giveback URB %p, len = %d, " "expected = %x, status = %d\n", urb, urb->actual_length, urb->transfer_buffer_length, status); spin_unlock(&xhci->lock); /* EHCI, UHCI, and OHCI always unconditionally set the * urb->status of an isochronous endpoint to 0. */ if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS) status = 0; usb_hcd_giveback_urb(bus_to_hcd(urb->dev->bus), urb, status); spin_lock(&xhci->lock); } /* * If ep->skip is set, it means there are missed tds on the * endpoint ring need to take care of. * Process them as short transfer until reach the td pointed by * the event. */ } while (ep->skip && trb_comp_code != COMP_MISSED_INT); return 0; } /* * This function handles all OS-owned events on the event ring. It may drop * xhci->lock between event processing (e.g. to pass up port status changes). * Returns >0 for "possibly more events to process" (caller should call again), * otherwise 0 if done. In future, <0 returns should indicate error code. */ static int xhci_handle_event(struct xhci_hcd *xhci) { union xhci_trb *event; int update_ptrs = 1; int ret; if (!xhci->event_ring || !xhci->event_ring->dequeue) { xhci->error_bitmask |= 1 << 1; return 0; } event = xhci->event_ring->dequeue; /* Does the HC or OS own the TRB? */ if ((le32_to_cpu(event->event_cmd.flags) & TRB_CYCLE) != xhci->event_ring->cycle_state) { xhci->error_bitmask |= 1 << 2; return 0; } /* * Barrier between reading the TRB_CYCLE (valid) flag above and any * speculative reads of the event's flags/data below. */ rmb(); /* FIXME: Handle more event types. */ switch ((le32_to_cpu(event->event_cmd.flags) & TRB_TYPE_BITMASK)) { case TRB_TYPE(TRB_COMPLETION): handle_cmd_completion(xhci, &event->event_cmd); break; case TRB_TYPE(TRB_PORT_STATUS): handle_port_status(xhci, event); update_ptrs = 0; break; case TRB_TYPE(TRB_TRANSFER): ret = handle_tx_event(xhci, &event->trans_event); if (ret < 0) xhci->error_bitmask |= 1 << 9; else update_ptrs = 0; break; case TRB_TYPE(TRB_DEV_NOTE): handle_device_notification(xhci, event); break; default: if ((le32_to_cpu(event->event_cmd.flags) & TRB_TYPE_BITMASK) >= TRB_TYPE(48)) handle_vendor_event(xhci, event); else xhci->error_bitmask |= 1 << 3; } /* Any of the above functions may drop and re-acquire the lock, so check * to make sure a watchdog timer didn't mark the host as non-responsive. */ if (xhci->xhc_state & XHCI_STATE_DYING) { xhci_dbg(xhci, "xHCI host dying, returning from " "event handler.\n"); return 0; } if (update_ptrs) /* Update SW event ring dequeue pointer */ inc_deq(xhci, xhci->event_ring); /* Are there more items on the event ring? Caller will call us again to * check. */ return 1; } /* * xHCI spec says we can get an interrupt, and if the HC has an error condition, * we might get bad data out of the event ring. Section 4.10.2.7 has a list of * indicators of an event TRB error, but we check the status *first* to be safe. */ irqreturn_t xhci_irq(struct usb_hcd *hcd) { struct xhci_hcd *xhci = hcd_to_xhci(hcd); u32 status; union xhci_trb *trb; u64 temp_64; union xhci_trb *event_ring_deq; dma_addr_t deq; spin_lock(&xhci->lock); trb = xhci->event_ring->dequeue; /* Check if the xHC generated the interrupt, or the irq is shared */ status = xhci_readl(xhci, &xhci->op_regs->status); if (status == 0xffffffff) goto hw_died; if (!(status & STS_EINT)) { spin_unlock(&xhci->lock); return IRQ_NONE; } if (status & STS_FATAL) { xhci_warn(xhci, "WARNING: Host System Error\n"); xhci_halt(xhci); hw_died: spin_unlock(&xhci->lock); return -ESHUTDOWN; } /* * Clear the op reg interrupt status first, * so we can receive interrupts from other MSI-X interrupters. * Write 1 to clear the interrupt status. */ status |= STS_EINT; xhci_writel(xhci, status, &xhci->op_regs->status); /* FIXME when MSI-X is supported and there are multiple vectors */ /* Clear the MSI-X event interrupt status */ if (hcd->irq) { u32 irq_pending; /* Acknowledge the PCI interrupt */ irq_pending = xhci_readl(xhci, &xhci->ir_set->irq_pending); irq_pending |= IMAN_IP; xhci_writel(xhci, irq_pending, &xhci->ir_set->irq_pending); } if (xhci->xhc_state & XHCI_STATE_DYING) { xhci_dbg(xhci, "xHCI dying, ignoring interrupt. " "Shouldn't IRQs be disabled?\n"); /* Clear the event handler busy flag (RW1C); * the event ring should be empty. */ temp_64 = xhci_read_64(xhci, &xhci->ir_set->erst_dequeue); xhci_write_64(xhci, temp_64 | ERST_EHB, &xhci->ir_set->erst_dequeue); spin_unlock(&xhci->lock); return IRQ_HANDLED; } event_ring_deq = xhci->event_ring->dequeue; /* FIXME this should be a delayed service routine * that clears the EHB. */ while (xhci_handle_event(xhci) > 0) {} temp_64 = xhci_read_64(xhci, &xhci->ir_set->erst_dequeue); /* If necessary, update the HW's version of the event ring deq ptr. */ if (event_ring_deq != xhci->event_ring->dequeue) { deq = xhci_trb_virt_to_dma(xhci->event_ring->deq_seg, xhci->event_ring->dequeue); if (deq == 0) xhci_warn(xhci, "WARN something wrong with SW event " "ring dequeue ptr.\n"); /* Update HC event ring dequeue pointer */ temp_64 &= ERST_PTR_MASK; temp_64 |= ((u64) deq & (u64) ~ERST_PTR_MASK); } /* Clear the event handler busy flag (RW1C); event ring is empty. */ temp_64 |= ERST_EHB; xhci_write_64(xhci, temp_64, &xhci->ir_set->erst_dequeue); spin_unlock(&xhci->lock); return IRQ_HANDLED; } irqreturn_t xhci_msi_irq(int irq, struct usb_hcd *hcd) { return xhci_irq(hcd); } /**** Endpoint Ring Operations ****/ /* * Generic function for queueing a TRB on a ring. * The caller must have checked to make sure there's room on the ring. * * @more_trbs_coming: Will you enqueue more TRBs before calling * prepare_transfer()? */ static void queue_trb(struct xhci_hcd *xhci, struct xhci_ring *ring, bool more_trbs_coming, u32 field1, u32 field2, u32 field3, u32 field4) { struct xhci_generic_trb *trb; trb = &ring->enqueue->generic; trb->field[0] = cpu_to_le32(field1); trb->field[1] = cpu_to_le32(field2); trb->field[2] = cpu_to_le32(field3); trb->field[3] = cpu_to_le32(field4); inc_enq(xhci, ring, more_trbs_coming); } /* * Does various checks on the endpoint ring, and makes it ready to queue num_trbs. * FIXME allocate segments if the ring is full. */ static int prepare_ring(struct xhci_hcd *xhci, struct xhci_ring *ep_ring, u32 ep_state, unsigned int num_trbs, gfp_t mem_flags) { unsigned int num_trbs_needed; /* Make sure the endpoint has been added to xHC schedule */ switch (ep_state) { case EP_STATE_DISABLED: /* * USB core changed config/interfaces without notifying us, * or hardware is reporting the wrong state. */ xhci_warn(xhci, "WARN urb submitted to disabled ep\n"); return -ENOENT; case EP_STATE_ERROR: xhci_warn(xhci, "WARN waiting for error on ep to be cleared\n"); /* FIXME event handling code for error needs to clear it */ /* XXX not sure if this should be -ENOENT or not */ return -EINVAL; case EP_STATE_HALTED: xhci_dbg(xhci, "WARN halted endpoint, queueing URB anyway.\n"); case EP_STATE_STOPPED: case EP_STATE_RUNNING: break; default: xhci_err(xhci, "ERROR unknown endpoint state for ep\n"); /* * FIXME issue Configure Endpoint command to try to get the HC * back into a known state. */ return -EINVAL; } while (1) { if (room_on_ring(xhci, ep_ring, num_trbs)) break; if (ep_ring == xhci->cmd_ring) { xhci_err(xhci, "Do not support expand command ring\n"); return -ENOMEM; } xhci_dbg(xhci, "ERROR no room on ep ring, " "try ring expansion\n"); num_trbs_needed = num_trbs - ep_ring->num_trbs_free; if (xhci_ring_expansion(xhci, ep_ring, num_trbs_needed, mem_flags)) { xhci_err(xhci, "Ring expansion failed\n"); return -ENOMEM; } }; if (enqueue_is_link_trb(ep_ring)) { struct xhci_ring *ring = ep_ring; union xhci_trb *next; next = ring->enqueue; while (last_trb(xhci, ring, ring->enq_seg, next)) { /* If we're not dealing with 0.95 hardware or isoc rings * on AMD 0.96 host, clear the chain bit. */ if (!xhci_link_trb_quirk(xhci) && !(ring->type == TYPE_ISOC && (xhci->quirks & XHCI_AMD_0x96_HOST))) next->link.control &= cpu_to_le32(~TRB_CHAIN); else next->link.control |= cpu_to_le32(TRB_CHAIN); wmb(); next->link.control ^= cpu_to_le32(TRB_CYCLE); /* Toggle the cycle bit after the last ring segment. */ if (last_trb_on_last_seg(xhci, ring, ring->enq_seg, next)) { ring->cycle_state = (ring->cycle_state ? 0 : 1); } ring->enq_seg = ring->enq_seg->next; ring->enqueue = ring->enq_seg->trbs; next = ring->enqueue; } } return 0; } static int prepare_transfer(struct xhci_hcd *xhci, struct xhci_virt_device *xdev, unsigned int ep_index, unsigned int stream_id, unsigned int num_trbs, struct urb *urb, unsigned int td_index, gfp_t mem_flags) { int ret; struct urb_priv *urb_priv; struct xhci_td *td; struct xhci_ring *ep_ring; struct xhci_ep_ctx *ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index); ep_ring = xhci_stream_id_to_ring(xdev, ep_index, stream_id); if (!ep_ring) { xhci_dbg(xhci, "Can't prepare ring for bad stream ID %u\n", stream_id); return -EINVAL; } ret = prepare_ring(xhci, ep_ring, le32_to_cpu(ep_ctx->ep_info) & EP_STATE_MASK, num_trbs, mem_flags); if (ret) return ret; urb_priv = urb->hcpriv; td = urb_priv->td[td_index]; INIT_LIST_HEAD(&td->td_list); INIT_LIST_HEAD(&td->cancelled_td_list); if (td_index == 0) { ret = usb_hcd_link_urb_to_ep(bus_to_hcd(urb->dev->bus), urb); if (unlikely(ret)) return ret; } td->urb = urb; /* Add this TD to the tail of the endpoint ring's TD list */ list_add_tail(&td->td_list, &ep_ring->td_list); td->start_seg = ep_ring->enq_seg; td->first_trb = ep_ring->enqueue; urb_priv->td[td_index] = td; return 0; } static unsigned int count_sg_trbs_needed(struct xhci_hcd *xhci, struct urb *urb) { int num_sgs, num_trbs, running_total, temp, i; struct scatterlist *sg; sg = NULL; num_sgs = urb->num_mapped_sgs; temp = urb->transfer_buffer_length; num_trbs = 0; for_each_sg(urb->sg, sg, num_sgs, i) { unsigned int len = sg_dma_len(sg); /* Scatter gather list entries may cross 64KB boundaries */ running_total = TRB_MAX_BUFF_SIZE - (sg_dma_address(sg) & (TRB_MAX_BUFF_SIZE - 1)); running_total &= TRB_MAX_BUFF_SIZE - 1; if (running_total != 0) num_trbs++; /* How many more 64KB chunks to transfer, how many more TRBs? */ while (running_total < sg_dma_len(sg) && running_total < temp) { num_trbs++; running_total += TRB_MAX_BUFF_SIZE; } len = min_t(int, len, temp); temp -= len; if (temp == 0) break; } return num_trbs; } static void check_trb_math(struct urb *urb, int num_trbs, int running_total) { if (num_trbs != 0) dev_err(&urb->dev->dev, "%s - ep %#x - Miscalculated number of " "TRBs, %d left\n", __func__, urb->ep->desc.bEndpointAddress, num_trbs); if (running_total != urb->transfer_buffer_length) dev_err(&urb->dev->dev, "%s - ep %#x - Miscalculated tx length, " "queued %#x (%d), asked for %#x (%d)\n", __func__, urb->ep->desc.bEndpointAddress, running_total, running_total, urb->transfer_buffer_length, urb->transfer_buffer_length); } static void giveback_first_trb(struct xhci_hcd *xhci, int slot_id, unsigned int ep_index, unsigned int stream_id, int start_cycle, struct xhci_generic_trb *start_trb) { /* * Pass all the TRBs to the hardware at once and make sure this write * isn't reordered. */ wmb(); if (start_cycle) start_trb->field[3] |= cpu_to_le32(start_cycle); else start_trb->field[3] &= cpu_to_le32(~TRB_CYCLE); xhci_ring_ep_doorbell(xhci, slot_id, ep_index, stream_id); } /* * xHCI uses normal TRBs for both bulk and interrupt. When the interrupt * endpoint is to be serviced, the xHC will consume (at most) one TD. A TD * (comprised of sg list entries) can take several service intervals to * transmit. */ int xhci_queue_intr_tx(struct xhci_hcd *xhci, gfp_t mem_flags, struct urb *urb, int slot_id, unsigned int ep_index) { struct xhci_ep_ctx *ep_ctx = xhci_get_ep_ctx(xhci, xhci->devs[slot_id]->out_ctx, ep_index); int xhci_interval; int ep_interval; xhci_interval = EP_INTERVAL_TO_UFRAMES(le32_to_cpu(ep_ctx->ep_info)); ep_interval = urb->interval; /* Convert to microframes */ if (urb->dev->speed == USB_SPEED_LOW || urb->dev->speed == USB_SPEED_FULL) ep_interval *= 8; /* FIXME change this to a warning and a suggestion to use the new API * to set the polling interval (once the API is added). */ if (xhci_interval != ep_interval) { if (printk_ratelimit()) dev_dbg(&urb->dev->dev, "Driver uses different interval" " (%d microframe%s) than xHCI " "(%d microframe%s)\n", ep_interval, ep_interval == 1 ? "" : "s", xhci_interval, xhci_interval == 1 ? "" : "s"); urb->interval = xhci_interval; /* Convert back to frames for LS/FS devices */ if (urb->dev->speed == USB_SPEED_LOW || urb->dev->speed == USB_SPEED_FULL) urb->interval /= 8; } return xhci_queue_bulk_tx(xhci, mem_flags, urb, slot_id, ep_index); } /* * The TD size is the number of bytes remaining in the TD (including this TRB), * right shifted by 10. * It must fit in bits 21:17, so it can't be bigger than 31. */ static u32 xhci_td_remainder(unsigned int remainder) { u32 max = (1 << (21 - 17 + 1)) - 1; if ((remainder >> 10) >= max) return max << 17; else return (remainder >> 10) << 17; } /* * For xHCI 1.0 host controllers, TD size is the number of packets remaining in * the TD (*not* including this TRB). * * Total TD packet count = total_packet_count = * roundup(TD size in bytes / wMaxPacketSize) * * Packets transferred up to and including this TRB = packets_transferred = * rounddown(total bytes transferred including this TRB / wMaxPacketSize) * * TD size = total_packet_count - packets_transferred * * It must fit in bits 21:17, so it can't be bigger than 31. */ static u32 xhci_v1_0_td_remainder(int running_total, int trb_buff_len, unsigned int total_packet_count, struct urb *urb) { int packets_transferred; /* One TRB with a zero-length data packet. */ if (running_total == 0 && trb_buff_len == 0) return 0; /* All the TRB queueing functions don't count the current TRB in * running_total. */ packets_transferred = (running_total + trb_buff_len) / usb_endpoint_maxp(&urb->ep->desc); return xhci_td_remainder(total_packet_count - packets_transferred); } static int queue_bulk_sg_tx(struct xhci_hcd *xhci, gfp_t mem_flags, struct urb *urb, int slot_id, unsigned int ep_index) { struct xhci_ring *ep_ring; unsigned int num_trbs; struct urb_priv *urb_priv; struct xhci_td *td; struct scatterlist *sg; int num_sgs; int trb_buff_len, this_sg_len, running_total; unsigned int total_packet_count; bool first_trb; u64 addr; bool more_trbs_coming; struct xhci_generic_trb *start_trb; int start_cycle; ep_ring = xhci_urb_to_transfer_ring(xhci, urb); if (!ep_ring) return -EINVAL; num_trbs = count_sg_trbs_needed(xhci, urb); num_sgs = urb->num_mapped_sgs; total_packet_count = roundup(urb->transfer_buffer_length, usb_endpoint_maxp(&urb->ep->desc)); trb_buff_len = prepare_transfer(xhci, xhci->devs[slot_id], ep_index, urb->stream_id, num_trbs, urb, 0, mem_flags); if (trb_buff_len < 0) return trb_buff_len; urb_priv = urb->hcpriv; td = urb_priv->td[0]; /* * Don't give the first TRB to the hardware (by toggling the cycle bit) * until we've finished creating all the other TRBs. The ring's cycle * state may change as we enqueue the other TRBs, so save it too. */ start_trb = &ep_ring->enqueue->generic; start_cycle = ep_ring->cycle_state; running_total = 0; /* * How much data is in the first TRB? * * There are three forces at work for TRB buffer pointers and lengths: * 1. We don't want to walk off the end of this sg-list entry buffer. * 2. The transfer length that the driver requested may be smaller than * the amount of memory allocated for this scatter-gather list. * 3. TRBs buffers can't cross 64KB boundaries. */ sg = urb->sg; addr = (u64) sg_dma_address(sg); this_sg_len = sg_dma_len(sg); trb_buff_len = TRB_MAX_BUFF_SIZE - (addr & (TRB_MAX_BUFF_SIZE - 1)); trb_buff_len = min_t(int, trb_buff_len, this_sg_len); if (trb_buff_len > urb->transfer_buffer_length) trb_buff_len = urb->transfer_buffer_length; first_trb = true; /* Queue the first TRB, even if it's zero-length */ do { u32 field = 0; u32 length_field = 0; u32 remainder = 0; /* Don't change the cycle bit of the first TRB until later */ if (first_trb) { first_trb = false; if (start_cycle == 0) field |= 0x1; } else field |= ep_ring->cycle_state; /* Chain all the TRBs together; clear the chain bit in the last * TRB to indicate it's the last TRB in the chain. */ if (num_trbs > 1) { field |= TRB_CHAIN; } else { /* FIXME - add check for ZERO_PACKET flag before this */ td->last_trb = ep_ring->enqueue; field |= TRB_IOC; } /* Only set interrupt on short packet for IN endpoints */ if (usb_urb_dir_in(urb)) field |= TRB_ISP; if (TRB_MAX_BUFF_SIZE - (addr & (TRB_MAX_BUFF_SIZE - 1)) < trb_buff_len) { xhci_warn(xhci, "WARN: sg dma xfer crosses 64KB boundaries!\n"); xhci_dbg(xhci, "Next boundary at %#x, end dma = %#x\n", (unsigned int) (addr + TRB_MAX_BUFF_SIZE) & ~(TRB_MAX_BUFF_SIZE - 1), (unsigned int) addr + trb_buff_len); } /* Set the TRB length, TD size, and interrupter fields. */ if (xhci->hci_version < 0x100) { remainder = xhci_td_remainder( urb->transfer_buffer_length - running_total); } else { remainder = xhci_v1_0_td_remainder(running_total, trb_buff_len, total_packet_count, urb); } length_field = TRB_LEN(trb_buff_len) | remainder | TRB_INTR_TARGET(0); if (num_trbs > 1) more_trbs_coming = true; else more_trbs_coming = false; queue_trb(xhci, ep_ring, more_trbs_coming, lower_32_bits(addr), upper_32_bits(addr), length_field, field | TRB_TYPE(TRB_NORMAL)); --num_trbs; running_total += trb_buff_len; /* Calculate length for next transfer -- * Are we done queueing all the TRBs for this sg entry? */ this_sg_len -= trb_buff_len; if (this_sg_len == 0) { --num_sgs; if (num_sgs == 0) break; sg = sg_next(sg); addr = (u64) sg_dma_address(sg); this_sg_len = sg_dma_len(sg); } else { addr += trb_buff_len; } trb_buff_len = TRB_MAX_BUFF_SIZE - (addr & (TRB_MAX_BUFF_SIZE - 1)); trb_buff_len = min_t(int, trb_buff_len, this_sg_len); if (running_total + trb_buff_len > urb->transfer_buffer_length) trb_buff_len = urb->transfer_buffer_length - running_total; } while (running_total < urb->transfer_buffer_length); check_trb_math(urb, num_trbs, running_total); giveback_first_trb(xhci, slot_id, ep_index, urb->stream_id, start_cycle, start_trb); return 0; } /* This is very similar to what ehci-q.c qtd_fill() does */ int xhci_queue_bulk_tx(struct xhci_hcd *xhci, gfp_t mem_flags, struct urb *urb, int slot_id, unsigned int ep_index) { struct xhci_ring *ep_ring; struct urb_priv *urb_priv; struct xhci_td *td; int num_trbs; struct xhci_generic_trb *start_trb; bool first_trb; bool more_trbs_coming; int start_cycle; u32 field, length_field; int running_total, trb_buff_len, ret; unsigned int total_packet_count; u64 addr; if (urb->num_sgs) return queue_bulk_sg_tx(xhci, mem_flags, urb, slot_id, ep_index); ep_ring = xhci_urb_to_transfer_ring(xhci, urb); if (!ep_ring) return -EINVAL; num_trbs = 0; /* How much data is (potentially) left before the 64KB boundary? */ running_total = TRB_MAX_BUFF_SIZE - (urb->transfer_dma & (TRB_MAX_BUFF_SIZE - 1)); running_total &= TRB_MAX_BUFF_SIZE - 1; /* If there's some data on this 64KB chunk, or we have to send a * zero-length transfer, we need at least one TRB */ if (running_total != 0 || urb->transfer_buffer_length == 0) num_trbs++; /* How many more 64KB chunks to transfer, how many more TRBs? */ while (running_total < urb->transfer_buffer_length) { num_trbs++; running_total += TRB_MAX_BUFF_SIZE; } /* FIXME: this doesn't deal with URB_ZERO_PACKET - need one more */ ret = prepare_transfer(xhci, xhci->devs[slot_id], ep_index, urb->stream_id, num_trbs, urb, 0, mem_flags); if (ret < 0) return ret; urb_priv = urb->hcpriv; td = urb_priv->td[0]; /* * Don't give the first TRB to the hardware (by toggling the cycle bit) * until we've finished creating all the other TRBs. The ring's cycle * state may change as we enqueue the other TRBs, so save it too. */ start_trb = &ep_ring->enqueue->generic; start_cycle = ep_ring->cycle_state; running_total = 0; total_packet_count = roundup(urb->transfer_buffer_length, usb_endpoint_maxp(&urb->ep->desc)); /* How much data is in the first TRB? */ addr = (u64) urb->transfer_dma; trb_buff_len = TRB_MAX_BUFF_SIZE - (urb->transfer_dma & (TRB_MAX_BUFF_SIZE - 1)); if (trb_buff_len > urb->transfer_buffer_length) trb_buff_len = urb->transfer_buffer_length; first_trb = true; /* Queue the first TRB, even if it's zero-length */ do { u32 remainder = 0; field = 0; /* Don't change the cycle bit of the first TRB until later */ if (first_trb) { first_trb = false; if (start_cycle == 0) field |= 0x1; } else field |= ep_ring->cycle_state; /* Chain all the TRBs together; clear the chain bit in the last * TRB to indicate it's the last TRB in the chain. */ if (num_trbs > 1) { field |= TRB_CHAIN; } else { /* FIXME - add check for ZERO_PACKET flag before this */ td->last_trb = ep_ring->enqueue; field |= TRB_IOC; } /* Only set interrupt on short packet for IN endpoints */ if (usb_urb_dir_in(urb)) field |= TRB_ISP; /* Set the TRB length, TD size, and interrupter fields. */ if (xhci->hci_version < 0x100) { remainder = xhci_td_remainder( urb->transfer_buffer_length - running_total); } else { remainder = xhci_v1_0_td_remainder(running_total, trb_buff_len, total_packet_count, urb); } length_field = TRB_LEN(trb_buff_len) | remainder | TRB_INTR_TARGET(0); if (num_trbs > 1) more_trbs_coming = true; else more_trbs_coming = false; queue_trb(xhci, ep_ring, more_trbs_coming, lower_32_bits(addr), upper_32_bits(addr), length_field, field | TRB_TYPE(TRB_NORMAL)); --num_trbs; running_total += trb_buff_len; /* Calculate length for next transfer */ addr += trb_buff_len; trb_buff_len = urb->transfer_buffer_length - running_total; if (trb_buff_len > TRB_MAX_BUFF_SIZE) trb_buff_len = TRB_MAX_BUFF_SIZE; } while (running_total < urb->transfer_buffer_length); check_trb_math(urb, num_trbs, running_total); giveback_first_trb(xhci, slot_id, ep_index, urb->stream_id, start_cycle, start_trb); return 0; } /* Caller must have locked xhci->lock */ int xhci_queue_ctrl_tx(struct xhci_hcd *xhci, gfp_t mem_flags, struct urb *urb, int slot_id, unsigned int ep_index) { struct xhci_ring *ep_ring; int num_trbs; int ret; struct usb_ctrlrequest *setup; struct xhci_generic_trb *start_trb; int start_cycle; u32 field, length_field; struct urb_priv *urb_priv; struct xhci_td *td; ep_ring = xhci_urb_to_transfer_ring(xhci, urb); if (!ep_ring) return -EINVAL; /* * Need to copy setup packet into setup TRB, so we can't use the setup * DMA address. */ if (!urb->setup_packet) return -EINVAL; /* 1 TRB for setup, 1 for status */ num_trbs = 2; /* * Don't need to check if we need additional event data and normal TRBs, * since data in control transfers will never get bigger than 16MB * XXX: can we get a buffer that crosses 64KB boundaries? */ if (urb->transfer_buffer_length > 0) num_trbs++; ret = prepare_transfer(xhci, xhci->devs[slot_id], ep_index, urb->stream_id, num_trbs, urb, 0, mem_flags); if (ret < 0) return ret; urb_priv = urb->hcpriv; td = urb_priv->td[0]; /* * Don't give the first TRB to the hardware (by toggling the cycle bit) * until we've finished creating all the other TRBs. The ring's cycle * state may change as we enqueue the other TRBs, so save it too. */ start_trb = &ep_ring->enqueue->generic; start_cycle = ep_ring->cycle_state; /* Queue setup TRB - see section 6.4.1.2.1 */ /* FIXME better way to translate setup_packet into two u32 fields? */ setup = (struct usb_ctrlrequest *) urb->setup_packet; field = 0; field |= TRB_IDT | TRB_TYPE(TRB_SETUP); if (start_cycle == 0) field |= 0x1; /* xHCI 1.0 6.4.1.2.1: Transfer Type field */ if (xhci->hci_version == 0x100) { if (urb->transfer_buffer_length > 0) { if (setup->bRequestType & USB_DIR_IN) field |= TRB_TX_TYPE(TRB_DATA_IN); else field |= TRB_TX_TYPE(TRB_DATA_OUT); } } queue_trb(xhci, ep_ring, true, setup->bRequestType | setup->bRequest << 8 | le16_to_cpu(setup->wValue) << 16, le16_to_cpu(setup->wIndex) | le16_to_cpu(setup->wLength) << 16, TRB_LEN(8) | TRB_INTR_TARGET(0), /* Immediate data in pointer */ field); /* If there's data, queue data TRBs */ /* Only set interrupt on short packet for IN endpoints */ if (usb_urb_dir_in(urb)) field = TRB_ISP | TRB_TYPE(TRB_DATA); else field = TRB_TYPE(TRB_DATA); length_field = TRB_LEN(urb->transfer_buffer_length) | xhci_td_remainder(urb->transfer_buffer_length) | TRB_INTR_TARGET(0); if (urb->transfer_buffer_length > 0) { if (setup->bRequestType & USB_DIR_IN) field |= TRB_DIR_IN; queue_trb(xhci, ep_ring, true, lower_32_bits(urb->transfer_dma), upper_32_bits(urb->transfer_dma), length_field, field | ep_ring->cycle_state); } /* Save the DMA address of the last TRB in the TD */ td->last_trb = ep_ring->enqueue; /* Queue status TRB - see Table 7 and sections 4.11.2.2 and 6.4.1.2.3 */ /* If the device sent data, the status stage is an OUT transfer */ if (urb->transfer_buffer_length > 0 && setup->bRequestType & USB_DIR_IN) field = 0; else field = TRB_DIR_IN; queue_trb(xhci, ep_ring, false, 0, 0, TRB_INTR_TARGET(0), /* Event on completion */ field | TRB_IOC | TRB_TYPE(TRB_STATUS) | ep_ring->cycle_state); giveback_first_trb(xhci, slot_id, ep_index, 0, start_cycle, start_trb); return 0; } static int count_isoc_trbs_needed(struct xhci_hcd *xhci, struct urb *urb, int i) { int num_trbs = 0; u64 addr, td_len; addr = (u64) (urb->transfer_dma + urb->iso_frame_desc[i].offset); td_len = urb->iso_frame_desc[i].length; num_trbs = DIV_ROUND_UP(td_len + (addr & (TRB_MAX_BUFF_SIZE - 1)), TRB_MAX_BUFF_SIZE); if (num_trbs == 0) num_trbs++; return num_trbs; } /* * The transfer burst count field of the isochronous TRB defines the number of * bursts that are required to move all packets in this TD. Only SuperSpeed * devices can burst up to bMaxBurst number of packets per service interval. * This field is zero based, meaning a value of zero in the field means one * burst. Basically, for everything but SuperSpeed devices, this field will be * zero. Only xHCI 1.0 host controllers support this field. */ static unsigned int xhci_get_burst_count(struct xhci_hcd *xhci, struct usb_device *udev, struct urb *urb, unsigned int total_packet_count) { unsigned int max_burst; if (xhci->hci_version < 0x100 || udev->speed != USB_SPEED_SUPER) return 0; max_burst = urb->ep->ss_ep_comp.bMaxBurst; return roundup(total_packet_count, max_burst + 1) - 1; } /* * Returns the number of packets in the last "burst" of packets. This field is * valid for all speeds of devices. USB 2.0 devices can only do one "burst", so * the last burst packet count is equal to the total number of packets in the * TD. SuperSpeed endpoints can have up to 3 bursts. All but the last burst * must contain (bMaxBurst + 1) number of packets, but the last burst can * contain 1 to (bMaxBurst + 1) packets. */ static unsigned int xhci_get_last_burst_packet_count(struct xhci_hcd *xhci, struct usb_device *udev, struct urb *urb, unsigned int total_packet_count) { unsigned int max_burst; unsigned int residue; if (xhci->hci_version < 0x100) return 0; switch (udev->speed) { case USB_SPEED_SUPER: /* bMaxBurst is zero based: 0 means 1 packet per burst */ max_burst = urb->ep->ss_ep_comp.bMaxBurst; residue = total_packet_count % (max_burst + 1); /* If residue is zero, the last burst contains (max_burst + 1) * number of packets, but the TLBPC field is zero-based. */ if (residue == 0) return max_burst; return residue - 1; default: if (total_packet_count == 0) return 0; return total_packet_count - 1; } } /* This is for isoc transfer */ static int xhci_queue_isoc_tx(struct xhci_hcd *xhci, gfp_t mem_flags, struct urb *urb, int slot_id, unsigned int ep_index) { struct xhci_ring *ep_ring; struct urb_priv *urb_priv; struct xhci_td *td; int num_tds, trbs_per_td; struct xhci_generic_trb *start_trb; bool first_trb; int start_cycle; u32 field, length_field; int running_total, trb_buff_len, td_len, td_remain_len, ret; u64 start_addr, addr; int i, j; bool more_trbs_coming; ep_ring = xhci->devs[slot_id]->eps[ep_index].ring; num_tds = urb->number_of_packets; if (num_tds < 1) { xhci_dbg(xhci, "Isoc URB with zero packets?\n"); return -EINVAL; } start_addr = (u64) urb->transfer_dma; start_trb = &ep_ring->enqueue->generic; start_cycle = ep_ring->cycle_state; urb_priv = urb->hcpriv; /* Queue the first TRB, even if it's zero-length */ for (i = 0; i < num_tds; i++) { unsigned int total_packet_count; unsigned int burst_count; unsigned int residue; first_trb = true; running_total = 0; addr = start_addr + urb->iso_frame_desc[i].offset; td_len = urb->iso_frame_desc[i].length; td_remain_len = td_len; total_packet_count = roundup(td_len, usb_endpoint_maxp(&urb->ep->desc)); /* A zero-length transfer still involves at least one packet. */ if (total_packet_count == 0) total_packet_count++; burst_count = xhci_get_burst_count(xhci, urb->dev, urb, total_packet_count); residue = xhci_get_last_burst_packet_count(xhci, urb->dev, urb, total_packet_count); trbs_per_td = count_isoc_trbs_needed(xhci, urb, i); ret = prepare_transfer(xhci, xhci->devs[slot_id], ep_index, urb->stream_id, trbs_per_td, urb, i, mem_flags); if (ret < 0) { if (i == 0) return ret; goto cleanup; } td = urb_priv->td[i]; for (j = 0; j < trbs_per_td; j++) { u32 remainder = 0; field = TRB_TBC(burst_count) | TRB_TLBPC(residue); if (first_trb) { /* Queue the isoc TRB */ field |= TRB_TYPE(TRB_ISOC); /* Assume URB_ISO_ASAP is set */ field |= TRB_SIA; if (i == 0) { if (start_cycle == 0) field |= 0x1; } else field |= ep_ring->cycle_state; first_trb = false; } else { /* Queue other normal TRBs */ field |= TRB_TYPE(TRB_NORMAL); field |= ep_ring->cycle_state; } /* Only set interrupt on short packet for IN EPs */ if (usb_urb_dir_in(urb)) field |= TRB_ISP; /* Chain all the TRBs together; clear the chain bit in * the last TRB to indicate it's the last TRB in the * chain. */ if (j < trbs_per_td - 1) { field |= TRB_CHAIN; more_trbs_coming = true; } else { td->last_trb = ep_ring->enqueue; field |= TRB_IOC; if (xhci->hci_version == 0x100) { /* Set BEI bit except for the last td */ if (i < num_tds - 1) field |= TRB_BEI; } more_trbs_coming = false; } /* Calculate TRB length */ trb_buff_len = TRB_MAX_BUFF_SIZE - (addr & ((1 << TRB_MAX_BUFF_SHIFT) - 1)); if (trb_buff_len > td_remain_len) trb_buff_len = td_remain_len; /* Set the TRB length, TD size, & interrupter fields. */ if (xhci->hci_version < 0x100) { remainder = xhci_td_remainder( td_len - running_total); } else { remainder = xhci_v1_0_td_remainder( running_total, trb_buff_len, total_packet_count, urb); } length_field = TRB_LEN(trb_buff_len) | remainder | TRB_INTR_TARGET(0); queue_trb(xhci, ep_ring, more_trbs_coming, lower_32_bits(addr), upper_32_bits(addr), length_field, field); running_total += trb_buff_len; addr += trb_buff_len; td_remain_len -= trb_buff_len; } /* Check TD length */ if (running_total != td_len) { xhci_err(xhci, "ISOC TD length unmatch\n"); ret = -EINVAL; goto cleanup; } } if (xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs == 0) { if (xhci->quirks & XHCI_AMD_PLL_FIX) usb_amd_quirk_pll_disable(); } xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs++; giveback_first_trb(xhci, slot_id, ep_index, urb->stream_id, start_cycle, start_trb); return 0; cleanup: /* Clean up a partially enqueued isoc transfer. */ for (i--; i >= 0; i--) list_del_init(&urb_priv->td[i]->td_list); /* Use the first TD as a temporary variable to turn the TDs we've queued * into No-ops with a software-owned cycle bit. That way the hardware * won't accidentally start executing bogus TDs when we partially * overwrite them. td->first_trb and td->start_seg are already set. */ urb_priv->td[0]->last_trb = ep_ring->enqueue; /* Every TRB except the first & last will have its cycle bit flipped. */ td_to_noop(xhci, ep_ring, urb_priv->td[0], true); /* Reset the ring enqueue back to the first TRB and its cycle bit. */ ep_ring->enqueue = urb_priv->td[0]->first_trb; ep_ring->enq_seg = urb_priv->td[0]->start_seg; ep_ring->cycle_state = start_cycle; ep_ring->num_trbs_free = ep_ring->num_trbs_free_temp; usb_hcd_unlink_urb_from_ep(bus_to_hcd(urb->dev->bus), urb); return ret; } /* * Check transfer ring to guarantee there is enough room for the urb. * Update ISO URB start_frame and interval. * Update interval as xhci_queue_intr_tx does. Just use xhci frame_index to * update the urb->start_frame by now. * Always assume URB_ISO_ASAP set, and NEVER use urb->start_frame as input. */ int xhci_queue_isoc_tx_prepare(struct xhci_hcd *xhci, gfp_t mem_flags, struct urb *urb, int slot_id, unsigned int ep_index) { struct xhci_virt_device *xdev; struct xhci_ring *ep_ring; struct xhci_ep_ctx *ep_ctx; int start_frame; int xhci_interval; int ep_interval; int num_tds, num_trbs, i; int ret; xdev = xhci->devs[slot_id]; ep_ring = xdev->eps[ep_index].ring; ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index); num_trbs = 0; num_tds = urb->number_of_packets; for (i = 0; i < num_tds; i++) num_trbs += count_isoc_trbs_needed(xhci, urb, i); /* Check the ring to guarantee there is enough room for the whole urb. * Do not insert any td of the urb to the ring if the check failed. */ ret = prepare_ring(xhci, ep_ring, le32_to_cpu(ep_ctx->ep_info) & EP_STATE_MASK, num_trbs, mem_flags); if (ret) return ret; start_frame = xhci_readl(xhci, &xhci->run_regs->microframe_index); start_frame &= 0x3fff; urb->start_frame = start_frame; if (urb->dev->speed == USB_SPEED_LOW || urb->dev->speed == USB_SPEED_FULL) urb->start_frame >>= 3; xhci_interval = EP_INTERVAL_TO_UFRAMES(le32_to_cpu(ep_ctx->ep_info)); ep_interval = urb->interval; /* Convert to microframes */ if (urb->dev->speed == USB_SPEED_LOW || urb->dev->speed == USB_SPEED_FULL) ep_interval *= 8; /* FIXME change this to a warning and a suggestion to use the new API * to set the polling interval (once the API is added). */ if (xhci_interval != ep_interval) { if (printk_ratelimit()) dev_dbg(&urb->dev->dev, "Driver uses different interval" " (%d microframe%s) than xHCI " "(%d microframe%s)\n", ep_interval, ep_interval == 1 ? "" : "s", xhci_interval, xhci_interval == 1 ? "" : "s"); urb->interval = xhci_interval; /* Convert back to frames for LS/FS devices */ if (urb->dev->speed == USB_SPEED_LOW || urb->dev->speed == USB_SPEED_FULL) urb->interval /= 8; } ep_ring->num_trbs_free_temp = ep_ring->num_trbs_free; return xhci_queue_isoc_tx(xhci, mem_flags, urb, slot_id, ep_index); } /**** Command Ring Operations ****/ /* Generic function for queueing a command TRB on the command ring. * Check to make sure there's room on the command ring for one command TRB. * Also check that there's room reserved for commands that must not fail. * If this is a command that must not fail, meaning command_must_succeed = TRUE, * then only check for the number of reserved spots. * Don't decrement xhci->cmd_ring_reserved_trbs after we've queued the TRB * because the command event handler may want to resubmit a failed command. */ static int queue_command(struct xhci_hcd *xhci, u32 field1, u32 field2, u32 field3, u32 field4, bool command_must_succeed) { int reserved_trbs = xhci->cmd_ring_reserved_trbs; int ret; if (!command_must_succeed) reserved_trbs++; ret = prepare_ring(xhci, xhci->cmd_ring, EP_STATE_RUNNING, reserved_trbs, GFP_ATOMIC); if (ret < 0) { xhci_err(xhci, "ERR: No room for command on command ring\n"); if (command_must_succeed) xhci_err(xhci, "ERR: Reserved TRB counting for " "unfailable commands failed.\n"); return ret; } queue_trb(xhci, xhci->cmd_ring, false, field1, field2, field3, field4 | xhci->cmd_ring->cycle_state); return 0; } /* Queue a slot enable or disable request on the command ring */ int xhci_queue_slot_control(struct xhci_hcd *xhci, u32 trb_type, u32 slot_id) { return queue_command(xhci, 0, 0, 0, TRB_TYPE(trb_type) | SLOT_ID_FOR_TRB(slot_id), false); } /* Queue an address device command TRB */ int xhci_queue_address_device(struct xhci_hcd *xhci, dma_addr_t in_ctx_ptr, u32 slot_id) { return queue_command(xhci, lower_32_bits(in_ctx_ptr), upper_32_bits(in_ctx_ptr), 0, TRB_TYPE(TRB_ADDR_DEV) | SLOT_ID_FOR_TRB(slot_id), false); } int xhci_queue_vendor_command(struct xhci_hcd *xhci, u32 field1, u32 field2, u32 field3, u32 field4) { return queue_command(xhci, field1, field2, field3, field4, false); } /* Queue a reset device command TRB */ int xhci_queue_reset_device(struct xhci_hcd *xhci, u32 slot_id) { return queue_command(xhci, 0, 0, 0, TRB_TYPE(TRB_RESET_DEV) | SLOT_ID_FOR_TRB(slot_id), false); } /* Queue a configure endpoint command TRB */ int xhci_queue_configure_endpoint(struct xhci_hcd *xhci, dma_addr_t in_ctx_ptr, u32 slot_id, bool command_must_succeed) { return queue_command(xhci, lower_32_bits(in_ctx_ptr), upper_32_bits(in_ctx_ptr), 0, TRB_TYPE(TRB_CONFIG_EP) | SLOT_ID_FOR_TRB(slot_id), command_must_succeed); } /* Queue an evaluate context command TRB */ int xhci_queue_evaluate_context(struct xhci_hcd *xhci, dma_addr_t in_ctx_ptr, u32 slot_id) { return queue_command(xhci, lower_32_bits(in_ctx_ptr), upper_32_bits(in_ctx_ptr), 0, TRB_TYPE(TRB_EVAL_CONTEXT) | SLOT_ID_FOR_TRB(slot_id), false); } /* * Suspend is set to indicate "Stop Endpoint Command" is being issued to stop * activity on an endpoint that is about to be suspended. */ int xhci_queue_stop_endpoint(struct xhci_hcd *xhci, int slot_id, unsigned int ep_index, int suspend) { u32 trb_slot_id = SLOT_ID_FOR_TRB(slot_id); u32 trb_ep_index = EP_ID_FOR_TRB(ep_index); u32 type = TRB_TYPE(TRB_STOP_RING); u32 trb_suspend = SUSPEND_PORT_FOR_TRB(suspend); return queue_command(xhci, 0, 0, 0, trb_slot_id | trb_ep_index | type | trb_suspend, false); } /* Set Transfer Ring Dequeue Pointer command. * This should not be used for endpoints that have streams enabled. */ static int queue_set_tr_deq(struct xhci_hcd *xhci, int slot_id, unsigned int ep_index, unsigned int stream_id, struct xhci_segment *deq_seg, union xhci_trb *deq_ptr, u32 cycle_state) { dma_addr_t addr; u32 trb_slot_id = SLOT_ID_FOR_TRB(slot_id); u32 trb_ep_index = EP_ID_FOR_TRB(ep_index); u32 trb_stream_id = STREAM_ID_FOR_TRB(stream_id); u32 type = TRB_TYPE(TRB_SET_DEQ); struct xhci_virt_ep *ep; addr = xhci_trb_virt_to_dma(deq_seg, deq_ptr); if (addr == 0) { xhci_warn(xhci, "WARN Cannot submit Set TR Deq Ptr\n"); xhci_warn(xhci, "WARN deq seg = %p, deq pt = %p\n", deq_seg, deq_ptr); return 0; } ep = &xhci->devs[slot_id]->eps[ep_index]; if ((ep->ep_state & SET_DEQ_PENDING)) { xhci_warn(xhci, "WARN Cannot submit Set TR Deq Ptr\n"); xhci_warn(xhci, "A Set TR Deq Ptr command is pending.\n"); return 0; } ep->queued_deq_seg = deq_seg; ep->queued_deq_ptr = deq_ptr; return queue_command(xhci, lower_32_bits(addr) | cycle_state, upper_32_bits(addr), trb_stream_id, trb_slot_id | trb_ep_index | type, false); } int xhci_queue_reset_ep(struct xhci_hcd *xhci, int slot_id, unsigned int ep_index) { u32 trb_slot_id = SLOT_ID_FOR_TRB(slot_id); u32 trb_ep_index = EP_ID_FOR_TRB(ep_index); u32 type = TRB_TYPE(TRB_RESET_EP); return queue_command(xhci, 0, 0, 0, trb_slot_id | trb_ep_index | type, false); }
ashikrobi/Crabbykernel
drivers/usb/host/xhci-ring.c
C
gpl-2.0
115,318
/* * Copyright (c) 2009-2013, The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * 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/module.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/time.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/spinlock.h> #include <linux/hrtimer.h> #include <linux/clk.h> #include <mach/hardware.h> #include <mach/iommu_domains.h> #include <mach/iommu.h> #include <linux/iommu.h> #include <linux/io.h> #include <linux/debugfs.h> #include <linux/fb.h> #include <linux/msm_mdp.h> #include <linux/file.h> #include <linux/android_pmem.h> #include <linux/major.h> #include <asm/system.h> #include <asm/mach-types.h> #include <linux/semaphore.h> #include <linux/uaccess.h> #include <linux/mutex.h> #include <linux/msm_kgsl.h> #include "mdp.h" #include "msm_fb.h" #include "mdp4.h" #define VERSION_KEY_MASK 0xFFFFFF00 struct mdp4_overlay_ctrl { struct mdp4_overlay_pipe plist[OVERLAY_PIPE_MAX]; struct mdp4_overlay_pipe *stage[MDP4_MIXER_MAX][MDP4_MIXER_STAGE_MAX]; struct mdp4_overlay_pipe *baselayer[MDP4_MIXER_MAX]; struct blend_cfg blend[MDP4_MIXER_MAX][MDP4_MIXER_STAGE_MAX]; uint32 mixer_cfg[MDP4_MIXER_MAX]; uint32 flush[MDP4_MIXER_MAX]; struct iommu_free_list iommu_free[MDP4_MIXER_MAX]; struct iommu_free_list iommu_free_prev[MDP4_MIXER_MAX]; uint32 dmap_cfg[5]; uint32 cs_controller; uint32 panel_3d; uint32 panel_mode; uint32 mixer0_played; uint32 mixer1_played; uint32 mixer2_played; } mdp4_overlay_db = { .cs_controller = CS_CONTROLLER_0, .plist = { { .pipe_type = OVERLAY_TYPE_RGB, .pipe_num = OVERLAY_PIPE_RGB1, .pipe_ndx = 1, }, { .pipe_type = OVERLAY_TYPE_RGB, .pipe_num = OVERLAY_PIPE_RGB2, .pipe_ndx = 2, }, { .pipe_type = OVERLAY_TYPE_VIDEO, .pipe_num = OVERLAY_PIPE_VG1, .pipe_ndx = 3, }, { .pipe_type = OVERLAY_TYPE_VIDEO, .pipe_num = OVERLAY_PIPE_VG2, .pipe_ndx = 4, }, { .pipe_type = OVERLAY_TYPE_BF, .pipe_num = OVERLAY_PIPE_RGB3, .pipe_ndx = 5, .mixer_num = MDP4_MIXER0, }, { .pipe_type = OVERLAY_TYPE_BF, .pipe_num = OVERLAY_PIPE_VG3, .pipe_ndx = 6, .mixer_num = MDP4_MIXER1, }, { .pipe_type = OVERLAY_TYPE_BF, .pipe_num = OVERLAY_PIPE_VG4, .pipe_ndx = 7, .mixer_num = MDP4_MIXER2, }, }, }; static DEFINE_MUTEX(iommu_mutex); static DEFINE_MUTEX(perf_mutex); static struct mdp4_overlay_ctrl *ctrl = &mdp4_overlay_db; struct mdp4_overlay_perf { u32 mdp_clk_rate; u32 use_ov_blt[MDP4_MIXER_MAX]; u64 mdp_ov_ab_bw[MDP4_MIXER_MAX]; u64 mdp_ov_ib_bw[MDP4_MIXER_MAX]; u32 mdp_ab_bw; u32 mdp_ib_bw; }; static struct mdp4_overlay_perf perf_request; static struct mdp4_overlay_perf perf_current; void mdp4_overlay_free_base_pipe(struct msm_fb_data_type *mfd) { if (!hdmi_prim_display && mfd->index == 0) { if (ctrl->panel_mode & MDP4_PANEL_DSI_VIDEO) mdp4_dsi_video_free_base_pipe(mfd); else if (ctrl->panel_mode & MDP4_PANEL_DSI_CMD) mdp4_dsi_cmd_free_base_pipe(mfd); else if (ctrl->panel_mode & MDP4_PANEL_LCDC) mdp4_lcdc_free_base_pipe(mfd); } else if (hdmi_prim_display || mfd->index == 1) { mdp4_dtv_free_base_pipe(mfd); } } static struct ion_client *display_iclient; static int mdp4_map_sec_resource(struct msm_fb_data_type *mfd) { int ret = 0; if (!mfd) { pr_err("%s: mfd is invalid\n", __func__); return -ENODEV; } pr_debug("%s %d mfd->index=%d,mapped=%d\n", __func__, __LINE__, mfd->index, mfd->sec_mapped); if (mfd->sec_mapped) return 0; ret = mdp_enable_iommu_clocks(); if (ret) { pr_err("IOMMU clock enabled failed while open"); return ret; } ret = msm_ion_secure_heap(ION_HEAP(ION_CP_MM_HEAP_ID)); if (ret) pr_err("ION heap secure failed heap id %d ret %d\n", ION_CP_MM_HEAP_ID, ret); else mfd->sec_mapped = 1; mdp_disable_iommu_clocks(); return ret; } int mdp4_unmap_sec_resource(struct msm_fb_data_type *mfd) { int ret = 0; int i, sec_cnt = 0; struct mdp4_overlay_pipe *pipe; if (!mfd) { pr_err("%s: mfd is invalid\n", __func__); return -ENODEV; } if (mfd->sec_mapped == 0) return 0; for (i = 0; i < OVERLAY_PIPE_MAX; i++) { pipe = &ctrl->plist[i]; if ((pipe->mixer_num == mfd->index) && pipe->flags & MDP_SECURE_OVERLAY_SESSION) sec_cnt++; } if (sec_cnt) return 0; pr_debug("%s %d mfd->index=%d,mapped=%d\n", __func__, __LINE__, mfd->index, mfd->sec_mapped); ret = mdp_enable_iommu_clocks(); if (ret) { pr_err("IOMMU clock enabled failed while close\n"); return ret; } msm_ion_unsecure_heap(ION_HEAP(ION_CP_MM_HEAP_ID)); mfd->sec_mapped = 0; mdp_disable_iommu_clocks(); return ret; } /* * mdp4_overlay_iommu_unmap_freelist() * mdp4_overlay_iommu_2freelist() * mdp4_overlay_iommu_pipe_free() * above three functiosns need to be called from same thread and * in order so that no mutex are needed. */ void mdp4_overlay_iommu_unmap_freelist(int mixer) { int i; struct ion_handle *ihdl; struct iommu_free_list *flist, *pflist; if (mixer >= MDP4_MIXER_MAX) return; mutex_lock(&iommu_mutex); pflist = &ctrl->iommu_free_prev[mixer]; flist = &ctrl->iommu_free[mixer]; pr_debug("%s: mixer=%d fndx=%d %d\n", __func__, mixer, pflist->fndx, flist->fndx); if (pflist->fndx == 0) { goto flist_to_pflist; } for (i = 0; i < IOMMU_FREE_LIST_MAX; i++) { ihdl = pflist->ihdl[i]; if (ihdl == NULL) continue; pr_debug("%s: mixer=%d i=%d ihdl=0x%p\n", __func__, mixer, i, ihdl); ion_unmap_iommu(display_iclient, ihdl, DISPLAY_READ_DOMAIN, GEN_POOL); mdp4_stat.iommu_unmap++; pr_debug("%s: map=%d unmap=%d drop=%d\n", __func__, (int)mdp4_stat.iommu_map, (int)mdp4_stat.iommu_unmap, (int)mdp4_stat.iommu_drop); ion_free(display_iclient, ihdl); } flist_to_pflist: /* move flist to pflist*/ memcpy(pflist, flist, sizeof(*pflist)); memset(flist, 0, sizeof(*flist)); mutex_unlock(&iommu_mutex); } void mdp4_overlay_iommu_2freelist(int mixer, struct ion_handle *ihdl) { struct iommu_free_list *flist; flist = &ctrl->iommu_free[mixer]; if (flist->fndx >= IOMMU_FREE_LIST_MAX) { pr_err("%s: Error, mixer=%d iommu fndx=%d\n", __func__, mixer, flist->fndx); mdp4_stat.iommu_drop++; return; } pr_debug("%s: add mixer=%d fndx=%d ihdl=0x%p\n", __func__, mixer, flist->fndx, ihdl); flist->ihdl[flist->fndx++] = ihdl; } void mdp4_overlay_iommu_pipe_free(int ndx, int all) { struct mdp4_overlay_pipe *pipe; struct mdp4_iommu_pipe_info *iom; int plane, mixer; pipe = mdp4_overlay_ndx2pipe(ndx); if (pipe == NULL) return; if (pipe->flags & MDP_MEMORY_ID_TYPE_FB) { pipe->flags &= ~MDP_MEMORY_ID_TYPE_FB; if (pipe->put0_need) { fput_light(pipe->srcp0_file, pipe->put0_need); pipe->put0_need = 0; } if (pipe->put1_need) { fput_light(pipe->srcp1_file, pipe->put1_need); pipe->put1_need = 0; } if (pipe->put2_need) { fput_light(pipe->srcp2_file, pipe->put2_need); pipe->put2_need = 0; } pr_debug("%s: ndx=%d flags=%x put=%d\n", __func__, pipe->pipe_ndx, pipe->flags, pipe->put0_need); return; } mutex_lock(&iommu_mutex); mixer = pipe->mixer_num; iom = &pipe->iommu; pr_debug("%s: mixer=%d ndx=%d all=%d\n", __func__, mixer, pipe->pipe_ndx, all); for (plane = 0; plane < MDP4_MAX_PLANE; plane++) { if (iom->prev_ihdl[plane]) { mdp4_overlay_iommu_2freelist(mixer, iom->prev_ihdl[plane]); iom->prev_ihdl[plane] = NULL; } if (all && iom->ihdl[plane]) { mdp4_overlay_iommu_2freelist(mixer, iom->ihdl[plane]); iom->ihdl[plane] = NULL; } } mutex_unlock(&iommu_mutex); } int mdp4_overlay_iommu_map_buf(int mem_id, struct mdp4_overlay_pipe *pipe, unsigned int plane, unsigned long *start, unsigned long *len, struct ion_handle **srcp_ihdl) { struct mdp4_iommu_pipe_info *iom; if (!display_iclient) return -EINVAL; *srcp_ihdl = ion_import_dma_buf(display_iclient, mem_id); if (IS_ERR_OR_NULL(*srcp_ihdl)) { pr_err("ion_import_dma_buf() failed\n"); return PTR_ERR(*srcp_ihdl); } pr_debug("%s(): ion_hdl %p, ion_buf %d\n", __func__, *srcp_ihdl, ion_share_dma_buf(display_iclient, *srcp_ihdl)); pr_debug("mixer %u, pipe %u, plane %u\n", pipe->mixer_num, pipe->pipe_ndx, plane); if (ion_map_iommu(display_iclient, *srcp_ihdl, DISPLAY_READ_DOMAIN, GEN_POOL, SZ_4K, 0, start, len, 0, 0)) { ion_free(display_iclient, *srcp_ihdl); pr_err("ion_map_iommu() failed\n"); return -EINVAL; } mutex_lock(&iommu_mutex); iom = &pipe->iommu; if (iom->prev_ihdl[plane]) { mdp4_overlay_iommu_2freelist(pipe->mixer_num, iom->prev_ihdl[plane]); mdp4_stat.iommu_drop++; pr_err("%s: dropped, ndx=%d plane=%d\n", __func__, pipe->pipe_ndx, plane); } iom->prev_ihdl[plane] = iom->ihdl[plane]; iom->ihdl[plane] = *srcp_ihdl; mdp4_stat.iommu_map++; pr_debug("%s: ndx=%d plane=%d prev=0x%p cur=0x%p start=0x%lx len=%lx\n", __func__, pipe->pipe_ndx, plane, iom->prev_ihdl[plane], iom->ihdl[plane], *start, *len); mutex_unlock(&iommu_mutex); return 0; } static struct mdp4_iommu_pipe_info mdp_iommu[MDP4_MIXER_MAX][OVERLAY_PIPE_MAX]; void mdp4_iommu_unmap(struct mdp4_overlay_pipe *pipe) { struct mdp4_iommu_pipe_info *iom_pipe_info; unsigned char i, j; if (!display_iclient) return; for (j = 0; j < OVERLAY_PIPE_MAX; j++) { iom_pipe_info = &mdp_iommu[pipe->mixer_num][j]; for (i = 0; i < MDP4_MAX_PLANE; i++) { if (iom_pipe_info->prev_ihdl[i]) { pr_debug("%s(): mixer %u, pipe %u, plane %u, " "prev_ihdl %p\n", __func__, pipe->mixer_num, j + 1, i, iom_pipe_info->prev_ihdl[i]); ion_unmap_iommu(display_iclient, iom_pipe_info->prev_ihdl[i], DISPLAY_READ_DOMAIN, GEN_POOL); ion_free(display_iclient, iom_pipe_info->prev_ihdl[i]); iom_pipe_info->prev_ihdl[i] = NULL; } if (iom_pipe_info->mark_unmap) { if (iom_pipe_info->ihdl[i]) { pr_debug("%s(): MARK, mixer %u, pipe %u, plane %u, " "ihdl %p\n", __func__, pipe->mixer_num, j + 1, i, iom_pipe_info->ihdl[i]); ion_unmap_iommu(display_iclient, iom_pipe_info->ihdl[i], DISPLAY_READ_DOMAIN, GEN_POOL); ion_free(display_iclient, iom_pipe_info->ihdl[i]); iom_pipe_info->ihdl[i] = NULL; } } } iom_pipe_info->mark_unmap = 0; } } #if defined(CONFIG_FB_MSM_MIPI_LGIT_VIDEO_FHD_INVERSE_PT) static int panel_rotate_180 = 1; #endif int mdp4_overlay_mixer_play(int mixer_num) { if (mixer_num == MDP4_MIXER2) return ctrl->mixer2_played; else if (mixer_num == MDP4_MIXER1) return ctrl->mixer1_played; else return ctrl->mixer0_played; } void mdp4_overlay_panel_3d(int mixer_num, uint32 panel_3d) { ctrl->panel_3d = panel_3d; } void mdp4_overlay_panel_mode(int mixer_num, uint32 mode) { ctrl->panel_mode |= mode; } void mdp4_overlay_panel_mode_unset(int mixer_num, uint32 mode) { ctrl->panel_mode &= ~mode; } uint32 mdp4_overlay_panel_list(void) { return ctrl->panel_mode; } int mdp4_overlay_borderfill_supported(void) { return (mdp_rev >= MDP_REV_42); } void mdp4_overlay_dmae_cfg(struct msm_fb_data_type *mfd, int atv) { uint32 dmae_cfg_reg; if (atv) dmae_cfg_reg = DMA_DEFLKR_EN; else dmae_cfg_reg = 0; if (mfd->fb_imgType == MDP_BGR_565) dmae_cfg_reg |= DMA_PACK_PATTERN_BGR; else dmae_cfg_reg |= DMA_PACK_PATTERN_RGB; if (mfd->panel_info.bpp == 18) { dmae_cfg_reg |= DMA_DSTC0G_6BITS | /* 666 18BPP */ DMA_DSTC1B_6BITS | DMA_DSTC2R_6BITS; } else if (mfd->panel_info.bpp == 16) { dmae_cfg_reg |= DMA_DSTC0G_6BITS | /* 565 16BPP */ DMA_DSTC1B_5BITS | DMA_DSTC2R_5BITS; } else { dmae_cfg_reg |= DMA_DSTC0G_8BITS | /* 888 16BPP */ DMA_DSTC1B_8BITS | DMA_DSTC2R_8BITS; } mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); /* dma2 config register */ MDP_OUTP(MDP_BASE + 0xb0000, dmae_cfg_reg); if (atv) { MDP_OUTP(MDP_BASE + 0xb0070, 0xeb0010); MDP_OUTP(MDP_BASE + 0xb0074, 0xf00010); MDP_OUTP(MDP_BASE + 0xb0078, 0xf00010); MDP_OUTP(MDP_BASE + 0xb3000, 0x80); MDP_OUTP(MDP_BASE + 0xb3010, 0x1800040); MDP_OUTP(MDP_BASE + 0xb3014, 0x1000080); MDP_OUTP(MDP_BASE + 0xb4004, 0x67686970); } else { mdp_vid_quant_set(); } mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); } #ifdef CONFIG_FB_MSM_HDMI_3D void unfill_black_screen(void) { return; } #else void unfill_black_screen(void) { uint32 temp_src_format; mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); /* * VG2 Constant Color */ temp_src_format = inpdw(MDP_BASE + 0x30050); MDP_OUTP(MDP_BASE + 0x30050, temp_src_format&(~BIT(22))); /* * MDP_OVERLAY_REG_FLUSH */ MDP_OUTP(MDP_BASE + 0x18000, BIT(3)); mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); return; } #endif #ifdef CONFIG_FB_MSM_HDMI_3D void fill_black_screen(void) { return; } #else void fill_black_screen(void) { /*Black color*/ uint32 color = 0x00000000; uint32 temp_src_format; mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); /* * VG2 Constant Color */ MDP_OUTP(MDP_BASE + 0x31008, color); /* * MDP_VG2_SRC_FORMAT */ temp_src_format = inpdw(MDP_BASE + 0x30050); MDP_OUTP(MDP_BASE + 0x30050, temp_src_format | BIT(22)); /* * MDP_OVERLAY_REG_FLUSH */ MDP_OUTP(MDP_BASE + 0x18000, BIT(3)); mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); return; } #endif void mdp4_overlay_dmae_xy(struct mdp4_overlay_pipe *pipe) { mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); MDP_OUTP(MDP_BASE + 0xb0004, (pipe->src_height << 16 | pipe->src_width)); if (pipe->dma_blt_addr) { uint32 off, bpp; #ifdef BLT_RGB565 bpp = 2; /* overlay ouput is RGB565 */ #else bpp = 3; /* overlay ouput is RGB888 */ #endif off = 0; if (pipe->ov_cnt & 0x01) off = pipe->src_height * pipe->src_width * bpp; MDP_OUTP(MDP_BASE + 0xb0008, pipe->dma_blt_addr + off); /* RGB888, output of overlay blending */ MDP_OUTP(MDP_BASE + 0xb000c, pipe->src_width * bpp); } else { /* dma_e source */ MDP_OUTP(MDP_BASE + 0xb0008, pipe->srcp0_addr); MDP_OUTP(MDP_BASE + 0xb000c, pipe->srcp0_ystride); } /* dma_e dest */ MDP_OUTP(MDP_BASE + 0xb0010, (pipe->dst_y << 16 | pipe->dst_x)); mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); } void mdp4_overlay_dmap_cfg(struct msm_fb_data_type *mfd, int lcdc) { uint32 dma2_cfg_reg; uint32 mask, curr; dma2_cfg_reg = DMA_DITHER_EN; #ifdef BLT_RGB565 /* RGB888 is 0 */ dma2_cfg_reg |= DMA_BUF_FORMAT_RGB565; /* blt only */ #endif if (mfd->fb_imgType == MDP_BGR_565) dma2_cfg_reg |= DMA_PACK_PATTERN_BGR; else dma2_cfg_reg |= DMA_PACK_PATTERN_RGB; if ((mfd->panel_info.type == MIPI_CMD_PANEL) || (mfd->panel_info.type == MIPI_VIDEO_PANEL)) { dma2_cfg_reg |= DMA_DSTC0G_8BITS | /* 888 24BPP */ DMA_DSTC1B_8BITS | DMA_DSTC2R_8BITS; } else if (mfd->panel_info.bpp == 18) { dma2_cfg_reg |= DMA_DSTC0G_6BITS | /* 666 18BPP */ DMA_DSTC1B_6BITS | DMA_DSTC2R_6BITS; } else if (mfd->panel_info.bpp == 16) { dma2_cfg_reg |= DMA_DSTC0G_6BITS | /* 565 16BPP */ DMA_DSTC1B_5BITS | DMA_DSTC2R_5BITS; } else { dma2_cfg_reg |= DMA_DSTC0G_8BITS | /* 888 24BPP */ DMA_DSTC1B_8BITS | DMA_DSTC2R_8BITS; } mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); #ifndef CONFIG_FB_MSM_LCDC_CHIMEI_WXGA_PANEL if (lcdc) dma2_cfg_reg |= DMA_PACK_ALIGN_MSB; #endif /* dma2 config register */ curr = inpdw(MDP_BASE + 0x90000); mask = 0x0FFFFFFF; dma2_cfg_reg = (dma2_cfg_reg & mask) | (curr & ~mask); MDP_OUTP(MDP_BASE + 0x90000, dma2_cfg_reg); ctrl->dmap_cfg[0] = dma2_cfg_reg; mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); } /* * mdp4_overlay_dmap_xy: called form baselayer only */ void mdp4_overlay_dmap_xy(struct mdp4_overlay_pipe *pipe) { uint32 off, bpp; if (!in_interrupt()) mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); if (pipe->dma_blt_addr) { #ifdef BLT_RGB565 bpp = 2; /* overlay ouput is RGB565 */ #else bpp = 3; /* overlay ouput is RGB888 */ #endif off = 0; if (pipe->dmap_cnt & 0x01) off = pipe->src_height * pipe->src_width * bpp; ctrl->dmap_cfg[2] = pipe->dma_blt_addr + off; MDP_OUTP(MDP_BASE + 0x90008, pipe->dma_blt_addr + off); /* RGB888, output of overlay blending */ MDP_OUTP(MDP_BASE + 0x9000c, pipe->src_width * bpp); ctrl->dmap_cfg[3] = pipe->src_width * bpp; } else { MDP_OUTP(MDP_BASE + 0x90008, pipe->srcp0_addr); ctrl->dmap_cfg[2] = pipe->srcp0_addr; MDP_OUTP(MDP_BASE + 0x9000c, pipe->srcp0_ystride); ctrl->dmap_cfg[3] = pipe->srcp0_ystride; } /* dma_p source */ MDP_OUTP(MDP_BASE + 0x90004, (pipe->src_height << 16 | pipe->src_width)); ctrl->dmap_cfg[1] = (pipe->src_height << 16 | pipe->src_width); /* dma_p dest */ MDP_OUTP(MDP_BASE + 0x90010, (pipe->dst_y << 16 | pipe->dst_x)); ctrl->dmap_cfg[4] = (pipe->dst_y << 16 | pipe->dst_x); if (!in_interrupt()) mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); } static void mdp4_overlay_dmap_reconfig(void) { MDP_OUTP(MDP_BASE + 0x90000, ctrl->dmap_cfg[0]); MDP_OUTP(MDP_BASE + 0x90004, ctrl->dmap_cfg[1]); MDP_OUTP(MDP_BASE + 0x90008, ctrl->dmap_cfg[2]); MDP_OUTP(MDP_BASE + 0x9000c, ctrl->dmap_cfg[3]); MDP_OUTP(MDP_BASE + 0x90010, ctrl->dmap_cfg[4]); } #define MDP4_VG_PHASE_STEP_DEFAULT 0x20000000 #define MDP4_VG_PHASE_STEP_SHIFT 29 static int mdp4_leading_0(uint32 num) { uint32 bit = 0x80000000; int i; for (i = 0; i < 32; i++) { if (bit & num) return i; bit >>= 1; } return i; } static uint32 mdp4_scale_phase_step(int f_num, uint32 src, uint32 dst) { uint32 val, s; int n; n = mdp4_leading_0(src); if (n > f_num) n = f_num; s = src << n; /* maximum to reduce lose of resolution */ val = s / dst; if (n < f_num) { n = f_num - n; val <<= n; val |= ((s % dst) << n) / dst; } return val; } static void mdp4_scale_setup(struct mdp4_overlay_pipe *pipe) { pipe->phasex_step = MDP4_VG_PHASE_STEP_DEFAULT; pipe->phasey_step = MDP4_VG_PHASE_STEP_DEFAULT; if (pipe->dst_h && pipe->src_h != pipe->dst_h) { u32 upscale_max; upscale_max = (mdp_rev >= MDP_REV_41) ? MDP4_REV41_OR_LATER_UP_SCALING_MAX : MDP4_REV40_UP_SCALING_MAX; if (pipe->dst_h > pipe->src_h * upscale_max) return; pipe->op_mode |= MDP4_OP_SCALEY_EN; if (pipe->pipe_type == OVERLAY_TYPE_VIDEO) { if (pipe->flags & MDP_BACKEND_COMPOSITION && pipe->alpha_enable && pipe->dst_h > pipe->src_h) pipe->op_mode |= MDP4_OP_SCALEY_PIXEL_RPT; else if (pipe->dst_h <= (pipe->src_h / 4)) pipe->op_mode |= MDP4_OP_SCALEY_MN_PHASE; else pipe->op_mode |= MDP4_OP_SCALEY_FIR; } else { /* RGB pipe */ pipe->op_mode |= MDP4_OP_SCALE_RGB_ENHANCED | MDP4_OP_SCALE_RGB_BILINEAR | MDP4_OP_SCALE_ALPHA_BILINEAR; } pipe->phasey_step = mdp4_scale_phase_step(29, pipe->src_h, pipe->dst_h); } if (pipe->dst_w && pipe->src_w != pipe->dst_w) { u32 upscale_max; upscale_max = (mdp_rev >= MDP_REV_41) ? MDP4_REV41_OR_LATER_UP_SCALING_MAX : MDP4_REV40_UP_SCALING_MAX; if (pipe->dst_w > pipe->src_w * upscale_max) return; pipe->op_mode |= MDP4_OP_SCALEX_EN; if (pipe->pipe_type == OVERLAY_TYPE_VIDEO) { if (pipe->flags & MDP_BACKEND_COMPOSITION && pipe->alpha_enable && pipe->dst_w > pipe->src_w) pipe->op_mode |= MDP4_OP_SCALEX_PIXEL_RPT; else if (pipe->dst_w <= (pipe->src_w / 4)) pipe->op_mode |= MDP4_OP_SCALEX_MN_PHASE; else pipe->op_mode |= MDP4_OP_SCALEX_FIR; } else { /* RGB pipe */ pipe->op_mode |= MDP4_OP_SCALE_RGB_ENHANCED | MDP4_OP_SCALE_RGB_BILINEAR | MDP4_OP_SCALE_ALPHA_BILINEAR; } pipe->phasex_step = mdp4_scale_phase_step(29, pipe->src_w, pipe->dst_w); } } void mdp4_overlay_solidfill_init(struct mdp4_overlay_pipe *pipe) { char *base; uint32 src_size, src_xy, dst_size, dst_xy; uint32 format; uint32 off; int i; src_size = ((pipe->src_h << 16) | pipe->src_w); src_xy = ((pipe->src_y << 16) | pipe->src_x); dst_size = ((pipe->dst_h << 16) | pipe->dst_w); dst_xy = ((pipe->dst_y << 16) | pipe->dst_x); base = MDP_BASE + MDP4_VIDEO_BASE; off = MDP4_VIDEO_OFF; /* 0x10000 */ mdp_clk_ctrl(1); for(i = 0; i < 4; i++) { /* 4 pipes */ format = inpdw(base + 0x50); format |= MDP4_FORMAT_SOLID_FILL; outpdw(base + 0x0000, src_size);/* MDP_RGB_SRC_SIZE */ outpdw(base + 0x0004, src_xy); /* MDP_RGB_SRC_XY */ outpdw(base + 0x0008, dst_size);/* MDP_RGB_DST_SIZE */ outpdw(base + 0x000c, dst_xy); /* MDP_RGB_DST_XY */ outpdw(base + 0x0050, format);/* MDP_RGB_SRC_FORMAT */ outpdw(base + 0x1008, 0x0);/* Black */ base += off; } /* * keep it at primary * will be picked up at first commit */ ctrl->flush[MDP4_MIXER0] = 0x3c; /* all pipes */ mdp_clk_ctrl(0); } void mdp4_overlay_rgb_setup(struct mdp4_overlay_pipe *pipe) { char *rgb_base; uint32 src_size, src_xy, dst_size, dst_xy; uint32 format, pattern; uint32 curr, mask; uint32 offset = 0; int pnum; pnum = pipe->pipe_num - OVERLAY_PIPE_RGB1; /* start from 0 */ rgb_base = MDP_BASE + MDP4_RGB_BASE; rgb_base += (MDP4_RGB_OFF * pnum); src_size = ((pipe->src_h << 16) | pipe->src_w); src_xy = ((pipe->src_y << 16) | pipe->src_x); dst_size = ((pipe->dst_h << 16) | pipe->dst_w); dst_xy = ((pipe->dst_y << 16) | pipe->dst_x); if ((pipe->src_x + pipe->src_w) > 0x7FF) { offset += pipe->src_x * pipe->bpp; src_xy &= 0xFFFF0000; } if ((pipe->src_y + pipe->src_h) > 0x7FF) { offset += pipe->src_y * pipe->src_width * pipe->bpp; src_xy &= 0x0000FFFF; } format = mdp4_overlay_format(pipe); pattern = mdp4_overlay_unpack_pattern(pipe); #ifdef MDP4_IGC_LUT_ENABLE pipe->op_mode |= MDP4_OP_IGC_LUT_EN; #endif mdp4_scale_setup(pipe); mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); /* Ensure proper covert matrix loaded when color space swaps */ curr = inpdw(rgb_base + 0x0058); /* Don't touch bits you don't want to configure*/ mask = 0xFFFEFFFF; pipe->op_mode = (pipe->op_mode & mask) | (curr & ~mask); #if defined(CONFIG_FB_MSM_MIPI_LGIT_VIDEO_FHD_INVERSE_PT) //2012-11-20 [email protected] : QCT pre patch for the inverted clone image [START] if((pipe->mfd->panel_info.type != DTV_PANEL)&&(pipe->mfd->panel_info.type != WRITEBACK_PANEL)) //2012-11-20 [email protected] : QCT pre patch for the inverted clone image [END] { if (panel_rotate_180 && (pipe->pipe_num == OVERLAY_PIPE_RGB1 || pipe->pipe_num == OVERLAY_PIPE_RGB2)) { uint32 op_mode = pipe->op_mode | MDP4_OP_FLIP_UD | MDP4_OP_SCALEY_EN; if (pipe->ext_flag & MDP_FLIP_UD) op_mode &= ~MDP4_OP_FLIP_UD; pipe->op_mode = op_mode; } if ((pipe->op_mode & MDP4_OP_FLIP_UD) && pipe->mfd) dst_xy = (((pipe->mfd->panel_info.yres - pipe->dst_y - pipe->dst_h) << 16) | pipe->dst_x); } if (!pipe->mfd) pr_err("rgb mfd is not set\n"); #endif outpdw(rgb_base + 0x0000, src_size); /* MDP_RGB_SRC_SIZE */ outpdw(rgb_base + 0x0004, src_xy); /* MDP_RGB_SRC_XY */ outpdw(rgb_base + 0x0008, dst_size); /* MDP_RGB_DST_SIZE */ outpdw(rgb_base + 0x000c, dst_xy); /* MDP_RGB_DST_XY */ outpdw(rgb_base + 0x0010, pipe->srcp0_addr + offset); outpdw(rgb_base + 0x0040, pipe->srcp0_ystride); outpdw(rgb_base + 0x0050, format);/* MDP_RGB_SRC_FORMAT */ outpdw(rgb_base + 0x0054, pattern);/* MDP_RGB_SRC_UNPACK_PATTERN */ if (format & MDP4_FORMAT_SOLID_FILL) { u32 op_mode = pipe->op_mode; op_mode &= ~(MDP4_OP_FLIP_LR + MDP4_OP_SCALEX_EN); op_mode &= ~(MDP4_OP_FLIP_UD + MDP4_OP_SCALEY_EN); outpdw(rgb_base + 0x0058, op_mode);/* MDP_RGB_OP_MODE */ } else { if (pipe->op_mode & MDP4_OP_FLIP_LR && mdp_rev >= MDP_REV_42) { /* Enable x-scaling bit to enable LR flip */ /* for MDP > 4.2 targets */ pipe->op_mode |= 0x01; } outpdw(rgb_base + 0x0058, pipe->op_mode);/* MDP_RGB_OP_MODE */ } outpdw(rgb_base + 0x005c, pipe->phasex_step); outpdw(rgb_base + 0x0060, pipe->phasey_step); mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); mdp4_stat.pipe[pipe->pipe_num]++; } static void mdp4_overlay_vg_get_src_offset(struct mdp4_overlay_pipe *pipe, char *vg_base, uint32 *luma_off, uint32 *chroma_off) { uint32 src_xy; *luma_off = 0; *chroma_off = 0; if (pipe->src_x && (pipe->frame_format == MDP4_FRAME_FORMAT_LINEAR)) { src_xy = (pipe->src_y << 16) | pipe->src_x; src_xy &= 0xffff0000; outpdw(vg_base + 0x0004, src_xy); /* MDP_RGB_SRC_XY */ switch (pipe->src_format) { case MDP_Y_CR_CB_H2V2: case MDP_Y_CR_CB_GH2V2: case MDP_Y_CB_CR_H2V2: *luma_off = pipe->src_x; *chroma_off = pipe->src_x/2; break; case MDP_Y_CBCR_H2V2_TILE: case MDP_Y_CRCB_H2V2_TILE: case MDP_Y_CBCR_H2V2: case MDP_Y_CRCB_H2V2: case MDP_Y_CRCB_H1V1: case MDP_Y_CBCR_H1V1: case MDP_Y_CRCB_H2V1: case MDP_Y_CBCR_H2V1: case MDP_Y_CRCB_H1V2: case MDP_Y_CBCR_H1V2: *luma_off = pipe->src_x + (pipe->src_y * pipe->srcp0_ystride); *chroma_off = pipe->src_x + (pipe->src_y * pipe->srcp1_ystride); break; case MDP_YCBYCR_H2V1: case MDP_YCRYCB_H2V1: if (pipe->src_x & 0x1) pipe->src_x += 1; *luma_off += pipe->src_x * 2; break; case MDP_ARGB_8888: case MDP_RGBA_8888: case MDP_BGRA_8888: case MDP_RGBX_8888: case MDP_RGB_565: case MDP_BGR_565: case MDP_XRGB_8888: case MDP_RGB_888: case MDP_YCBCR_H1V1: case MDP_YCRCB_H1V1: *luma_off = pipe->src_x * pipe->bpp; break; default: pr_err("%s: fmt %u not supported for adjustment\n", __func__, pipe->src_format); break; } } } void mdp4_overlay_vg_setup(struct mdp4_overlay_pipe *pipe) { char *vg_base; uint32 frame_size, src_size, src_xy, dst_size, dst_xy; uint32 format, pattern, luma_offset, chroma_offset; /* 2012-11-29 [email protected] this code add to mdp tunning when start DMB in G, GK (apq8064) [S]*/ /* This source code confirmed by QCT*/ uint32 mask, curr, addr; /* 2012-11-29 [email protected] this code add to mdp tunning when start DMB in G, GK (apq8064) [E]*/ int pnum, ptype, i; uint32_t block; pnum = pipe->pipe_num - OVERLAY_PIPE_VG1; /* start from 0 */ vg_base = MDP_BASE + MDP4_VIDEO_BASE; vg_base += (MDP4_VIDEO_OFF * pnum); frame_size = ((pipe->src_height << 16) | pipe->src_width); src_size = ((pipe->src_h << 16) | pipe->src_w); src_xy = ((pipe->src_y << 16) | pipe->src_x); dst_size = ((pipe->dst_h << 16) | pipe->dst_w); dst_xy = ((pipe->dst_y << 16) | pipe->dst_x); ptype = mdp4_overlay_format2type(pipe->src_format); format = mdp4_overlay_format(pipe); pattern = mdp4_overlay_unpack_pattern(pipe); /* CSC Post Processing enabled? */ if (pipe->flags & MDP_OVERLAY_PP_CFG_EN) { if (pipe->pp_cfg.config_ops & MDP_OVERLAY_PP_CSC_CFG) { if (pipe->pp_cfg.csc_cfg.flags & MDP_CSC_FLAG_ENABLE) pipe->op_mode |= MDP4_OP_CSC_EN; if (pipe->pp_cfg.csc_cfg.flags & MDP_CSC_FLAG_YUV_IN) pipe->op_mode |= MDP4_OP_SRC_DATA_YCBCR; if (pipe->pp_cfg.csc_cfg.flags & MDP_CSC_FLAG_YUV_OUT) pipe->op_mode |= MDP4_OP_DST_DATA_YCBCR; mdp4_csc_write(&pipe->pp_cfg.csc_cfg, (uint32_t) (vg_base + MDP4_VIDEO_CSC_OFF)); if (pipe->pipe_num == OVERLAY_PIPE_VG1) block = MDP_BLOCK_VG_1; else block = MDP_BLOCK_VG_2; for (i = 0; i < CSC_MAX_BLOCKS; i++) { if (block == csc_cfg_matrix[i].block) { memcpy(&csc_cfg_matrix[i].csc_data, &(pipe->pp_cfg.csc_cfg), sizeof(struct mdp_csc_cfg)); break; } } } if (pipe->pp_cfg.config_ops & MDP_OVERLAY_PP_QSEED_CFG) { mdp4_qseed_access_cfg(&pipe->pp_cfg.qseed_cfg[0], (uint32_t) vg_base); mdp4_qseed_access_cfg(&pipe->pp_cfg.qseed_cfg[1], (uint32_t) vg_base); } } /* not RGB use VG pipe, pure VG pipe */ if (ptype != OVERLAY_TYPE_RGB) pipe->op_mode |= (MDP4_OP_CSC_EN | MDP4_OP_SRC_DATA_YCBCR); #ifdef MDP4_IGC_LUT_ENABLE pipe->op_mode |= MDP4_OP_IGC_LUT_EN; #endif mdp4_scale_setup(pipe); luma_offset = 0; chroma_offset = 0; if (ptype == OVERLAY_TYPE_RGB) { if ((pipe->src_y + pipe->src_h) > 0x7FF) { luma_offset = pipe->src_y * pipe->src_width * pipe->bpp; src_xy &= 0x0000FFFF; } if ((pipe->src_x + pipe->src_w) > 0x7FF) { luma_offset += pipe->src_x * pipe->bpp; src_xy &= 0xFFFF0000; } } #if defined(CONFIG_FB_MSM_MIPI_LGIT_VIDEO_FHD_INVERSE_PT) //2012-11-20 [email protected] : QCT pre patch for the inverted clone image [START] if((pipe->mfd->panel_info.type != DTV_PANEL) && (pipe->mfd->panel_info.type != WRITEBACK_PANEL)) //2012-11-20 [email protected] : QCT pre patch for the inverted clone image [END] { if (panel_rotate_180) { uint32 op_mode = pipe->op_mode | MDP4_OP_FLIP_UD; if (pipe->ext_flag & MDP_FLIP_UD) op_mode &= ~MDP4_OP_FLIP_UD; pipe->op_mode = op_mode; } if ((pipe->op_mode & MDP4_OP_FLIP_UD) && pipe->mfd) { dst_xy = (((pipe->mfd->panel_info.yres - pipe->dst_y - pipe->dst_h) << 16) | pipe->dst_x); outpdw(MDP_BASE + 0xE0044, 0xe0fff); } } if (!pipe->mfd) pr_err("vg mfd is not set\n"); #endif mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); outpdw(vg_base + 0x0000, src_size); /* MDP_RGB_SRC_SIZE */ outpdw(vg_base + 0x0004, src_xy); /* MDP_RGB_SRC_XY */ outpdw(vg_base + 0x0008, dst_size); /* MDP_RGB_DST_SIZE */ outpdw(vg_base + 0x000c, dst_xy); /* MDP_RGB_DST_XY */ if (pipe->frame_format != MDP4_FRAME_FORMAT_LINEAR) { struct mdp4_overlay_pipe *real_pipe; u32 psize, csize; /* * video tile frame size register is NOT double buffered. * when this register updated, it kicks in immediatly * During transition from smaller resolution to higher * resolution it may have possibility that mdp still fetch * from smaller resolution buffer with new higher resolution * frame size. This will cause iommu page fault. */ real_pipe = mdp4_overlay_ndx2pipe(pipe->pipe_ndx); psize = real_pipe->prev_src_height * real_pipe->prev_src_width; csize = pipe->src_height * pipe->src_width; if (psize && (csize > psize)) { frame_size = (real_pipe->prev_src_height << 16 | real_pipe->prev_src_width); } outpdw(vg_base + 0x0048, frame_size); /* TILE frame size */ real_pipe->prev_src_height = pipe->src_height; real_pipe->prev_src_width = pipe->src_width; } /* * Adjust src X offset to avoid MDP from overfetching pixels * present before the offset. This is required for video * frames coming with unused green pixels along the left margin */ /* not RGB use VG pipe, pure VG pipe */ if (ptype != OVERLAY_TYPE_RGB) { mdp4_overlay_vg_get_src_offset(pipe, vg_base, &luma_offset, &chroma_offset); } /* 2012-11-29 [email protected] this code add to mdp tunning when start DMB in G, GK (apq8064) [S]*/ /* This source code confirmed by QCT*/ /* Ensure proper covert matrix loaded when color space swaps */ curr = inpdw(vg_base + 0x0058); mask = 0x600; if ((curr & mask) != (pipe->op_mode & mask)) { addr = ((uint32_t)vg_base) + 0x4000; if (ptype != OVERLAY_TYPE_RGB) mdp4_csc_write(&(mdp_csc_convert[1]), addr); else mdp4_csc_write(&(mdp_csc_convert[0]), addr); mask = 0xFFFCFFFF; } else { /* Don't touch bits you don't want to configure*/ mask = 0xFFFCF1FF; } pipe->op_mode = (pipe->op_mode & mask) | (curr & ~mask); /* 2012-11-29 [email protected] this code add to mdp tunning when start DMB in G, GK (apq8064) [E]*/ /* luma component plane */ outpdw(vg_base + 0x0010, pipe->srcp0_addr + luma_offset); /* chroma component plane or planar color 1 */ outpdw(vg_base + 0x0014, pipe->srcp1_addr + chroma_offset); /* planar color 2 */ outpdw(vg_base + 0x0018, pipe->srcp2_addr + chroma_offset); outpdw(vg_base + 0x0040, pipe->srcp1_ystride << 16 | pipe->srcp0_ystride); outpdw(vg_base + 0x0044, pipe->srcp3_ystride << 16 | pipe->srcp2_ystride); outpdw(vg_base + 0x0050, format); /* MDP_RGB_SRC_FORMAT */ outpdw(vg_base + 0x0054, pattern); /* MDP_RGB_SRC_UNPACK_PATTERN */ if (format & MDP4_FORMAT_SOLID_FILL) { u32 op_mode = pipe->op_mode; op_mode &= ~(MDP4_OP_FLIP_LR + MDP4_OP_SCALEX_EN); op_mode &= ~(MDP4_OP_FLIP_UD + MDP4_OP_SCALEY_EN); outpdw(vg_base + 0x0058, op_mode);/* MDP_RGB_OP_MODE */ } else outpdw(vg_base + 0x0058, pipe->op_mode);/* MDP_RGB_OP_MODE */ outpdw(vg_base + 0x005c, pipe->phasex_step); outpdw(vg_base + 0x0060, pipe->phasey_step); if (pipe->op_mode & MDP4_OP_DITHER_EN) { outpdw(vg_base + 0x0068, pipe->r_bit << 4 | pipe->b_bit << 2 | pipe->g_bit); } if (mdp_rev > MDP_REV_41) { /* mdp chip select controller */ mask = 0; if (pipe->pipe_num == OVERLAY_PIPE_VG1) mask = 0x020; /* bit 5 */ else if (pipe->pipe_num == OVERLAY_PIPE_VG2) mask = 0x02000; /* bit 13 */ if (mask) { if (pipe->op_mode & MDP4_OP_SCALEY_MN_PHASE) ctrl->cs_controller &= ~mask; else ctrl->cs_controller |= mask; /* NOT double buffered */ outpdw(MDP_BASE + 0x00c0, ctrl->cs_controller); } } mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); mdp4_stat.pipe[pipe->pipe_num]++; } int mdp4_overlay_format2type(uint32 format) { switch (format) { case MDP_RGB_565: case MDP_RGB_888: case MDP_BGR_565: case MDP_XRGB_8888: case MDP_ARGB_8888: case MDP_RGBA_8888: case MDP_BGRA_8888: case MDP_RGBX_8888: return OVERLAY_TYPE_RGB; case MDP_YCBYCR_H2V1: case MDP_YCRYCB_H2V1: case MDP_Y_CRCB_H2V1: case MDP_Y_CBCR_H2V1: case MDP_Y_CRCB_H1V2: case MDP_Y_CBCR_H1V2: case MDP_Y_CRCB_H2V2: case MDP_Y_CBCR_H2V2: case MDP_Y_CBCR_H2V2_TILE: case MDP_Y_CRCB_H2V2_TILE: case MDP_Y_CR_CB_H2V2: case MDP_Y_CR_CB_GH2V2: case MDP_Y_CB_CR_H2V2: case MDP_Y_CRCB_H1V1: case MDP_Y_CBCR_H1V1: case MDP_YCRCB_H1V1: case MDP_YCBCR_H1V1: return OVERLAY_TYPE_VIDEO; case MDP_RGB_BORDERFILL: return OVERLAY_TYPE_BF; default: mdp4_stat.err_format++; return -ERANGE; } } #define C3_ALPHA 3 /* alpha */ #define C2_R_Cr 2 /* R/Cr */ #define C1_B_Cb 1 /* B/Cb */ #define C0_G_Y 0 /* G/luma */ #define YUV_444_MAX_WIDTH 1280 /* Max width for YUV 444*/ int mdp4_overlay_format2pipe(struct mdp4_overlay_pipe *pipe) { switch (pipe->src_format) { case MDP_RGB_565: pipe->frame_format = MDP4_FRAME_FORMAT_LINEAR; pipe->fetch_plane = OVERLAY_PLANE_INTERLEAVED; pipe->a_bit = 0; pipe->r_bit = 1; /* R, 5 bits */ pipe->b_bit = 1; /* B, 5 bits */ pipe->g_bit = 2; /* G, 6 bits */ pipe->alpha_enable = 0; pipe->unpack_tight = 1; pipe->unpack_align_msb = 0; pipe->unpack_count = 2; pipe->element2 = C2_R_Cr; /* R */ pipe->element1 = C0_G_Y; /* G */ pipe->element0 = C1_B_Cb; /* B */ pipe->bpp = 2; /* 2 bpp */ pipe->chroma_sample = MDP4_CHROMA_RGB; break; case MDP_RGB_888: pipe->frame_format = MDP4_FRAME_FORMAT_LINEAR; pipe->fetch_plane = OVERLAY_PLANE_INTERLEAVED; pipe->a_bit = 0; pipe->r_bit = 3; /* R, 8 bits */ pipe->b_bit = 3; /* B, 8 bits */ pipe->g_bit = 3; /* G, 8 bits */ pipe->alpha_enable = 0; pipe->unpack_tight = 1; pipe->unpack_align_msb = 0; pipe->unpack_count = 2; pipe->element2 = C1_B_Cb; /* B */ pipe->element1 = C0_G_Y; /* G */ pipe->element0 = C2_R_Cr; /* R */ pipe->bpp = 3; /* 3 bpp */ pipe->chroma_sample = MDP4_CHROMA_RGB; break; case MDP_BGR_565: pipe->frame_format = MDP4_FRAME_FORMAT_LINEAR; pipe->fetch_plane = OVERLAY_PLANE_INTERLEAVED; pipe->a_bit = 0; pipe->r_bit = 1; /* R, 5 bits */ pipe->b_bit = 1; /* B, 5 bits */ pipe->g_bit = 2; /* G, 6 bits */ pipe->alpha_enable = 0; pipe->unpack_tight = 1; pipe->unpack_align_msb = 0; pipe->unpack_count = 2; pipe->element2 = C1_B_Cb; /* B */ pipe->element1 = C0_G_Y; /* G */ pipe->element0 = C2_R_Cr; /* R */ pipe->bpp = 2; /* 2 bpp */ pipe->chroma_sample = MDP4_CHROMA_RGB; break; case MDP_XRGB_8888: pipe->frame_format = MDP4_FRAME_FORMAT_LINEAR; pipe->fetch_plane = OVERLAY_PLANE_INTERLEAVED; pipe->a_bit = 3; /* alpha, 4 bits */ pipe->r_bit = 3; /* R, 8 bits */ pipe->b_bit = 3; /* B, 8 bits */ pipe->g_bit = 3; /* G, 8 bits */ pipe->alpha_enable = 0; pipe->unpack_tight = 1; pipe->unpack_align_msb = 0; pipe->unpack_count = 3; pipe->element3 = C1_B_Cb; /* B */ pipe->element2 = C0_G_Y; /* G */ pipe->element1 = C2_R_Cr; /* R */ pipe->element0 = C3_ALPHA; /* alpha */ pipe->bpp = 4; /* 4 bpp */ pipe->chroma_sample = MDP4_CHROMA_RGB; break; case MDP_ARGB_8888: pipe->frame_format = MDP4_FRAME_FORMAT_LINEAR; pipe->fetch_plane = OVERLAY_PLANE_INTERLEAVED; pipe->a_bit = 3; /* alpha, 4 bits */ pipe->r_bit = 3; /* R, 8 bits */ pipe->b_bit = 3; /* B, 8 bits */ pipe->g_bit = 3; /* G, 8 bits */ pipe->alpha_enable = 1; pipe->unpack_tight = 1; pipe->unpack_align_msb = 0; pipe->unpack_count = 3; pipe->element3 = C1_B_Cb; /* B */ pipe->element2 = C0_G_Y; /* G */ pipe->element1 = C2_R_Cr; /* R */ pipe->element0 = C3_ALPHA; /* alpha */ pipe->bpp = 4; /* 4 bpp */ pipe->chroma_sample = MDP4_CHROMA_RGB; break; case MDP_RGBA_8888: pipe->frame_format = MDP4_FRAME_FORMAT_LINEAR; pipe->fetch_plane = OVERLAY_PLANE_INTERLEAVED; pipe->a_bit = 3; /* alpha, 4 bits */ pipe->r_bit = 3; /* R, 8 bits */ pipe->b_bit = 3; /* B, 8 bits */ pipe->g_bit = 3; /* G, 8 bits */ pipe->alpha_enable = 1; pipe->unpack_tight = 1; pipe->unpack_align_msb = 0; pipe->unpack_count = 3; pipe->element3 = C3_ALPHA; /* alpha */ pipe->element2 = C1_B_Cb; /* B */ pipe->element1 = C0_G_Y; /* G */ pipe->element0 = C2_R_Cr; /* R */ pipe->bpp = 4; /* 4 bpp */ pipe->chroma_sample = MDP4_CHROMA_RGB; break; case MDP_RGBX_8888: pipe->frame_format = MDP4_FRAME_FORMAT_LINEAR; pipe->fetch_plane = OVERLAY_PLANE_INTERLEAVED; pipe->a_bit = 3; pipe->r_bit = 3; /* R, 8 bits */ pipe->b_bit = 3; /* B, 8 bits */ pipe->g_bit = 3; /* G, 8 bits */ pipe->alpha_enable = 0; pipe->unpack_tight = 1; pipe->unpack_align_msb = 0; pipe->unpack_count = 3; pipe->element3 = C3_ALPHA; /* alpha */ pipe->element2 = C1_B_Cb; /* B */ pipe->element1 = C0_G_Y; /* G */ pipe->element0 = C2_R_Cr; /* R */ pipe->bpp = 4; /* 4 bpp */ pipe->chroma_sample = MDP4_CHROMA_RGB; break; case MDP_BGRA_8888: pipe->frame_format = MDP4_FRAME_FORMAT_LINEAR; pipe->fetch_plane = OVERLAY_PLANE_INTERLEAVED; pipe->a_bit = 3; /* alpha, 4 bits */ pipe->r_bit = 3; /* R, 8 bits */ pipe->b_bit = 3; /* B, 8 bits */ pipe->g_bit = 3; /* G, 8 bits */ pipe->alpha_enable = 1; pipe->unpack_tight = 1; pipe->unpack_align_msb = 0; pipe->unpack_count = 3; pipe->element3 = C3_ALPHA; /* alpha */ pipe->element2 = C2_R_Cr; /* R */ pipe->element1 = C0_G_Y; /* G */ pipe->element0 = C1_B_Cb; /* B */ pipe->bpp = 4; /* 4 bpp */ pipe->chroma_sample = MDP4_CHROMA_RGB; break; case MDP_YCBYCR_H2V1: case MDP_YCRYCB_H2V1: pipe->frame_format = MDP4_FRAME_FORMAT_LINEAR; pipe->fetch_plane = OVERLAY_PLANE_INTERLEAVED; pipe->a_bit = 0; /* alpha, 4 bits */ pipe->r_bit = 3; /* R, 8 bits */ pipe->b_bit = 3; /* B, 8 bits */ pipe->g_bit = 3; /* G, 8 bits */ pipe->alpha_enable = 0; pipe->unpack_tight = 1; pipe->unpack_align_msb = 0; pipe->unpack_count = 3; if (pipe->src_format == MDP_YCRYCB_H2V1) { pipe->element3 = C0_G_Y; /* G */ pipe->element2 = C2_R_Cr; /* R */ pipe->element1 = C0_G_Y; /* G */ pipe->element0 = C1_B_Cb; /* B */ } else if (pipe->src_format == MDP_YCBYCR_H2V1) { pipe->element3 = C0_G_Y; /* G */ pipe->element2 = C1_B_Cb; /* B */ pipe->element1 = C0_G_Y; /* G */ pipe->element0 = C2_R_Cr; /* R */ } pipe->bpp = 2; /* 2 bpp */ pipe->chroma_sample = MDP4_CHROMA_H2V1; break; case MDP_Y_CRCB_H2V1: case MDP_Y_CBCR_H2V1: case MDP_Y_CRCB_H1V2: case MDP_Y_CBCR_H1V2: case MDP_Y_CRCB_H2V2: case MDP_Y_CBCR_H2V2: case MDP_Y_CRCB_H1V1: case MDP_Y_CBCR_H1V1: pipe->frame_format = MDP4_FRAME_FORMAT_LINEAR; pipe->fetch_plane = OVERLAY_PLANE_PSEUDO_PLANAR; pipe->a_bit = 0; pipe->r_bit = 3; /* R, 8 bits */ pipe->b_bit = 3; /* B, 8 bits */ pipe->g_bit = 3; /* G, 8 bits */ pipe->alpha_enable = 0; pipe->unpack_tight = 1; pipe->unpack_align_msb = 0; pipe->unpack_count = 1; /* 2 */ if (pipe->src_format == MDP_Y_CRCB_H2V1) { pipe->element1 = C1_B_Cb; pipe->element0 = C2_R_Cr; pipe->chroma_sample = MDP4_CHROMA_H2V1; } else if (pipe->src_format == MDP_Y_CRCB_H1V1) { pipe->element1 = C1_B_Cb; pipe->element0 = C2_R_Cr; if (pipe->src_width > YUV_444_MAX_WIDTH) pipe->chroma_sample = MDP4_CHROMA_H1V2; else pipe->chroma_sample = MDP4_CHROMA_RGB; } else if (pipe->src_format == MDP_Y_CBCR_H2V1) { pipe->element1 = C2_R_Cr; pipe->element0 = C1_B_Cb; pipe->chroma_sample = MDP4_CHROMA_H2V1; } else if (pipe->src_format == MDP_Y_CBCR_H1V1) { pipe->element1 = C2_R_Cr; pipe->element0 = C1_B_Cb; if (pipe->src_width > YUV_444_MAX_WIDTH) pipe->chroma_sample = MDP4_CHROMA_H1V2; else pipe->chroma_sample = MDP4_CHROMA_RGB; } else if (pipe->src_format == MDP_Y_CRCB_H1V2) { pipe->element1 = C1_B_Cb; pipe->element0 = C2_R_Cr; pipe->chroma_sample = MDP4_CHROMA_H1V2; } else if (pipe->src_format == MDP_Y_CBCR_H1V2) { pipe->element1 = C2_R_Cr; pipe->element0 = C1_B_Cb; pipe->chroma_sample = MDP4_CHROMA_H1V2; } else if (pipe->src_format == MDP_Y_CRCB_H2V2) { pipe->element1 = C1_B_Cb; pipe->element0 = C2_R_Cr; pipe->chroma_sample = MDP4_CHROMA_420; } else if (pipe->src_format == MDP_Y_CBCR_H2V2) { pipe->element1 = C2_R_Cr; pipe->element0 = C1_B_Cb; pipe->chroma_sample = MDP4_CHROMA_420; } pipe->bpp = 2; /* 2 bpp */ break; case MDP_Y_CBCR_H2V2_TILE: case MDP_Y_CRCB_H2V2_TILE: pipe->frame_format = MDP4_FRAME_FORMAT_VIDEO_SUPERTILE; pipe->fetch_plane = OVERLAY_PLANE_PSEUDO_PLANAR; pipe->a_bit = 0; pipe->r_bit = 3; /* R, 8 bits */ pipe->b_bit = 3; /* B, 8 bits */ pipe->g_bit = 3; /* G, 8 bits */ pipe->alpha_enable = 0; pipe->unpack_tight = 1; pipe->unpack_align_msb = 0; pipe->unpack_count = 1; /* 2 */ if (pipe->src_format == MDP_Y_CRCB_H2V2_TILE) { pipe->element1 = C1_B_Cb; /* B */ pipe->element0 = C2_R_Cr; /* R */ pipe->chroma_sample = MDP4_CHROMA_420; } else if (pipe->src_format == MDP_Y_CBCR_H2V2_TILE) { pipe->element1 = C2_R_Cr; /* R */ pipe->element0 = C1_B_Cb; /* B */ pipe->chroma_sample = MDP4_CHROMA_420; } pipe->bpp = 2; /* 2 bpp */ break; case MDP_Y_CR_CB_H2V2: case MDP_Y_CR_CB_GH2V2: case MDP_Y_CB_CR_H2V2: pipe->frame_format = MDP4_FRAME_FORMAT_LINEAR; pipe->fetch_plane = OVERLAY_PLANE_PLANAR; pipe->a_bit = 0; pipe->r_bit = 3; /* R, 8 bits */ pipe->b_bit = 3; /* B, 8 bits */ pipe->g_bit = 3; /* G, 8 bits */ pipe->alpha_enable = 0; pipe->chroma_sample = MDP4_CHROMA_420; pipe->bpp = 2; /* 2 bpp */ break; case MDP_YCBCR_H1V1: case MDP_YCRCB_H1V1: pipe->frame_format = MDP4_FRAME_FORMAT_LINEAR; pipe->fetch_plane = OVERLAY_PLANE_INTERLEAVED; pipe->a_bit = 0; pipe->r_bit = 3; /* R, 8 bits */ pipe->b_bit = 3; /* B, 8 bits */ pipe->g_bit = 3; /* G, 8 bits */ pipe->alpha_enable = 0; pipe->unpack_tight = 1; pipe->unpack_align_msb = 0; pipe->unpack_count = 2; pipe->element0 = C0_G_Y; /* G */ if (pipe->src_format == MDP_YCRCB_H1V1) { pipe->element1 = C2_R_Cr; /* R */ pipe->element2 = C1_B_Cb; /* B */ } else { pipe->element1 = C1_B_Cb; /* B */ pipe->element2 = C2_R_Cr; /* R */ } pipe->bpp = 3; /* 3 bpp */ case MDP_RGB_BORDERFILL: pipe->alpha_enable = 0; pipe->alpha = 0; break; default: /* not likely */ mdp4_stat.err_format++; return -ERANGE; } return 0; } /* * color_key_convert: output with 12 bits color key */ static uint32 color_key_convert(int start, int num, uint32 color) { uint32 data; data = (color >> start) & ((1 << num) - 1); /* convert to 8 bits */ if (num == 5) data = ((data << 3) | (data >> 2)); else if (num == 6) data = ((data << 2) | (data >> 4)); /* convert 8 bits to 12 bits */ data = (data << 4) | (data >> 4); return data; } void transp_color_key(int format, uint32 transp, uint32 *c0, uint32 *c1, uint32 *c2) { int b_start, g_start, r_start; int b_num, g_num, r_num; switch (format) { case MDP_RGB_565: b_start = 0; g_start = 5; r_start = 11; r_num = 5; g_num = 6; b_num = 5; break; case MDP_RGB_888: case MDP_XRGB_8888: case MDP_ARGB_8888: case MDP_BGRA_8888: b_start = 0; g_start = 8; r_start = 16; r_num = 8; g_num = 8; b_num = 8; break; case MDP_RGBA_8888: case MDP_RGBX_8888: b_start = 16; g_start = 8; r_start = 0; r_num = 8; g_num = 8; b_num = 8; break; case MDP_BGR_565: b_start = 11; g_start = 5; r_start = 0; r_num = 5; g_num = 6; b_num = 5; break; case MDP_Y_CB_CR_H2V2: case MDP_Y_CBCR_H2V2: case MDP_Y_CBCR_H2V1: case MDP_YCBCR_H1V1: b_start = 8; g_start = 16; r_start = 0; r_num = 8; g_num = 8; b_num = 8; break; case MDP_Y_CR_CB_H2V2: case MDP_Y_CR_CB_GH2V2: case MDP_Y_CRCB_H2V2: case MDP_Y_CRCB_H2V1: case MDP_Y_CRCB_H1V2: case MDP_Y_CBCR_H1V2: case MDP_Y_CRCB_H1V1: case MDP_Y_CBCR_H1V1: case MDP_YCRCB_H1V1: b_start = 0; g_start = 16; r_start = 8; r_num = 8; g_num = 8; b_num = 8; break; default: b_start = 0; g_start = 8; r_start = 16; r_num = 8; g_num = 8; b_num = 8; break; } *c0 = color_key_convert(g_start, g_num, transp); *c1 = color_key_convert(b_start, b_num, transp); *c2 = color_key_convert(r_start, r_num, transp); } uint32 mdp4_overlay_format(struct mdp4_overlay_pipe *pipe) { uint32 format; format = 0; if (pipe->solid_fill) format |= MDP4_FORMAT_SOLID_FILL; if (pipe->unpack_align_msb) format |= MDP4_FORMAT_UNPACK_ALIGN_MSB; if (pipe->unpack_tight) format |= MDP4_FORMAT_UNPACK_TIGHT; if (pipe->alpha_enable) format |= MDP4_FORMAT_ALPHA_ENABLE; if (pipe->flags & MDP_SOURCE_ROTATED_90) format |= MDP4_FORMAT_90_ROTATED; format |= (pipe->unpack_count << 13); format |= ((pipe->bpp - 1) << 9); format |= (pipe->a_bit << 6); format |= (pipe->r_bit << 4); format |= (pipe->b_bit << 2); format |= pipe->g_bit; format |= (pipe->frame_format << 29); /* video/graphic */ format |= (pipe->fetch_plane << 19); format |= (pipe->chroma_site << 28); format |= (pipe->chroma_sample << 26); return format; } uint32 mdp4_overlay_unpack_pattern(struct mdp4_overlay_pipe *pipe) { return (pipe->element3 << 24) | (pipe->element2 << 16) | (pipe->element1 << 8) | pipe->element0; } /* * mdp4_overlayproc_cfg: only be called from base layer */ void mdp4_overlayproc_cfg(struct mdp4_overlay_pipe *pipe) { uint32 data, intf; char *overlay_base; uint32 curr; intf = 0; if (pipe->mixer_num == MDP4_MIXER2) overlay_base = MDP_BASE + MDP4_OVERLAYPROC2_BASE; else if (pipe->mixer_num == MDP4_MIXER1) { overlay_base = MDP_BASE + MDP4_OVERLAYPROC1_BASE;/* 0x18000 */ intf = inpdw(MDP_BASE + 0x0038); /* MDP_DISP_INTF_SEL */ intf >>= 4; intf &= 0x03; } else overlay_base = MDP_BASE + MDP4_OVERLAYPROC0_BASE;/* 0x10000 */ if (!in_interrupt()) mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); /* * BLT support both primary and external external */ if (pipe->ov_blt_addr) { int off, bpp; #ifdef BLT_RGB565 bpp = 2; /* overlay ouput is RGB565 */ #else bpp = 3; /* overlay ouput is RGB888 */ #endif data = pipe->src_height; data <<= 16; data |= pipe->src_width; outpdw(overlay_base + 0x0008, data); /* ROI, height + width */ if (pipe->mixer_num == MDP4_MIXER0 || pipe->mixer_num == MDP4_MIXER1) { off = 0; if (pipe->ov_cnt & 0x01) off = pipe->src_height * pipe->src_width * bpp; outpdw(overlay_base + 0x000c, pipe->ov_blt_addr + off); /* overlay ouput is RGB888 */ outpdw(overlay_base + 0x0010, pipe->src_width * bpp); outpdw(overlay_base + 0x001c, pipe->ov_blt_addr + off); /* MDDI - BLT + on demand */ outpdw(overlay_base + 0x0004, 0x08); curr = inpdw(overlay_base + 0x0014); curr &= 0x4; #ifdef BLT_RGB565 outpdw(overlay_base + 0x0014, curr | 0x1); /* RGB565 */ #else outpdw(overlay_base + 0x0014, curr | 0x0); /* RGB888 */ #endif } else if (pipe->mixer_num == MDP4_MIXER2) { if (ctrl->panel_mode & MDP4_PANEL_WRITEBACK) { off = 0; bpp = 1; if (pipe->ov_cnt & 0x01) off = pipe->src_height * pipe->src_width * bpp; outpdw(overlay_base + 0x000c, pipe->ov_blt_addr + off); /* overlay ouput is RGB888 */ outpdw(overlay_base + 0x0010, ((pipe->src_width << 16) | pipe->src_width)); outpdw(overlay_base + 0x001c, pipe->ov_blt_addr + off); off = pipe->src_height * pipe->src_width; /* align chroma to 2k address */ off = (off + 2047) & ~2047; /* UV plane adress */ outpdw(overlay_base + 0x0020, pipe->ov_blt_addr + off); /* MDDI - BLT + on demand */ outpdw(overlay_base + 0x0004, 0x08); /* pseudo planar + writeback */ curr = inpdw(overlay_base + 0x0014); curr &= 0x4; outpdw(overlay_base + 0x0014, curr | 0x012); /* rgb->yuv */ outpdw(overlay_base + 0x0200, 0x05); } } } else { data = pipe->src_height; data <<= 16; data |= pipe->src_width; outpdw(overlay_base + 0x0008, data); /* ROI, height + width */ outpdw(overlay_base + 0x000c, pipe->srcp0_addr); outpdw(overlay_base + 0x0010, pipe->srcp0_ystride); outpdw(overlay_base + 0x0004, 0x01); /* directout */ } if (pipe->mixer_num == MDP4_MIXER1) { if (intf == TV_INTF) { curr = inpdw(overlay_base + 0x0014); curr &= 0x4; outpdw(overlay_base + 0x0014, 0x02); /* yuv422 */ /* overlay1 CSC config */ outpdw(overlay_base + 0x0200, 0x05); /* rgb->yuv */ } } #ifdef MDP4_IGC_LUT_ENABLE curr = inpdw(overlay_base + 0x0014); curr &= ~0x4; outpdw(overlay_base + 0x0014, curr | 0x4); /* GC_LUT_EN, 888 */ #endif if (!in_interrupt()) mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); } int mdp4_overlay_pipe_staged(struct mdp4_overlay_pipe *pipe) { uint32 data, mask; int mixer; mixer = pipe->mixer_num; data = ctrl->mixer_cfg[mixer]; mask = 0x0f; mask <<= (4 * pipe->pipe_num); data &= mask; return data; } int mdp4_mixer_info(int mixer_num, struct mdp_mixer_info *info) { int ndx, cnt; struct mdp4_overlay_pipe *pipe; if (mixer_num > MDP4_MIXER_MAX) return -ENODEV; cnt = 0; ndx = MDP4_MIXER_STAGE_BASE; for ( ; ndx < MDP4_MIXER_STAGE_MAX; ndx++) { pipe = &ctrl->plist[ndx]; if (pipe == NULL) continue; if (!pipe->pipe_used) continue; info->z_order = pipe->mixer_stage - MDP4_MIXER_STAGE0; /* z_order == -1, means base layer */ info->ptype = pipe->pipe_type; info->pnum = pipe->pipe_num; info->pndx = pipe->pipe_ndx; info->mixer_num = pipe->mixer_num; info++; cnt++; } return cnt; } void mdp4_mixer_reset(int mixer) { uint32 data, data1, mask; int i, ndx, min, max, bit; mdp_clk_ctrl(1); /* MDP_LAYERMIXER_IN_CFG, shard by both mixer 0 and 1 */ data = inpdw(MDP_BASE + 0x10100); data1 = data; if (mixer == 0) { min = 1; max = 8; bit = 0x03; /* mixer0, dmap */ } else { min = 9; max = 0xf; bit = 0x0C; /* mixer1, dmae */ } mask = 0x0f; for (i = 0 ; i < 8 ; i++) { ndx = data & mask; ndx >>= (i * 4); if (ndx >= min && ndx <= max) data1 &= ~mask; /* unstage pipe from mixer */ mask <<= 4; } pr_debug("%s: => MIXER_RESET, data1=%x data=%x bit=%x\n", __func__, data1, data, bit); /* unstage pipes of mixer to be reset */ outpdw(MDP_BASE + 0x10100, data1); /* MDP_LAYERMIXER_IN_CFG */ outpdw(MDP_BASE + 0x18000, 0); mdp4_sw_reset(bit); /* reset mixer */ /* 0 => mixer0, dmap */ /* restore origianl stage */ outpdw(MDP_BASE + 0x10100, data); /* MDP_LAYERMIXER_IN_CFG */ outpdw(MDP_BASE + 0x18000, 0); mdp4_vg_csc_restore(); mdp4_overlay_dmap_reconfig(); mdp_clk_ctrl(0); } void mdp4_mixer_stage_commit(int mixer) { struct mdp4_overlay_pipe *pipe; int i, num; u32 data, stage; int off; unsigned long flags; data = 0; for (i = MDP4_MIXER_STAGE_BASE; i < MDP4_MIXER_STAGE_MAX; i++) { pipe = ctrl->stage[mixer][i]; if (pipe == NULL) continue; pr_debug("%s: mixer=%d ndx=%d stage=%d\n", __func__, mixer, pipe->pipe_ndx, i); stage = pipe->mixer_stage; if (mixer >= MDP4_MIXER1) stage += 8; stage <<= (4 * pipe->pipe_num); data |= stage; } /* * stage_commit may be called from overlay_unset * for command panel, mdp clocks may be off at this time. * so mdp clock enabled is necessary */ mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); mdp_clk_ctrl(1); if (data) mdp4_mixer_blend_setup(mixer); off = 0; if (data != ctrl->mixer_cfg[mixer]) { ctrl->mixer_cfg[mixer] = data; if (mixer >= MDP4_MIXER2) { /* MDP_LAYERMIXER2_IN_CFG */ off = 0x100f0; } else { /* mixer 0 or 1 */ num = mixer + 1; num &= 0x01; data |= ctrl->mixer_cfg[num]; off = 0x10100; } pr_debug("%s: mixer=%d data=%x flush=%x pid=%d\n", __func__, mixer, data, ctrl->flush[mixer], current->pid); } local_irq_save(flags); if (off) outpdw(MDP_BASE + off, data); if (ctrl->flush[mixer]) { outpdw(MDP_BASE + 0x18000, ctrl->flush[mixer]); ctrl->flush[mixer] = 0; } local_irq_restore(flags); mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); mdp_clk_ctrl(0); } void mdp4_mixer_stage_up(struct mdp4_overlay_pipe *pipe, int commit) { struct mdp4_overlay_pipe *pp; int i, mixer; mixer = pipe->mixer_num; for (i = MDP4_MIXER_STAGE_BASE; i < MDP4_MIXER_STAGE_MAX; i++) { pp = ctrl->stage[mixer][i]; if (pp && pp->pipe_ndx == pipe->pipe_ndx) { ctrl->stage[mixer][i] = NULL; break; } } ctrl->stage[mixer][pipe->mixer_stage] = pipe; /* keep it */ if (commit) mdp4_mixer_stage_commit(mixer); } void mdp4_mixer_stage_down(struct mdp4_overlay_pipe *pipe, int commit) { struct mdp4_overlay_pipe *pp; int i, mixer; mixer = pipe->mixer_num; for (i = MDP4_MIXER_STAGE_BASE; i < MDP4_MIXER_STAGE_MAX; i++) { pp = ctrl->stage[mixer][i]; if (pp && pp->pipe_ndx == pipe->pipe_ndx) ctrl->stage[mixer][i] = NULL; /* clear it */ } if (commit) mdp4_mixer_stage_commit(mixer); } /* * mixer0: rgb3: border color at register 0x15004, 0x15008 * mixer1: vg3: border color at register 0x1D004, 0x1D008 * mixer2: xxx: border color at register 0x8D004, 0x8D008 */ void mdp4_overlay_borderfill_stage_up(struct mdp4_overlay_pipe *pipe) { struct mdp4_overlay_pipe *bspipe; int ptype, pnum, pndx, mixer; int format, alpha_enable, alpha; struct mdp4_iommu_pipe_info iom; if (pipe->pipe_type != OVERLAY_TYPE_BF) return; mixer = pipe->mixer_num; if (ctrl->baselayer[mixer]) return; bspipe = ctrl->stage[mixer][MDP4_MIXER_STAGE_BASE]; if (bspipe == NULL) { pr_err("%s: no base layer at mixer=%d\n", __func__, mixer); return; } /* * bspipe is clone here * get real pipe */ bspipe = mdp4_overlay_ndx2pipe(bspipe->pipe_ndx); if (bspipe == NULL) { pr_err("%s: mdp4_overlay_ndx2pipe returned null pipe ndx\n", __func__); return; } /* save original base layer */ ctrl->baselayer[mixer] = bspipe; iom = pipe->iommu; pipe->alpha = 0; /* make sure bf pipe has alpha 0 */ ptype = pipe->pipe_type; pnum = pipe->pipe_num; pndx = pipe->pipe_ndx; format = pipe->src_format; alpha_enable = pipe->alpha_enable; alpha = pipe->alpha; *pipe = *bspipe; /* keep base layer configuration */ pipe->pipe_type = ptype; pipe->pipe_num = pnum; pipe->pipe_ndx = pndx; pipe->src_format = format; pipe->alpha_enable = alpha_enable; pipe->alpha = alpha; pipe->iommu = iom; /* free original base layer pipe to be sued as normal pipe */ bspipe->pipe_used = 0; if (ctrl->panel_mode & MDP4_PANEL_DSI_VIDEO) mdp4_dsi_video_base_swap(0, pipe); else if (ctrl->panel_mode & MDP4_PANEL_DSI_CMD) mdp4_dsi_cmd_base_swap(0, pipe); else if (ctrl->panel_mode & MDP4_PANEL_LCDC) mdp4_lcdc_base_swap(0, pipe); else if (ctrl->panel_mode & MDP4_PANEL_DTV) mdp4_dtv_base_swap(0, pipe); mdp4_overlay_reg_flush(bspipe, 1); /* borderfill pipe as base layer */ mdp4_mixer_stage_up(pipe, 0); } void mdp4_overlay_borderfill_stage_down(struct mdp4_overlay_pipe *pipe) { struct mdp4_overlay_pipe *bspipe; int ptype, pnum, pndx, mixer; int format, alpha_enable, alpha; struct mdp4_iommu_pipe_info iom; if (pipe->pipe_type != OVERLAY_TYPE_BF) return; mixer = pipe->mixer_num; /* retrieve original base layer */ bspipe = ctrl->baselayer[mixer]; if (bspipe == NULL) { pr_err("%s: no base layer at mixer=%d\n", __func__, mixer); return; } iom = bspipe->iommu; ptype = bspipe->pipe_type; pnum = bspipe->pipe_num; pndx = bspipe->pipe_ndx; format = bspipe->src_format; alpha_enable = bspipe->alpha_enable; alpha = bspipe->alpha; *bspipe = *pipe; /* restore base layer configuration */ bspipe->pipe_type = ptype; bspipe->pipe_num = pnum; bspipe->pipe_ndx = pndx; bspipe->src_format = format; bspipe->alpha_enable = alpha_enable; bspipe->alpha = alpha; bspipe->iommu = iom; bspipe->pipe_used++; /* mark base layer pipe used */ ctrl->baselayer[mixer] = NULL; /* free borderfill pipe */ pipe->pipe_used = 0; if (ctrl->panel_mode & MDP4_PANEL_DSI_VIDEO) mdp4_dsi_video_base_swap(0, bspipe); else if (ctrl->panel_mode & MDP4_PANEL_DSI_CMD) mdp4_dsi_cmd_base_swap(0, bspipe); else if (ctrl->panel_mode & MDP4_PANEL_LCDC) mdp4_lcdc_base_swap(0, bspipe); else if (ctrl->panel_mode & MDP4_PANEL_DTV) mdp4_dtv_base_swap(0, bspipe); /* free borderfill pipe */ mdp4_overlay_reg_flush(pipe, 1); mdp4_mixer_stage_down(pipe, 0); /* commit will happen for bspipe up */ mdp4_overlay_pipe_free(pipe, 0); /* stage up base layer */ mdp4_overlay_reg_flush(bspipe, 1); /* restore original base layer */ mdp4_mixer_stage_up(bspipe, 1); } static struct mdp4_overlay_pipe *mdp4_background_layer(int mixer, struct mdp4_overlay_pipe *sp) { struct mdp4_overlay_pipe *pp; struct mdp4_overlay_pipe *kp; int i; kp = ctrl->stage[mixer][MDP4_MIXER_STAGE_BASE]; for (i = MDP4_MIXER_STAGE_BASE; i < MDP4_MIXER_STAGE_MAX; i++) { pp = ctrl->stage[mixer][i]; if (pp == NULL) continue; if (pp == sp) break; if ((pp->dst_x <= sp->dst_x) && ((pp->dst_x + pp->dst_w) >= (sp->dst_x + sp->dst_w))) { if ((pp->dst_y <= sp->dst_y) && ((pp->dst_y + pp->dst_h) >= (sp->dst_y + sp->dst_h))) { kp = pp; } } } return kp; } static void mdp4_overlay_bg_solidfill(struct blend_cfg *blend) { struct mdp4_overlay_pipe *pipe; char *base; u32 op_mode, format; int pnum, ptype; pipe = blend->solidfill_pipe; if (pipe == NULL) return; if (pipe->pipe_type == OVERLAY_TYPE_BF) return; ptype = mdp4_overlay_format2type(pipe->src_format); if (ptype == OVERLAY_TYPE_RGB) { pnum = pipe->pipe_num - OVERLAY_PIPE_RGB1; base = MDP_BASE + MDP4_RGB_BASE; base += MDP4_RGB_OFF * pnum; } else { pnum = pipe->pipe_num - OVERLAY_PIPE_VG1; base = MDP_BASE + MDP4_VIDEO_BASE; base += MDP4_VIDEO_OFF * pnum; } format = inpdw(base + 0x50); if (blend->solidfill) { format |= MDP4_FORMAT_SOLID_FILL; /* * If solid fill is enabled, flip and scale * have to be disabled. otherwise, h/w * underruns. */ op_mode = inpdw(base + 0x0058); op_mode &= ~(MDP4_OP_FLIP_LR + MDP4_OP_SCALEX_EN); op_mode &= ~(MDP4_OP_FLIP_UD + MDP4_OP_SCALEY_EN); outpdw(base + 0x0058, op_mode); outpdw(base + 0x1008, 0); /* black */ /* * Set src size and dst size same to avoid underruns */ outpdw(base + 0x0000, inpdw(base + 0x0008)); } else { u32 src_size = ((pipe->src_h << 16) | pipe->src_w); outpdw(base + 0x0000, src_size); format &= ~MDP4_FORMAT_SOLID_FILL; blend->solidfill_pipe = NULL; } outpdw(base + 0x50, format); mdp4_overlay_reg_flush(pipe, 0); } void mdp4_mixer_blend_cfg(int mixer) { int i, off; unsigned char *overlay_base; struct blend_cfg *blend; if (mixer == MDP4_MIXER2) overlay_base = MDP_BASE + MDP4_OVERLAYPROC2_BASE; else if (mixer == MDP4_MIXER1) overlay_base = MDP_BASE + MDP4_OVERLAYPROC1_BASE; else overlay_base = MDP_BASE + MDP4_OVERLAYPROC0_BASE; blend = &ctrl->blend[mixer][MDP4_MIXER_STAGE_BASE]; blend++; /* stage0 */ for (i = MDP4_MIXER_STAGE0; i < MDP4_MIXER_STAGE_MAX; i++) { off = 20 * i; off = 0x20 * (i - MDP4_MIXER_STAGE0); if (i == MDP4_MIXER_STAGE3) off -= 4; outpdw(overlay_base + off + 0x104, blend->op); blend++; } } static void mdp4_set_blend_by_op(struct mdp4_overlay_pipe *s_pipe, struct mdp4_overlay_pipe *d_pipe, int alpha_drop, struct blend_cfg *blend) { int d_alpha, s_alpha; u32 op; d_alpha = d_pipe->alpha_enable; s_alpha = s_pipe->alpha_enable; /* base on fg's alpha */ blend->fg_alpha = s_pipe->alpha; blend->bg_alpha = 0x0ff - s_pipe->alpha; blend->op = MDP4_BLEND_FG_ALPHA_FG_CONST | MDP4_BLEND_BG_ALPHA_BG_CONST; blend->co3_sel = 1; /* use fg alpha */ op = s_pipe->blend_op; if (op == BLEND_OP_OPAQUE) { blend->bg_alpha = 0; blend->fg_alpha = 0xff; } else if ((op == BLEND_OP_PREMULTIPLIED) && (!alpha_drop) && s_alpha) { blend->op = MDP4_BLEND_FG_ALPHA_FG_CONST | MDP4_BLEND_BG_INV_ALPHA | MDP4_BLEND_BG_ALPHA_FG_PIXEL; if (blend->fg_alpha != 0xff) { blend->bg_alpha = blend->fg_alpha; blend->op |= MDP4_BLEND_BG_MOD_ALPHA; } } else if (!alpha_drop && s_alpha) { blend->op = MDP4_BLEND_FG_ALPHA_FG_PIXEL | MDP4_BLEND_BG_INV_ALPHA | MDP4_BLEND_BG_ALPHA_FG_PIXEL; if (blend->fg_alpha != 0xff) { blend->bg_alpha = blend->fg_alpha; blend->op |= MDP4_BLEND_FG_MOD_ALPHA | MDP4_BLEND_BG_MOD_ALPHA; } } if (!s_alpha && d_alpha) blend->co3_sel = 0; pr_debug("%s: op %d bg alpha %d, fg alpha %d blend: %x\n", __func__, op, blend->bg_alpha, blend->fg_alpha, blend->op); } static void mdp4_set_blend_by_fmt(struct mdp4_overlay_pipe *s_pipe, struct mdp4_overlay_pipe *d_pipe, int alpha_drop, struct blend_cfg *blend) { int ptype, d_alpha, s_alpha; d_alpha = d_pipe->alpha_enable; s_alpha = s_pipe->alpha_enable; /* base on fg's alpha */ blend->bg_alpha = 0x0ff - s_pipe->alpha; blend->fg_alpha = s_pipe->alpha; blend->co3_sel = 1; /* use fg alpha */ if (s_pipe->is_fg) { if (s_pipe->alpha == 0xff) { blend->solidfill = 1; blend->solidfill_pipe = d_pipe; } } else if (s_alpha) { if (!alpha_drop) { blend->op = MDP4_BLEND_BG_ALPHA_FG_PIXEL; if (!(s_pipe->flags & MDP_BLEND_FG_PREMULT)) blend->op |= MDP4_BLEND_FG_ALPHA_FG_PIXEL; } else blend->op = MDP4_BLEND_BG_ALPHA_FG_CONST; blend->op |= MDP4_BLEND_BG_INV_ALPHA; } else if (d_alpha) { ptype = mdp4_overlay_format2type(s_pipe->src_format); if (ptype == OVERLAY_TYPE_VIDEO && (!(s_pipe->flags & MDP_BACKEND_COMPOSITION))) { blend->op = (MDP4_BLEND_FG_ALPHA_BG_PIXEL | MDP4_BLEND_FG_INV_ALPHA); if (!(s_pipe->flags & MDP_BLEND_FG_PREMULT)) blend->op |= MDP4_BLEND_BG_ALPHA_BG_PIXEL; blend->co3_sel = 0; /* use bg alpha */ } else { /* s_pipe is rgb without alpha */ blend->op = (MDP4_BLEND_FG_ALPHA_FG_CONST | MDP4_BLEND_BG_ALPHA_BG_CONST); blend->bg_alpha = 0; } } } /* * D(i+1) = Ks * S + Kd * D(i) */ void mdp4_mixer_blend_setup(int mixer) { struct mdp4_overlay_pipe *d_pipe; struct mdp4_overlay_pipe *s_pipe; struct blend_cfg *blend; int i, off, alpha_drop; unsigned char *overlay_base; uint32 c0, c1, c2; d_pipe = ctrl->stage[mixer][MDP4_MIXER_STAGE_BASE]; if (d_pipe == NULL) { pr_err("%s: Error: no bg_pipe at mixer=%d\n", __func__, mixer); return; } blend = &ctrl->blend[mixer][MDP4_MIXER_STAGE0]; for (i = MDP4_MIXER_STAGE0; i < MDP4_MIXER_STAGE_MAX; i++) { blend->solidfill = 0; blend->op = (MDP4_BLEND_FG_ALPHA_FG_CONST | MDP4_BLEND_BG_ALPHA_BG_CONST); s_pipe = ctrl->stage[mixer][i]; if (s_pipe == NULL) { blend++; d_pipe = NULL; continue; } alpha_drop = 0; /* per stage */ /* alpha channel is lost on VG pipe when using QSEED or M/N */ if (s_pipe->pipe_type == OVERLAY_TYPE_VIDEO && s_pipe->alpha_enable && ((s_pipe->op_mode & MDP4_OP_SCALEY_EN) || (s_pipe->op_mode & MDP4_OP_SCALEX_EN)) && !(s_pipe->op_mode & (MDP4_OP_SCALEX_PIXEL_RPT | MDP4_OP_SCALEY_PIXEL_RPT))) alpha_drop = 1; d_pipe = mdp4_background_layer(mixer, s_pipe); pr_debug("%s: stage=%d: bg: ndx=%d da=%d dalpha=%x " "fg: ndx=%d sa=%d salpha=%x is_fg=%d alpha_drop=%d\n", __func__, i-2, d_pipe->pipe_ndx, d_pipe->alpha_enable, d_pipe->alpha, s_pipe->pipe_ndx, s_pipe->alpha_enable, s_pipe->alpha, s_pipe->is_fg, alpha_drop); if ((s_pipe->blend_op == BLEND_OP_NOT_DEFINED) || (s_pipe->blend_op >= BLEND_OP_MAX)) mdp4_set_blend_by_fmt(s_pipe, d_pipe, alpha_drop, blend); else mdp4_set_blend_by_op(s_pipe, d_pipe, alpha_drop, blend); if (s_pipe->transp != MDP_TRANSP_NOP) { if (s_pipe->is_fg) { transp_color_key(s_pipe->src_format, s_pipe->transp, &c0, &c1, &c2); /* Fg blocked */ blend->op |= MDP4_BLEND_FG_TRANSP_EN; /* lower limit */ blend->transp_low0 = (c1 << 16 | c0); blend->transp_low1 = c2; /* upper limit */ blend->transp_high0 = (c1 << 16 | c0); blend->transp_high1 = c2; } else { transp_color_key(d_pipe->src_format, s_pipe->transp, &c0, &c1, &c2); /* Fg blocked */ blend->op |= MDP4_BLEND_BG_TRANSP_EN; blend--; /* one stage back */ /* lower limit */ blend->transp_low0 = (c1 << 16 | c0); blend->transp_low1 = c2; /* upper limit */ blend->transp_high0 = (c1 << 16 | c0); blend->transp_high1 = c2; blend++; /* back to original stage */ } } blend++; } /* mixer numer, /dev/fb0, /dev/fb1, /dev/fb2 */ if (mixer == MDP4_MIXER2) overlay_base = MDP_BASE + MDP4_OVERLAYPROC2_BASE;/* 0x88000 */ else if (mixer == MDP4_MIXER1) overlay_base = MDP_BASE + MDP4_OVERLAYPROC1_BASE;/* 0x18000 */ else overlay_base = MDP_BASE + MDP4_OVERLAYPROC0_BASE;/* 0x10000 */ mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); blend = &ctrl->blend[mixer][MDP4_MIXER_STAGE_BASE]; /* lower limit */ outpdw(overlay_base + 0x180, blend->transp_low0); outpdw(overlay_base + 0x184, blend->transp_low1); /* upper limit */ outpdw(overlay_base + 0x188, blend->transp_high0); outpdw(overlay_base + 0x18c, blend->transp_high1); blend++; /* stage0 */ for (i = MDP4_MIXER_STAGE0; i < MDP4_MIXER_STAGE_MAX; i++) { off = 20 * i; off = 0x20 * (i - MDP4_MIXER_STAGE0); if (i == MDP4_MIXER_STAGE3) off -= 4; if (blend->solidfill_pipe) mdp4_overlay_bg_solidfill(blend); outpdw(overlay_base + off + 0x108, blend->fg_alpha); outpdw(overlay_base + off + 0x10c, blend->bg_alpha); if (mdp_rev >= MDP_REV_42) outpdw(overlay_base + off + 0x104, blend->op); outpdw(overlay_base + (off << 5) + 0x1004, blend->co3_sel); outpdw(overlay_base + off + 0x110, blend->transp_low0);/* low */ outpdw(overlay_base + off + 0x114, blend->transp_low1);/* low */ /* upper limit */ outpdw(overlay_base + off + 0x118, blend->transp_high0); outpdw(overlay_base + off + 0x11c, blend->transp_high1); blend++; } mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); } void mdp4_overlay_reg_flush(struct mdp4_overlay_pipe *pipe, int all) { int mixer; uint32 *reg; mixer = pipe->mixer_num; reg = &ctrl->flush[mixer]; *reg |= (1 << (2 + pipe->pipe_num)); if (all) { if (mixer == MDP4_MIXER0) *reg |= 0x01; else *reg |= 0x02; } } void mdp4_overlay_flush_piggyback(int m0, int m1) { u32 data; data = ctrl->flush[m0] | ctrl->flush[m1]; ctrl->flush[m0] = data; } void mdp4_overlay_reg_flush_reset(struct mdp4_overlay_pipe *pipe) { int mixer; mixer = pipe->mixer_num; ctrl->flush[mixer] = 0; } struct mdp4_overlay_pipe *mdp4_overlay_stage_pipe(int mixer, int stage) { return ctrl->stage[mixer][stage]; } struct mdp4_overlay_pipe *mdp4_overlay_ndx2pipe(int ndx) { struct mdp4_overlay_pipe *pipe; if (ndx <= 0 || ndx > OVERLAY_PIPE_MAX) return NULL; pipe = &ctrl->plist[ndx - 1]; /* ndx start from 1 */ if (pipe->pipe_used == 0) return NULL; return pipe; } struct mdp4_overlay_pipe *mdp4_overlay_pipe_alloc(int ptype, int mixer) { int i; struct mdp4_overlay_pipe *pipe; if (ptype == OVERLAY_TYPE_BF) { if (!mdp4_overlay_borderfill_supported()) return NULL; } for (i = 0; i < OVERLAY_PIPE_MAX; i++) { pipe = &ctrl->plist[i]; if (pipe->pipe_type == ptype || (ptype == OVERLAY_TYPE_RGB && pipe->pipe_type == OVERLAY_TYPE_VIDEO)) { if ((ptype == OVERLAY_TYPE_BF && mixer != pipe->mixer_num) || (ptype != OVERLAY_TYPE_BF && pipe->pipe_used != 0)) { continue; } else if (ptype == OVERLAY_TYPE_BF) { //borderfill pipe mdp4_overlay_borderfill_stage_down(pipe); } init_completion(&pipe->comp); init_completion(&pipe->dmas_comp); pr_debug("%s: pipe=%x ndx=%d num=%d\n", __func__, (int)pipe, pipe->pipe_ndx, pipe->pipe_num); return pipe; } } pr_err("%s: ptype=%d FAILED\n", __func__, ptype); return NULL; } void mdp4_overlay_pipe_free(struct mdp4_overlay_pipe *pipe, int all) { uint32 ptype, num, ndx, mixer; struct mdp4_iommu_pipe_info iom; struct mdp4_overlay_pipe *orgpipe; pr_debug("%s: pipe=%x ndx=%d\n", __func__, (int)pipe, pipe->pipe_ndx); ptype = pipe->pipe_type; num = pipe->pipe_num; ndx = pipe->pipe_ndx; mixer = pipe->mixer_num; /* No need for borderfill pipe */ if (pipe->pipe_type != OVERLAY_TYPE_BF) mdp4_overlay_iommu_pipe_free(pipe->pipe_ndx, all); iom = pipe->iommu; memset(pipe, 0, sizeof(*pipe)); pipe->pipe_type = ptype; pipe->pipe_num = num; pipe->pipe_ndx = ndx; pipe->mixer_num = mixer; pipe->iommu = iom; /*Clear real pipe attributes as well */ orgpipe = mdp4_overlay_ndx2pipe(pipe->pipe_ndx); if (orgpipe != NULL) orgpipe->pipe_used = 0; } static int mdp4_overlay_req2pipe(struct mdp_overlay *req, int mixer, struct mdp4_overlay_pipe **ppipe, struct msm_fb_data_type *mfd) { struct mdp4_overlay_pipe *pipe; int ret, ptype; u32 upscale_max; upscale_max = (mdp_rev >= MDP_REV_41) ? MDP4_REV41_OR_LATER_UP_SCALING_MAX : MDP4_REV40_UP_SCALING_MAX; if (mfd == NULL) { pr_err("%s: mfd == NULL, -ENODEV\n", __func__); return -ENODEV; } if (mixer >= MDP4_MIXER_MAX) { pr_err("%s: mixer out of range!\n", __func__); mdp4_stat.err_mixer++; return -ERANGE; } if (req->z_order < 0 || req->z_order > 3) { pr_err("%s: z_order=%d out of range!\n", __func__, req->z_order); mdp4_stat.err_zorder++; return -ERANGE; } if (req->src_rect.h > 0xFFF || req->src_rect.h < 2) { pr_err("%s: src_h is out of range: 0X%x!\n", __func__, req->src_rect.h); mdp4_stat.err_size++; return -EINVAL; } if (req->src_rect.w > 0xFFF || req->src_rect.w < 2) { pr_err("%s: src_w is out of range: 0X%x!\n", __func__, req->src_rect.w); mdp4_stat.err_size++; return -EINVAL; } if (req->src_rect.x > 0xFFF) { pr_err("%s: src_x is out of range: 0X%x!\n", __func__, req->src_rect.x); mdp4_stat.err_size++; return -EINVAL; } if (req->src_rect.y > 0xFFF) { pr_err("%s: src_y is out of range: 0X%x!\n", __func__, req->src_rect.y); mdp4_stat.err_size++; return -EINVAL; } if (req->dst_rect.h > 0xFFF || req->dst_rect.h < 2) { pr_err("%s: dst_h is out of range: 0X%x!\n", __func__, req->dst_rect.h); mdp4_stat.err_size++; return -EINVAL; } if (req->dst_rect.w > 0xFFF || req->dst_rect.w < 2) { pr_err("%s: dst_w is out of range: 0X%x!\n", __func__, req->dst_rect.w); mdp4_stat.err_size++; return -EINVAL; } if (req->dst_rect.x > 0xFFF) { pr_err("%s: dst_x is out of range: 0X%x!\n", __func__, req->dst_rect.x); mdp4_stat.err_size++; return -EINVAL; } if (req->dst_rect.y > 0xFFF) { pr_err("%s: dst_y is out of range: 0X%x!\n", __func__, req->dst_rect.y); mdp4_stat.err_size++; return -EINVAL; } if (req->src_rect.h == 0 || req->src_rect.w == 0) { pr_err("%s: src img of zero size!\n", __func__); mdp4_stat.err_size++; return -EINVAL; } if (req->dst_rect.h > (req->src_rect.h * upscale_max)) { mdp4_stat.err_scale++; pr_err("%s: scale up, too much (h)!\n", __func__); return -ERANGE; } if (req->src_rect.h > (req->dst_rect.h * 8)) { /* too little */ mdp4_stat.err_scale++; pr_err("%s: scale down, too little (h)!\n", __func__); return -ERANGE; } if (req->dst_rect.w > (req->src_rect.w * upscale_max)) { mdp4_stat.err_scale++; pr_err("%s: scale up, too much (w)!\n", __func__); return -ERANGE; } if (req->src_rect.w > (req->dst_rect.w * 8)) { /* too little */ mdp4_stat.err_scale++; pr_err("%s: scale down, too little (w)!\n", __func__); return -ERANGE; } if (mdp_hw_revision == MDP4_REVISION_V1) { /* non integer down saceling ratio smaller than 1/4 * is not supportted */ if (req->src_rect.h > (req->dst_rect.h * 4)) { if (req->src_rect.h % req->dst_rect.h) { mdp4_stat.err_scale++; pr_err("%s: need integer (h)!\n", __func__); return -ERANGE; } } if (req->src_rect.w > (req->dst_rect.w * 4)) { if (req->src_rect.w % req->dst_rect.w) { mdp4_stat.err_scale++; pr_err("%s: need integer (w)!\n", __func__); return -ERANGE; } } } if (((req->src_rect.x + req->src_rect.w) > req->src.width) || ((req->src_rect.y + req->src_rect.h) > req->src.height)) { mdp4_stat.err_size++; pr_err("%s invalid src rectangle\n", __func__); return -ERANGE; } if (ctrl->panel_3d != MDP4_3D_SIDE_BY_SIDE) { int xres; int yres; xres = mfd->panel_info.xres; yres = mfd->panel_info.yres; if (((req->dst_rect.x + req->dst_rect.w) > xres) || ((req->dst_rect.y + req->dst_rect.h) > yres)) { mdp4_stat.err_size++; pr_err("%s invalid dst rectangle (%dx%d) vs (%dx%d)\n", __func__,(req->dst_rect.x + req->dst_rect.w),(req->dst_rect.y + req->dst_rect.h),xres,yres); return -ERANGE; } } ptype = mdp4_overlay_format2type(req->src.format); if (ptype < 0) { pr_err("%s: mdp4_overlay_format2type!\n", __func__); return ptype; } if (req->flags & MDP_OV_PIPE_SHARE) ptype = OVERLAY_TYPE_VIDEO; /* VG pipe supports both RGB+YUV */ if (req->id == MSMFB_NEW_REQUEST) /* new request */ pipe = mdp4_overlay_pipe_alloc(ptype, mixer); else pipe = mdp4_overlay_ndx2pipe(req->id); if (pipe == NULL) { pr_err("%s: pipe == NULL!\n", __func__); return -ENOMEM; } #if defined(CONFIG_FB_MSM_MIPI_LGIT_VIDEO_FHD_INVERSE_PT) pipe->mfd = mfd; #endif if (!display_iclient && !IS_ERR_OR_NULL(mfd->iclient)) { display_iclient = mfd->iclient; pr_debug("%s(): display_iclient %p\n", __func__, display_iclient); } pipe->src_format = req->src.format; ret = mdp4_overlay_format2pipe(pipe); if (ret < 0) { pr_err("%s: mdp4_overlay_format2pipe!\n", __func__); return ret; } /* * base layer == 1, reserved for frame buffer * zorder 0 == stage 0 == 2 * zorder 1 == stage 1 == 3 * zorder 2 == stage 2 == 4 */ if (req->id == MSMFB_NEW_REQUEST) { /* new request */ if (mdp4_overlay_pipe_staged(pipe)) { pr_err("%s: ndx=%d still staged\n", __func__, pipe->pipe_ndx); return -EPERM; } pipe->pipe_used++; pipe->mixer_num = mixer; pr_debug("%s: zorder=%d pipe ndx=%d num=%d\n", __func__, req->z_order, pipe->pipe_ndx, pipe->pipe_num); } pipe->mixer_stage = req->z_order + MDP4_MIXER_STAGE0; pipe->src_width = req->src.width & 0x1fff; /* source img width */ pipe->src_height = req->src.height & 0x1fff; /* source img height */ pipe->src_h = req->src_rect.h & 0x07ff; pipe->src_w = req->src_rect.w & 0x07ff; pipe->src_y = req->src_rect.y & 0x07ff; pipe->src_x = req->src_rect.x & 0x07ff; pipe->dst_h = req->dst_rect.h & 0x07ff; pipe->dst_w = req->dst_rect.w & 0x07ff; pipe->dst_y = req->dst_rect.y & 0x07ff; pipe->dst_x = req->dst_rect.x & 0x07ff; pipe->op_mode = 0; #if defined(CONFIG_FB_MSM_MIPI_LGIT_VIDEO_FHD_INVERSE_PT) pipe->ext_flag = req->flags; #endif if (req->flags & MDP_FLIP_LR) pipe->op_mode |= MDP4_OP_FLIP_LR; if (req->flags & MDP_FLIP_UD) pipe->op_mode |= MDP4_OP_FLIP_UD; if (req->flags & MDP_DITHER) pipe->op_mode |= MDP4_OP_DITHER_EN; if (req->flags & MDP_DEINTERLACE) pipe->op_mode |= MDP4_OP_DEINT_EN; if (req->flags & MDP_DEINTERLACE_ODD) pipe->op_mode |= MDP4_OP_DEINT_ODD_REF; pipe->is_fg = req->is_fg;/* control alpha and color key */ pipe->alpha = req->alpha & 0x0ff; pipe->blend_op = req->blend_op; pipe->transp = req->transp_mask; pipe->flags = req->flags; *ppipe = pipe; return 0; } static int mdp4_calc_pipe_mdp_clk(struct msm_fb_data_type *mfd, struct mdp4_overlay_pipe *pipe) { u32 pclk; u32 xscale, yscale; u32 hsync = 0; u32 shift = 16; u64 rst; int ptype; int ret = -EINVAL; if (!pipe) { pr_err("%s: pipe is null!\n", __func__); return ret; } if (!mfd) { pr_err("%s: mfd is null!\n", __func__); return ret; } pr_debug("%s: pipe sets: panel res(x,y)=(%d,%d)\n", __func__, mfd->panel_info.xres, mfd->panel_info.yres); pr_debug("%s: src(w,h)(%d,%d),src(x,y)(%d,%d)\n", __func__, pipe->src_w, pipe->src_h, pipe->src_x, pipe->src_y); pr_debug("%s: dst(w,h)(%d,%d),dst(x,y)(%d,%d)\n", __func__, pipe->dst_w, pipe->dst_h, pipe->dst_x, pipe->dst_y); pclk = (mfd->panel_info.type == MIPI_VIDEO_PANEL || mfd->panel_info.type == MIPI_CMD_PANEL) ? mfd->panel_info.mipi.dsi_pclk_rate : mfd->panel_info.clk_rate; if (mfd->panel_info.type == LVDS_PANEL && mfd->panel_info.lvds.channel_mode == LVDS_DUAL_CHANNEL_MODE) pclk = pclk << 1; if (!pclk) { pipe->req_clk = mdp_max_clk; pr_err("%s panel pixel clk is zero!\n", __func__); return ret; } pr_debug("%s: mdp panel pixel clk is %d.\n", __func__, pclk); if (!pipe->dst_h) { pr_err("%s: pipe dst_h is zero!\n", __func__); pipe->req_clk = mdp_max_clk; return ret; } if (!pipe->src_h) { pr_err("%s: pipe src_h is zero!\n", __func__); pipe->req_clk = mdp_max_clk; return ret; } if (!pipe->dst_w) { pr_err("%s: pipe dst_w is zero!\n", __func__); pipe->req_clk = mdp_max_clk; return ret; } if (!pipe->dst_h) { pr_err("%s: pipe dst_h is zero!\n", __func__); pipe->req_clk = mdp_max_clk; return ret; } if (pipe->mixer_num == MDP4_MIXER0) { if (pipe->blt_forced) return 0; ptype = mdp4_overlay_format2type(pipe->src_format); if (ptype == OVERLAY_TYPE_VIDEO) { if ((pipe->src_h >= 720) && (pipe->src_w >= 1080)) { pipe->req_clk = (u32) mdp_max_clk + 100; pipe->blt_forced++; return 0; } else if ((pipe->src_h >= 1080) && (pipe->src_w >= 720)) { pipe->req_clk = (u32) mdp_max_clk + 100; pipe->blt_forced++; return 0; } } } /* * For the scaling cases, make more margin by removing porch * values and adding extra 20%. */ if ((pipe->src_h != pipe->dst_h) || (pipe->src_w != pipe->dst_w)) { hsync = mfd->panel_info.xres; hsync *= 100; hsync /= 120; pr_debug("%s: panel hsync is %d. with scaling\n", __func__, hsync); } else { hsync = mfd->panel_info.lcdc.h_back_porch + mfd->panel_info.lcdc.h_front_porch + mfd->panel_info.lcdc.h_pulse_width + mfd->panel_info.xres; pr_debug("%s: panel hsync is %d.\n", __func__, hsync); } if (!hsync) { pipe->req_clk = mdp_max_clk; pr_err("%s: panel hsync is zero!\n", __func__); return 0; } xscale = mfd->panel_info.xres; xscale += pipe->src_w; if (xscale < pipe->dst_w) { pipe->req_clk = mdp_max_clk; pr_err("%s: xres+src_w cannot be less than dst_w!\n", __func__); return ret; } xscale -= pipe->dst_w; xscale <<= shift; xscale /= hsync; pr_debug("%s: the right %d shifted xscale is %d.\n", __func__, shift, xscale); if (pipe->src_h > pipe->dst_h) { yscale = pipe->src_h; yscale <<= shift; yscale /= pipe->dst_h; } else { /* upscale */ yscale = pipe->dst_h; yscale <<= shift; yscale /= pipe->src_h; } yscale *= pipe->src_w; yscale /= hsync; pr_debug("%s: the right %d shifted yscale is %d.\n", __func__, shift, yscale); rst = pclk; if (yscale > xscale) rst *= yscale; else rst *= xscale; rst >>= shift; /* * There is one special case for the panels that have low * v_back_porch (<=4), mdp clk should be fast enough to buffer * 4 lines input during back porch time if scaling is * required(FIR). */ if ((mfd->panel_info.lcdc.v_back_porch <= 4) && (pipe->src_h != pipe->dst_h) && (mfd->panel_info.lcdc.v_back_porch)) { u32 clk = 0; clk = 4 * (pclk >> shift) / mfd->panel_info.lcdc.v_back_porch; clk <<= shift; pr_debug("%s: mdp clk rate %d based on low vbp %d\n", __func__, clk, mfd->panel_info.lcdc.v_back_porch); rst = (rst > clk) ? rst : clk; } /* * If the calculated mdp clk is less than panel pixel clk, * most likely due to upscaling, mdp clk rate will be set to * greater than pclk. Now the driver uses 1.15 as the * factor. Ideally this factor is passed from board file. */ if (rst < pclk) { rst = ((pclk >> shift) * 23 / 20) << shift; pr_debug("%s calculated mdp clk is less than pclk.\n", __func__); } /* * Interlaced videos require the max mdp clk but cannot * be explained by mdp clk equation. */ if (pipe->flags & MDP_DEINTERLACE) { rst = (rst > mdp_max_clk) ? rst : mdp_max_clk; pr_info("%s deinterlace requires max mdp clk.\n", __func__); } pipe->req_clk = (u32) rst; pr_debug("%s: required mdp clk %d mixer %d pipe ndx %d\n", __func__, pipe->req_clk, pipe->mixer_num, pipe->pipe_ndx); return 0; } static int mdp4_calc_pipe_mdp_bw(struct msm_fb_data_type *mfd, struct mdp4_overlay_pipe *pipe) { u32 fps; int ret = -EINVAL; u32 quota; u32 shift = 16; if (!pipe) { pr_err("%s: pipe is null!\n", __func__); return ret; } if (!mfd) { pr_err("%s: mfd is null!\n", __func__); return ret; } fps = mdp_get_panel_framerate(mfd); quota = pipe->src_w * pipe->src_h * fps * pipe->bpp; quota >>= shift; pipe->bw_ab_quota = quota * mdp_bw_ab_factor / 100; pipe->bw_ib_quota = quota * mdp_bw_ib_factor / 100; pr_debug("%s max_bw=%llu ab_factor=%d ib_factor=%d\n", __func__, mdp_max_bw, mdp_bw_ab_factor, mdp_bw_ib_factor); /* down scaling factor for ib */ if ((!pipe->dst_h) && (!pipe->src_h) && (pipe->src_h > pipe->dst_h)) { u64 ib = quota; ib *= pipe->src_h; ib /= pipe->dst_h; pipe->bw_ib_quota = max(ib, pipe->bw_ib_quota); pr_debug("%s: src_h=%d dst_h=%d mdp ib %llu, ib_quota=%llu\n", __func__, pipe->src_h, pipe->dst_h, ib<<shift, pipe->bw_ib_quota<<shift); } pipe->bw_ab_quota <<= shift; pipe->bw_ib_quota <<= shift; pr_debug("%s: pipe ndx=%d src(h,w)(%d, %d) fps=%d bpp=%d\n", __func__, pipe->pipe_ndx, pipe->src_h, pipe->src_w, fps, pipe->bpp); pr_debug("%s: ab_quota=%llu ib_quota=%llu\n", __func__, pipe->bw_ab_quota, pipe->bw_ib_quota); return 0; } int mdp4_calc_blt_mdp_bw(struct msm_fb_data_type *mfd, struct mdp4_overlay_pipe *pipe) { struct mdp4_overlay_perf *perf_req = &perf_request; u32 fps; int bpp; int ret = -EINVAL; u32 quota; u32 shift = 16; if (!pipe) { pr_err("%s: pipe is null!\n", __func__); return ret; } if (!mfd) { pr_err("%s: mfd is null!\n", __func__); return ret; } mutex_lock(&perf_mutex); bpp = BLT_BPP; fps = mdp_get_panel_framerate(mfd); /* read and write bw*/ quota = pipe->dst_w * pipe->dst_h * fps * bpp * 2; quota >>= shift; perf_req->mdp_ov_ab_bw[pipe->mixer_num] = quota * mdp_bw_ab_factor / 100; perf_req->mdp_ov_ib_bw[pipe->mixer_num] = quota * mdp_bw_ib_factor / 100; perf_req->mdp_ov_ab_bw[pipe->mixer_num] <<= shift; perf_req->mdp_ov_ib_bw[pipe->mixer_num] <<= shift; pr_debug("%s: pipe ndx=%d dst(h,w)(%d, %d) fps=%d bpp=%d\n", __func__, pipe->pipe_ndx, pipe->dst_h, pipe->dst_w, fps, bpp); pr_debug("%s: overlay=%d ab_bw=%llu ib_bw=%llu\n", __func__, pipe->mixer_num, perf_req->mdp_ov_ab_bw[pipe->mixer_num], perf_req->mdp_ov_ib_bw[pipe->mixer_num]); mutex_unlock(&perf_mutex); return 0; } int mdp4_overlay_mdp_perf_req(struct msm_fb_data_type *mfd) { u32 worst_mdp_clk = 0; int i; struct mdp4_overlay_perf *perf_req = &perf_request; struct mdp4_overlay_pipe *pipe; u32 cnt = 0; int ret = -EINVAL; u64 ab_quota_total = 0, ib_quota_total = 0; if (!mfd) { pr_err("%s: mfd is null!\n", __func__); return ret; } mutex_lock(&perf_mutex); pipe = ctrl->plist; for (i = 0; i < MDP4_MIXER_MAX; i++) perf_req->use_ov_blt[i] = 0; for (i = 0; i < OVERLAY_PIPE_MAX; i++, pipe++) { if (!pipe) { mutex_unlock(&perf_mutex); return ret; } if (!pipe->pipe_used) continue; cnt++; if (worst_mdp_clk < pipe->req_clk) worst_mdp_clk = pipe->req_clk; if (pipe->req_clk > mdp_max_clk) perf_req->use_ov_blt[pipe->mixer_num] = 1; if (pipe->mixer_num == MDP4_MIXER2) perf_req->use_ov_blt[MDP4_MIXER2] = 1; if (pipe->pipe_type != OVERLAY_TYPE_BF) { ab_quota_total += pipe->bw_ab_quota; ib_quota_total += pipe->bw_ib_quota; } if (mfd->mdp_rev == MDP_REV_41) { /* * writeback (blt) mode to provide work around * for dsi cmd mode interface hardware bug. */ if (ctrl->panel_mode & MDP4_PANEL_DSI_CMD) { if (pipe->dst_x != 0) perf_req->use_ov_blt[MDP4_MIXER0] = 1; } if ((mfd->panel_info.xres > 1280) && (mfd->panel_info.type != DTV_PANEL)) { perf_req->use_ov_blt[MDP4_MIXER0] = 1; } } } perf_req->mdp_clk_rate = min(worst_mdp_clk, mdp_max_clk); perf_req->mdp_clk_rate = mdp_clk_round_rate(perf_req->mdp_clk_rate); for (i = 0; i < MDP4_MIXER_MAX; i++) { if (perf_req->use_ov_blt[i]) { ab_quota_total += perf_req->mdp_ov_ab_bw[i]; ib_quota_total += perf_req->mdp_ov_ib_bw[i]; } } perf_req->mdp_ab_bw = roundup(ab_quota_total, MDP_BUS_SCALE_AB_STEP); perf_req->mdp_ib_bw = roundup(ib_quota_total, MDP_BUS_SCALE_AB_STEP); pr_debug("%s %d: ab_quota_total=(%llu, %d) ib_quota_total=(%llu, %d)\n", __func__, __LINE__, ab_quota_total, perf_req->mdp_ab_bw, ib_quota_total, perf_req->mdp_ib_bw); if (ab_quota_total > mdp_max_bw) pr_warn("%s: req ab bw=%llu is larger than max bw=%llu", __func__, ab_quota_total, mdp_max_bw); if (ib_quota_total > mdp_max_bw) pr_warn("%s: req ib bw=%llu is larger than max bw=%llu", __func__, ib_quota_total, mdp_max_bw); pr_debug("%s %d: pid %d cnt %d clk %d ov0_blt %d, ov1_blt %d\n", __func__, __LINE__, current->pid, cnt, perf_req->mdp_clk_rate, perf_req->use_ov_blt[0], perf_req->use_ov_blt[1]); mutex_unlock(&perf_mutex); return 0; } int mdp4_overlay_mdp_pipe_req(struct mdp4_overlay_pipe *pipe, struct msm_fb_data_type *mfd) { int ret = 0; if (mdp4_calc_pipe_mdp_clk(mfd, pipe)) { pr_err("%s unable to calc mdp pipe clk rate ret=%d\n", __func__, ret); ret = -EINVAL; } if (mdp4_calc_pipe_mdp_bw(mfd, pipe)) { pr_err("%s unable to calc mdp pipe bandwidth ret=%d\n", __func__, ret); ret = -EINVAL; } return ret; } void mdp4_overlay_mdp_perf_upd(struct msm_fb_data_type *mfd, int flag) { struct mdp4_overlay_perf *perf_req = &perf_request; struct mdp4_overlay_perf *perf_cur = &perf_current; pr_debug("%s %d: req mdp clk %d, cur mdp clk %d flag %d\n", __func__, __LINE__, perf_req->mdp_clk_rate, perf_cur->mdp_clk_rate, flag); mutex_lock(&perf_mutex); if (!mdp4_extn_disp) perf_cur->use_ov_blt[1] = 0; if (flag) { if (perf_req->mdp_clk_rate > perf_cur->mdp_clk_rate) { mdp_set_core_clk(perf_req->mdp_clk_rate); pr_info("%s mdp clk is changed [%d] from %d to %d\n", __func__, flag, perf_cur->mdp_clk_rate, perf_req->mdp_clk_rate); perf_cur->mdp_clk_rate = perf_req->mdp_clk_rate; } if ((perf_req->mdp_ab_bw > perf_cur->mdp_ab_bw) || (perf_req->mdp_ib_bw > perf_cur->mdp_ib_bw)) { mdp_bus_scale_update_request (perf_req->mdp_ab_bw, perf_req->mdp_ib_bw); pr_debug("%s mdp ab_bw is changed [%d] from %d to %d\n", __func__, flag, perf_cur->mdp_ab_bw, perf_req->mdp_ab_bw); pr_debug("%s mdp ib_bw is changed [%d] from %d to %d\n", __func__, flag, perf_cur->mdp_ib_bw, perf_req->mdp_ib_bw); perf_cur->mdp_ab_bw = perf_req->mdp_ab_bw; perf_cur->mdp_ib_bw = perf_req->mdp_ib_bw; } if ((mfd->panel_info.pdest == DISPLAY_1 && perf_req->use_ov_blt[0] && !perf_cur->use_ov_blt[0]) || dbg_force_ov0_blt) { if (mfd->panel_info.type == LCDC_PANEL || mfd->panel_info.type == LVDS_PANEL) mdp4_lcdc_overlay_blt_start(mfd); else if (mfd->panel_info.type == MIPI_VIDEO_PANEL) mdp4_dsi_video_blt_start(mfd); else if (ctrl->panel_mode & MDP4_PANEL_DSI_CMD) mdp4_dsi_cmd_blt_start(mfd); pr_debug("%s mixer0 start blt [%d] from %d to %d.\n", __func__, flag, perf_cur->use_ov_blt[0], perf_req->use_ov_blt[0]); perf_cur->use_ov_blt[0] = perf_req->use_ov_blt[0]; } if ((mfd->panel_info.pdest == DISPLAY_2 && perf_req->use_ov_blt[1] && !perf_cur->use_ov_blt[1]) || dbg_force_ov1_blt) { mdp4_dtv_overlay_blt_start(mfd); pr_debug("%s mixer1 start blt [%d] from %d to %d.\n", __func__, flag, perf_cur->use_ov_blt[1], perf_req->use_ov_blt[1]); perf_cur->use_ov_blt[1] = perf_req->use_ov_blt[1]; } } else { if (perf_req->mdp_clk_rate < perf_cur->mdp_clk_rate) { pr_info("%s mdp clk is changed [%d] from %d to %d\n", __func__, flag, perf_cur->mdp_clk_rate, perf_req->mdp_clk_rate); mdp_set_core_clk(perf_req->mdp_clk_rate); perf_cur->mdp_clk_rate = perf_req->mdp_clk_rate; } if (perf_req->mdp_ab_bw < perf_cur->mdp_ab_bw || perf_req->mdp_ib_bw < perf_cur->mdp_ib_bw) { mdp_bus_scale_update_request (perf_req->mdp_ab_bw, perf_req->mdp_ib_bw); pr_debug("%s mdp ab bw is changed [%d] from %d to %d\n", __func__, flag, perf_cur->mdp_ab_bw, perf_req->mdp_ab_bw); pr_debug("%s mdp ib bw is changed [%d] from %d to %d\n", __func__, flag, perf_cur->mdp_ib_bw, perf_req->mdp_ib_bw); perf_cur->mdp_ab_bw = perf_req->mdp_ab_bw; perf_cur->mdp_ib_bw = perf_req->mdp_ib_bw; } if ((mfd->panel_info.pdest == DISPLAY_1 && !perf_req->use_ov_blt[0] && perf_cur->use_ov_blt[0]) || dbg_force_ov0_blt) { if (mfd->panel_info.type == LCDC_PANEL || mfd->panel_info.type == LVDS_PANEL) mdp4_lcdc_overlay_blt_stop(mfd); else if (mfd->panel_info.type == MIPI_VIDEO_PANEL) mdp4_dsi_video_blt_stop(mfd); else if (ctrl->panel_mode & MDP4_PANEL_DSI_CMD) mdp4_dsi_cmd_blt_stop(mfd); pr_debug("%s mixer0 stop blt [%d] from %d to %d.\n", __func__, flag, perf_cur->use_ov_blt[0], perf_req->use_ov_blt[0]); perf_cur->use_ov_blt[0] = perf_req->use_ov_blt[0]; } if ((mfd->panel_info.pdest == DISPLAY_2 && !perf_req->use_ov_blt[1] && perf_cur->use_ov_blt[1]) || dbg_force_ov1_blt) { mdp4_dtv_overlay_blt_stop(mfd); pr_debug("%s mixer1 stop blt [%d] from %d to %d.\n", __func__, flag, perf_cur->use_ov_blt[1], perf_req->use_ov_blt[1]); perf_cur->use_ov_blt[1] = perf_req->use_ov_blt[1]; } } mutex_unlock(&perf_mutex); return; } static int get_img(struct msmfb_data *img, struct fb_info *info, struct mdp4_overlay_pipe *pipe, unsigned int plane, unsigned long *start, unsigned long *len, struct file **srcp_file, int *p_need, struct ion_handle **srcp_ihdl) { struct file *file; int put_needed, ret = 0, fb_num; #ifdef CONFIG_ANDROID_PMEM unsigned long vstart; #endif *p_need = 0; if (img->flags & MDP_BLIT_SRC_GEM) { *srcp_file = NULL; return kgsl_gem_obj_addr(img->memory_id, (int) img->priv, start, len); } if (img->flags & MDP_MEMORY_ID_TYPE_FB) { file = fget_light(img->memory_id, &put_needed); if (file == NULL) return -EINVAL; pipe->flags |= MDP_MEMORY_ID_TYPE_FB; if (MAJOR(file->f_dentry->d_inode->i_rdev) == FB_MAJOR) { fb_num = MINOR(file->f_dentry->d_inode->i_rdev); if (get_fb_phys_info(start, len, fb_num, DISPLAY_SUBSYSTEM_ID)) { ret = -1; } else { *srcp_file = file; *p_need = put_needed; } } else ret = -1; if (ret) fput_light(file, put_needed); return ret; } #ifdef CONFIG_MSM_MULTIMEDIA_USE_ION return mdp4_overlay_iommu_map_buf(img->memory_id, pipe, plane, start, len, srcp_ihdl); #endif #ifdef CONFIG_ANDROID_PMEM if (!get_pmem_file(img->memory_id, start, &vstart, len, srcp_file)) return 0; else return -EINVAL; #endif } #ifdef CONFIG_FB_MSM_MIPI_DSI int mdp4_overlay_3d_sbys(struct fb_info *info, struct msmfb_overlay_3d *req) { struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; int ret = -EPERM; if (mutex_lock_interruptible(&mfd->dma->ov_mutex)) return -EINTR; if (ctrl->panel_mode & MDP4_PANEL_DSI_CMD) { mdp4_dsi_cmd_3d_sbys(mfd, req); ret = 0; } else if (ctrl->panel_mode & MDP4_PANEL_DSI_VIDEO) { mdp4_dsi_video_3d_sbys(mfd, req); ret = 0; } mutex_unlock(&mfd->dma->ov_mutex); return ret; } #else int mdp4_overlay_3d_sbys(struct fb_info *info, struct msmfb_overlay_3d *req) { /* do nothing */ return -EPERM; } #endif int mdp4_overlay_blt(struct fb_info *info, struct msmfb_overlay_blt *req) { struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; if (mfd == NULL) return -ENODEV; if (mutex_lock_interruptible(&mfd->dma->ov_mutex)) return -EINTR; if (ctrl->panel_mode & MDP4_PANEL_DSI_CMD) mdp4_dsi_cmd_overlay_blt(mfd, req); else if (ctrl->panel_mode & MDP4_PANEL_DSI_VIDEO) mdp4_dsi_video_overlay_blt(mfd, req); else if (ctrl->panel_mode & MDP4_PANEL_LCDC) mdp4_lcdc_overlay_blt(mfd, req); else if (ctrl->panel_mode & MDP4_PANEL_MDDI) mdp4_mddi_overlay_blt(mfd, req); mutex_unlock(&mfd->dma->ov_mutex); return 0; } int mdp4_overlay_get(struct fb_info *info, struct mdp_overlay *req) { struct mdp4_overlay_pipe *pipe; pipe = mdp4_overlay_ndx2pipe(req->id); if (pipe == NULL) return -ENODEV; *req = pipe->req_data; if (mdp4_overlay_borderfill_supported()) req->flags |= MDP_BORDERFILL_SUPPORTED; return 0; } int mdp4_overlay_set(struct fb_info *info, struct mdp_overlay *req) { struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; int ret, mixer; struct mdp4_overlay_pipe *pipe; if (mfd == NULL) { pr_err("%s: mfd == NULL, -ENODEV\n", __func__); return -ENODEV; } if (info->node != 0 || mfd->cont_splash_done) /* primary */ if (!mfd->panel_power_on) /* suspended */ return -EPERM; if (req->src.format == MDP_FB_FORMAT) req->src.format = mfd->fb_imgType; if (mutex_lock_interruptible(&mfd->dma->ov_mutex)) { pr_err("%s: mutex_lock_interruptible, -EINTR\n", __func__); return -EINTR; } mixer = mfd->panel_info.pdest; /* DISPLAY_1 or DISPLAY_2 */ ret = mdp4_overlay_req2pipe(req, mixer, &pipe, mfd); if (ret < 0) { mutex_unlock(&mfd->dma->ov_mutex); pr_err("%s: mdp4_overlay_req2pipe, ret=%d\n", __func__, ret); return ret; } #if (CONFIG_MACH_LGE) mdp4_calc_pipe_mdp_clk(mfd, pipe); if(pipe->mixer_num == MDP4_MIXER0 && pipe->req_clk > mdp_max_clk && OVERLAY_TYPE_RGB == mdp4_overlay_format2type(pipe->src_format)) { pr_err("%s UI blt case, can't compose with MDP directly.\n", __func__); if(req->id == MSMFB_NEW_REQUEST) { mdp4_overlay_pipe_free(pipe,0); } mutex_unlock(&mfd->dma->ov_mutex); return -EINVAL; } #endif if (pipe->flags & MDP_SECURE_OVERLAY_SESSION) { mdp4_map_sec_resource(mfd); } /* return id back to user */ req->id = pipe->pipe_ndx; /* pipe_ndx start from 1 */ pipe->req_data = *req; /* keep original req */ if (!IS_ERR_OR_NULL(mfd->iclient)) { pr_debug("pipe->flags 0x%x\n", pipe->flags); if (pipe->flags & MDP_SECURE_OVERLAY_SESSION) { mfd->mem_hid &= ~BIT(ION_IOMMU_HEAP_ID); mfd->mem_hid |= ION_SECURE; } else { mfd->mem_hid |= BIT(ION_IOMMU_HEAP_ID); mfd->mem_hid &= ~ION_SECURE; } } mdp4_stat.overlay_set[pipe->mixer_num]++; if (pipe->flags & MDP_OVERLAY_PP_CFG_EN) { if (pipe->pipe_num <= OVERLAY_PIPE_VG2) memcpy(&pipe->pp_cfg, &req->overlay_pp_cfg, sizeof(struct mdp_overlay_pp_params)); else pr_debug("%s: RGB Pipes don't support CSC/QSEED\n", __func__); } mdp4_overlay_mdp_pipe_req(pipe, mfd); #if (CONFIG_MACH_LGE) #if defined(CONFIG_FB_MSM_MIPI_LGIT_VIDEO_WXGA_PT) || defined(CONFIG_FB_MSM_MIPI_HITACHI_VIDEO_HD_PT) if(pipe->mixer_num == MDP4_MIXER0 && OVERLAY_TYPE_VIDEO == mdp4_overlay_format2type(pipe->src_format)) { pr_debug("%s video blt mode off, req_clk is max now.\n", __func__); pipe->req_clk = mdp_max_clk; } #else if(pipe->mixer_num == MDP4_MIXER0 && pipe->req_clk > mdp_max_clk && OVERLAY_TYPE_VIDEO == mdp4_overlay_format2type(pipe->src_format)) { pr_debug("%s video blt mode off, req_clk is max now.\n", __func__); pipe->req_clk = mdp_max_clk; } #endif #endif mutex_unlock(&mfd->dma->ov_mutex); return 0; } int mdp4_overlay_unset_mixer(int mixer) { struct mdp4_overlay_pipe *pipe; int i, cnt = 0; /* free pipe besides base layer pipe */ for (i = MDP4_MIXER_STAGE3; i > MDP4_MIXER_STAGE_BASE; i--) { pipe = ctrl->stage[mixer][i]; if (pipe == NULL) continue; pipe->flags &= ~MDP_OV_PLAY_NOWAIT; mdp4_overlay_reg_flush(pipe, 1); mdp4_mixer_stage_down(pipe, 1); mdp4_overlay_pipe_free(pipe, 1); cnt++; } return cnt; } int mdp4_overlay_unset(struct fb_info *info, int ndx) { struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; struct mdp4_overlay_pipe *pipe; if (mfd == NULL) return -ENODEV; if (mutex_lock_interruptible(&mfd->dma->ov_mutex)) return -EINTR; pipe = mdp4_overlay_ndx2pipe(ndx); if (pipe == NULL) { mutex_unlock(&mfd->dma->ov_mutex); return -ENODEV; } if (pipe->pipe_type == OVERLAY_TYPE_BF) { mdp4_overlay_borderfill_stage_down(pipe); mutex_unlock(&mfd->dma->ov_mutex); return 0; } if (pipe->mixer_num == MDP4_MIXER2) ctrl->mixer2_played = 0; else if (pipe->mixer_num == MDP4_MIXER1) ctrl->mixer1_played = 0; else { /* mixer 0 */ ctrl->mixer0_played = 0; if (ctrl->panel_mode & MDP4_PANEL_MDDI) { if (mfd->panel_power_on) mdp4_mddi_blt_dmap_busy_wait(mfd); } } mdp4_overlay_reg_flush(pipe, 1); mdp4_mixer_stage_down(pipe, 0); if (pipe->blt_forced) { if (pipe->flags & MDP_SECURE_OVERLAY_SESSION) { pipe->blt_forced = 0; pipe->req_clk = 0; mdp4_overlay_mdp_perf_req(mfd); } } if (pipe->mixer_num == MDP4_MIXER0) { if (ctrl->panel_mode & MDP4_PANEL_MDDI) { if (mfd->panel_power_on) mdp4_mddi_overlay_restore(); } } else { /* mixer1, DTV, ATV */ if (ctrl->panel_mode & MDP4_PANEL_DTV) mdp4_overlay_dtv_unset(mfd, pipe); } mdp4_stat.overlay_unset[pipe->mixer_num]++; mdp4_overlay_pipe_free(pipe, 0); mutex_unlock(&mfd->dma->ov_mutex); return 0; } int mdp4_overlay_wait4vsync(struct fb_info *info) { if (!hdmi_prim_display && info->node == 0) { if (ctrl->panel_mode & MDP4_PANEL_DSI_VIDEO) mdp4_dsi_video_wait4vsync(0); else if (ctrl->panel_mode & MDP4_PANEL_DSI_CMD) mdp4_dsi_cmd_wait4vsync(0); else if (ctrl->panel_mode & MDP4_PANEL_LCDC) mdp4_lcdc_wait4vsync(0); } else if (hdmi_prim_display || info->node == 1) { mdp4_dtv_wait4vsync(0); } return 0; } int mdp4_overlay_vsync_ctrl(struct fb_info *info, int enable) { int cmd; if (enable) cmd = 1; else cmd = 0; if (!hdmi_prim_display && info->node == 0) { if (ctrl->panel_mode & MDP4_PANEL_DSI_VIDEO) mdp4_dsi_video_vsync_ctrl(info, cmd); else if (ctrl->panel_mode & MDP4_PANEL_DSI_CMD) mdp4_dsi_cmd_vsync_ctrl(info, cmd); else if (ctrl->panel_mode & MDP4_PANEL_LCDC) mdp4_lcdc_vsync_ctrl(info, cmd); } else if (hdmi_prim_display || info->node == 1) mdp4_dtv_vsync_ctrl(info, cmd); return 0; } struct tile_desc { uint32 width; /* tile's width */ uint32 height; /* tile's height */ uint32 row_tile_w; /* tiles per row's width */ uint32 row_tile_h; /* tiles per row's height */ }; void tile_samsung(struct tile_desc *tp) { /* * each row of samsung tile consists of two tiles in height * and two tiles in width which means width should align to * 64 x 2 bytes and height should align to 32 x 2 bytes. * video decoder generate two tiles in width and one tile * in height which ends up height align to 32 X 1 bytes. */ tp->width = 64; /* 64 bytes */ tp->row_tile_w = 2; /* 2 tiles per row's width */ tp->height = 32; /* 32 bytes */ tp->row_tile_h = 1; /* 1 tiles per row's height */ } uint32 tile_mem_size(struct mdp4_overlay_pipe *pipe, struct tile_desc *tp) { uint32 tile_w, tile_h; uint32 row_num_w, row_num_h; tile_w = tp->width * tp->row_tile_w; tile_h = tp->height * tp->row_tile_h; row_num_w = (pipe->src_width + tile_w - 1) / tile_w; row_num_h = (pipe->src_height + tile_h - 1) / tile_h; return ((row_num_w * row_num_h * tile_w * tile_h) + 8191) & ~8191; } int mdp4_overlay_play_wait(struct fb_info *info, struct msmfb_overlay_data *req) { return 0; } /* * mdp4_overlay_dma_commit: called from dma_done isr * No mutex/sleep allowed */ void mdp4_overlay_dma_commit(int mixer) { /* * non double buffer register update here * perf level, new clock rate should be done here */ } /* * mdp4_overlay_vsync_commit: called from tasklet context * No mutex/sleep allowed */ void mdp4_overlay_vsync_commit(struct mdp4_overlay_pipe *pipe) { if (pipe->pipe_type == OVERLAY_TYPE_VIDEO) mdp4_overlay_vg_setup(pipe); /* video/graphic pipe */ else mdp4_overlay_rgb_setup(pipe); /* rgb pipe */ pr_debug("%s: pipe=%x ndx=%d num=%d used=%d\n", __func__, (int) pipe, pipe->pipe_ndx, pipe->pipe_num, pipe->pipe_used); mdp4_overlay_reg_flush(pipe, 1); mdp4_mixer_stage_up(pipe, 0); } int mdp4_overlay_play(struct fb_info *info, struct msmfb_overlay_data *req) { struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; struct msmfb_data *img; struct mdp4_overlay_pipe *pipe; ulong start, addr; ulong len = 0; struct ion_handle *srcp0_ihdl = NULL; struct ion_handle *srcp1_ihdl = NULL, *srcp2_ihdl = NULL; uint32_t overlay_version = 0; int ret = 0; if (mfd == NULL) return -ENODEV; pipe = mdp4_overlay_ndx2pipe(req->id); if (pipe == NULL) { mdp4_stat.err_play++; return -ENODEV; } if (pipe->pipe_type == OVERLAY_TYPE_BF) { mdp4_overlay_borderfill_stage_up(pipe); mdp4_mixer_stage_commit(pipe->mixer_num); return 0; } mutex_lock(&mfd->dma->ov_mutex); img = &req->data; get_img(img, info, pipe, 0, &start, &len, &pipe->srcp0_file, &pipe->put0_need, &srcp0_ihdl); if (len == 0) { pr_err("%s: pmem Error\n", __func__); ret = -1; goto end; } addr = start + img->offset; pipe->srcp0_addr = addr; pipe->srcp0_ystride = pipe->src_width * pipe->bpp; pr_debug("%s: mixer=%d ndx=%x addr=%x flags=%x pid=%d\n", __func__, pipe->mixer_num, pipe->pipe_ndx, (int)addr, pipe->flags, current->pid); if ((req->version_key & VERSION_KEY_MASK) == 0xF9E8D700) overlay_version = (req->version_key & ~VERSION_KEY_MASK); if (pipe->fetch_plane == OVERLAY_PLANE_PSEUDO_PLANAR) { if (overlay_version > 0) { img = &req->plane1_data; get_img(img, info, pipe, 1, &start, &len, &pipe->srcp1_file, &pipe->put1_need, &srcp1_ihdl); if (len == 0) { pr_err("%s: Error to get plane1\n", __func__); ret = -EINVAL; goto end; } pipe->srcp1_addr = start + img->offset; } else if (pipe->frame_format == MDP4_FRAME_FORMAT_VIDEO_SUPERTILE) { struct tile_desc tile; tile_samsung(&tile); pipe->srcp1_addr = addr + tile_mem_size(pipe, &tile); } else { pipe->srcp1_addr = addr + (pipe->src_width * pipe->src_height); } pipe->srcp0_ystride = pipe->src_width; if ((pipe->src_format == MDP_Y_CRCB_H1V1) || (pipe->src_format == MDP_Y_CBCR_H1V1) || (pipe->src_format == MDP_Y_CRCB_H1V2) || (pipe->src_format == MDP_Y_CBCR_H1V2)) { if (pipe->src_width > YUV_444_MAX_WIDTH) pipe->srcp1_ystride = pipe->src_width << 2; else pipe->srcp1_ystride = pipe->src_width << 1; } else pipe->srcp1_ystride = pipe->src_width; } else if (pipe->fetch_plane == OVERLAY_PLANE_PLANAR) { if (overlay_version > 0) { img = &req->plane1_data; get_img(img, info, pipe, 1, &start, &len, &pipe->srcp1_file, &pipe->put1_need, &srcp1_ihdl); if (len == 0) { pr_err("%s: Error to get plane1\n", __func__); ret = -EINVAL; goto end; } pipe->srcp1_addr = start + img->offset; img = &req->plane2_data; get_img(img, info, pipe, 2, &start, &len, &pipe->srcp2_file, &pipe->put2_need, &srcp2_ihdl); if (len == 0) { pr_err("%s: Error to get plane2\n", __func__); ret = -EINVAL; goto end; } pipe->srcp2_addr = start + img->offset; } else { if (pipe->src_format == MDP_Y_CR_CB_GH2V2) { addr += (ALIGN(pipe->src_width, 16) * pipe->src_height); pipe->srcp1_addr = addr; addr += ((ALIGN((pipe->src_width / 2), 16)) * (pipe->src_height / 2)); pipe->srcp2_addr = addr; } else { addr += (pipe->src_width * pipe->src_height); pipe->srcp1_addr = addr; addr += ((pipe->src_width / 2) * (pipe->src_height / 2)); pipe->srcp2_addr = addr; } } /* mdp planar format expects Cb in srcp1 and Cr in p2 */ if ((pipe->src_format == MDP_Y_CR_CB_H2V2) || (pipe->src_format == MDP_Y_CR_CB_GH2V2)) swap(pipe->srcp1_addr, pipe->srcp2_addr); if (pipe->src_format == MDP_Y_CR_CB_GH2V2) { pipe->srcp0_ystride = ALIGN(pipe->src_width, 16); pipe->srcp1_ystride = ALIGN(pipe->src_width / 2, 16); pipe->srcp2_ystride = ALIGN(pipe->src_width / 2, 16); } else { pipe->srcp0_ystride = pipe->src_width; pipe->srcp1_ystride = pipe->src_width / 2; pipe->srcp2_ystride = pipe->src_width / 2; } } mdp4_overlay_mdp_perf_req(mfd); #if defined(CONFIG_FB_MSM_MIPI_LGIT_VIDEO_FHD_INVERSE_PT) pipe->mfd = mfd; #endif if (pipe->mixer_num == MDP4_MIXER0) { if (ctrl->panel_mode & MDP4_PANEL_DSI_CMD) { /* cndx = 0 */ mdp4_dsi_cmd_pipe_queue(0, pipe); } else if (ctrl->panel_mode & MDP4_PANEL_DSI_VIDEO) { /* cndx = 0 */ mdp4_dsi_video_pipe_queue(0, pipe); } else if (ctrl->panel_mode & MDP4_PANEL_LCDC) { /* cndx = 0 */ mdp4_lcdc_pipe_queue(0, pipe); } } else if (pipe->mixer_num == MDP4_MIXER1) { if (ctrl->panel_mode & MDP4_PANEL_DTV) mdp4_dtv_pipe_queue(0, pipe);/* cndx = 0 */ } else if (pipe->mixer_num == MDP4_MIXER2) { ctrl->mixer2_played++; if (ctrl->panel_mode & MDP4_PANEL_WRITEBACK) mdp4_wfd_pipe_queue(0, pipe);/* cndx = 0 */ } if (!(pipe->flags & MDP_OV_PLAY_NOWAIT)) mdp4_iommu_unmap(pipe); mdp4_stat.overlay_play[pipe->mixer_num]++; end: mutex_unlock(&mfd->dma->ov_mutex); return ret; } int mdp4_overlay_commit(struct fb_info *info) { int ret = 0, release_busy = true; struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; int mixer; if (mfd == NULL) { ret = -ENODEV; goto mdp4_overlay_commit_exit; } if (!mfd->panel_power_on) { ret = -EINVAL; goto mdp4_overlay_commit_exit; } mixer = mfd->panel_info.pdest; /* DISPLAY_1 or DISPLAY_2 */ if (mixer >= MDP4_MIXER_MAX) return -EPERM; mutex_lock(&mfd->dma->ov_mutex); msm_fb_wait_for_fence(mfd); switch (mfd->panel.type) { case MIPI_CMD_PANEL: mdp4_dsi_cmd_pipe_commit(0, 1, &release_busy); break; case MIPI_VIDEO_PANEL: mdp4_dsi_video_pipe_commit(0, 1); break; case LCDC_PANEL: mdp4_lcdc_pipe_commit(0, 1); break; case DTV_PANEL: mdp4_dtv_pipe_commit(0, 1); break; case WRITEBACK_PANEL: mdp4_wfd_pipe_commit(mfd, 0, 1); break; default: pr_err("Panel Not Supported for Commit"); ret = -EINVAL; break; } msm_fb_signal_timeline(mfd); mdp4_unmap_sec_resource(mfd); if (release_busy) mutex_unlock(&mfd->dma->ov_mutex); mdp4_overlay_commit_exit: if (release_busy) msm_fb_release_busy(mfd); return ret; } void mdp4_overlay_commit_finish(struct fb_info *info) { struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; mdp4_overlay_mdp_perf_upd(mfd, 0); } struct msm_iommu_ctx { char *name; int domain; }; static struct msm_iommu_ctx msm_iommu_ctx_names[] = { /* Display read*/ { .name = "mdp_port0_cb0", .domain = DISPLAY_READ_DOMAIN, }, /* Display read*/ { .name = "mdp_port0_cb1", .domain = DISPLAY_READ_DOMAIN, }, /* Display write */ { .name = "mdp_port1_cb0", .domain = DISPLAY_READ_DOMAIN, }, /* Display write */ { .name = "mdp_port1_cb1", .domain = DISPLAY_READ_DOMAIN, }, }; static struct msm_iommu_ctx msm_iommu_split_ctx_names[] = { /* Display read*/ { .name = "mdp_port0_cb0", .domain = DISPLAY_READ_DOMAIN, }, /* Display read*/ { .name = "mdp_port0_cb1", .domain = DISPLAY_WRITE_DOMAIN, }, /* Display write */ { .name = "mdp_port1_cb0", .domain = DISPLAY_READ_DOMAIN, }, /* Display write */ { .name = "mdp_port1_cb1", .domain = DISPLAY_WRITE_DOMAIN, }, }; void mdp4_iommu_attach(void) { static int done; struct msm_iommu_ctx *ctx_names; struct iommu_domain *domain; int i, arr_size; if (!done) { if (mdp_iommu_split_domain) { ctx_names = msm_iommu_split_ctx_names; arr_size = ARRAY_SIZE(msm_iommu_split_ctx_names); } else { ctx_names = msm_iommu_ctx_names; arr_size = ARRAY_SIZE(msm_iommu_ctx_names); } for (i = 0; i < arr_size; i++) { int domain_idx; struct device *ctx = msm_iommu_get_ctx( ctx_names[i].name); if (!ctx) continue; domain_idx = ctx_names[i].domain; domain = msm_get_iommu_domain(domain_idx); if (!domain) continue; if (iommu_attach_device(domain, ctx)) { WARN(1, "%s: could not attach domain %d to context %s." " iommu programming will not occur.\n", __func__, domain_idx, ctx_names[i].name); continue; } } done = 1; } } int mdp4_v4l2_overlay_set(struct fb_info *info, struct mdp_overlay *req, struct mdp4_overlay_pipe **ppipe) { struct mdp4_overlay_pipe *pipe; int err; struct msm_fb_data_type *mfb = info->par; req->z_order = 0; req->id = MSMFB_NEW_REQUEST; req->is_fg = false; req->alpha = 0xff; err = mdp4_overlay_req2pipe(req, MDP4_MIXER0, &pipe, mfb); if (err < 0) { pr_err("%s:Could not allocate MDP overlay pipe\n", __func__); return err; } mdp4_mixer_blend_setup(pipe->mixer_num); *ppipe = pipe; return 0; } void mdp4_v4l2_overlay_clear(struct mdp4_overlay_pipe *pipe) { mdp4_overlay_reg_flush(pipe, 1); mdp4_mixer_stage_down(pipe, 1); mdp4_overlay_pipe_free(pipe, 1); } int mdp4_v4l2_overlay_play(struct fb_info *info, struct mdp4_overlay_pipe *pipe, unsigned long srcp0_addr, unsigned long srcp1_addr, unsigned long srcp2_addr) { struct msm_fb_data_type *mfd = info->par; int err; if (mutex_lock_interruptible(&mfd->dma->ov_mutex)) return -EINTR; switch (pipe->src_format) { case MDP_Y_CR_CB_H2V2: /* YUV420 */ pipe->srcp0_addr = srcp0_addr; pipe->srcp0_ystride = pipe->src_width; /* * For YUV420, the luma plane is 1 byte per pixel times * num of pixels in the image Also, the planes are * switched in MDP, srcp2 is actually first chroma plane */ pipe->srcp2_addr = srcp1_addr ? srcp1_addr : pipe->srcp0_addr + (pipe->src_width * pipe->src_height); pipe->srcp2_ystride = pipe->src_width/2; /* * The chroma planes are half the size of the luma * planes */ pipe->srcp1_addr = srcp2_addr ? srcp2_addr : pipe->srcp2_addr + (pipe->src_width * pipe->src_height / 4); pipe->srcp1_ystride = pipe->src_width/2; break; case MDP_Y_CRCB_H2V2: /* NV12 */ pipe->srcp0_addr = srcp0_addr; pipe->srcp0_ystride = pipe->src_width; pipe->srcp1_addr = srcp1_addr ? srcp1_addr : pipe->srcp0_addr + (pipe->src_width * pipe->src_height); pipe->srcp1_ystride = pipe->src_width; break; default: pr_err("%s: format (%u) is not supported\n", __func__, pipe->src_format); err = -EINVAL; goto done; } pr_debug("%s: pipe ndx=%d stage=%d format=%x\n", __func__, pipe->pipe_ndx, pipe->mixer_stage, pipe->src_format); if (pipe->pipe_type == OVERLAY_TYPE_VIDEO) mdp4_overlay_vg_setup(pipe); else mdp4_overlay_rgb_setup(pipe); if (ctrl->panel_mode & MDP4_PANEL_LCDC) mdp4_overlay_reg_flush(pipe, 1); mdp4_mixer_stage_up(pipe, 0); /* mixer stage commit commits this */ mdp4_mixer_stage_commit(pipe->mixer_num); #ifdef V4L2_VSYNC /* * TODO: incorporate v4l2 into vsycn driven mechanism */ if (ctrl->panel_mode & MDP4_PANEL_LCDC) { mdp4_overlay_lcdc_vsync_push(mfd, pipe); } else { #ifdef CONFIG_FB_MSM_MIPI_DSI if (ctrl->panel_mode & MDP4_PANEL_DSI_CMD) { mdp4_dsi_cmd_dma_busy_wait(mfd); mdp4_dsi_cmd_kickoff_video(mfd, pipe); } #else if (ctrl->panel_mode & MDP4_PANEL_MDDI) { mdp4_mddi_dma_busy_wait(mfd); mdp4_mddi_kickoff_video(mfd, pipe); } #endif } #endif done: mutex_unlock(&mfd->dma->ov_mutex); return err; } int mdp4_overlay_reset() { memset(&perf_request, 0, sizeof(perf_request)); memset(&perf_current, 0, sizeof(perf_current)); return 0; }
OlegKyiashko/LGOGP-kernel
drivers/video/msm/mdp4_overlay.c
C
gpl-2.0
112,817
<?php /* +--------------------------------------------------------------------+ | CiviCRM version 4.6 | +--------------------------------------------------------------------+ | Copyright CiviCRM LLC (c) 2004-2015 | +--------------------------------------------------------------------+ | This file is a part of CiviCRM. | | | | CiviCRM is free software; you can copy, modify, and distribute it | | under the terms of the GNU Affero General Public License | | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. | | | | CiviCRM 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 Affero General Public License for more details. | | | | You should have received a copy of the GNU Affero General Public | | License and the CiviCRM Licensing Exception along | | with this program; if not, contact CiviCRM LLC | | at info[AT]civicrm[DOT]org. If you have questions about the | | GNU Affero General Public License or the licensing of CiviCRM, | | see the CiviCRM license FAQ at http://civicrm.org/licensing | +--------------------------------------------------------------------+ */ /** * @package CRM * @copyright CiviCRM LLC (c) 2004-2015 * * Generated from xml/schema/CRM/Contribute/Premium.xml * DO NOT EDIT. Generated by CRM_Core_CodeGen */ require_once 'CRM/Core/DAO.php'; require_once 'CRM/Utils/Type.php'; class CRM_Contribute_DAO_Premium extends CRM_Core_DAO { /** * static instance to hold the table name * * @var string */ static $_tableName = 'civicrm_premiums'; /** * static instance to hold the field values * * @var array */ static $_fields = null; /** * static instance to hold the keys used in $_fields for each field. * * @var array */ static $_fieldKeys = null; /** * static instance to hold the FK relationships * * @var string */ static $_links = null; /** * static instance to hold the values that can * be imported * * @var array */ static $_import = null; /** * static instance to hold the values that can * be exported * * @var array */ static $_export = null; /** * static value to see if we should log any modifications to * this table in the civicrm_log table * * @var boolean */ static $_log = true; /** * * @var int unsigned */ public $id; /** * Joins these premium settings to another object. Always civicrm_contribution_page for now. * * @var string */ public $entity_table; /** * * @var int unsigned */ public $entity_id; /** * Is the Premiums feature enabled for this page? * * @var boolean */ public $premiums_active; /** * Title for Premiums section. * * @var string */ public $premiums_intro_title; /** * Displayed in <div> at top of Premiums section of page. Text and HTML allowed. * * @var text */ public $premiums_intro_text; /** * This email address is included in receipts if it is populated and a premium has been selected. * * @var string */ public $premiums_contact_email; /** * This phone number is included in receipts if it is populated and a premium has been selected. * * @var string */ public $premiums_contact_phone; /** * Boolean. Should we automatically display minimum contribution amount text after the premium descriptions. * * @var boolean */ public $premiums_display_min_contribution; /** * Label displayed for No Thank-you option in premiums block (e.g. No thank you) * * @var string */ public $premiums_nothankyou_label; /** * * @var int unsigned */ public $premiums_nothankyou_position; /** * class constructor * * @return civicrm_premiums */ function __construct() { $this->__table = 'civicrm_premiums'; parent::__construct(); } /** * Returns foreign keys and entity references * * @return array * [CRM_Core_Reference_Interface] */ static function getReferenceColumns() { if (!self::$_links) { self::$_links = static ::createReferenceColumns(__CLASS__); self::$_links[] = new CRM_Core_Reference_Dynamic(self::getTableName() , 'entity_id', NULL, 'id', 'entity_table'); } return self::$_links; } /** * Returns all the column names of this table * * @return array */ static function &fields() { if (!(self::$_fields)) { self::$_fields = array( 'id' => array( 'name' => 'id', 'type' => CRM_Utils_Type::T_INT, 'title' => ts('Premium ID') , 'required' => true, ) , 'entity_table' => array( 'name' => 'entity_table', 'type' => CRM_Utils_Type::T_STRING, 'title' => ts('Premium Entity') , 'description' => 'Joins these premium settings to another object. Always civicrm_contribution_page for now.', 'required' => true, 'maxlength' => 64, 'size' => CRM_Utils_Type::BIG, ) , 'entity_id' => array( 'name' => 'entity_id', 'type' => CRM_Utils_Type::T_INT, 'title' => ts('Premium entity ID') , 'required' => true, ) , 'premiums_active' => array( 'name' => 'premiums_active', 'type' => CRM_Utils_Type::T_BOOLEAN, 'title' => ts('Is Premium Active?') , 'description' => 'Is the Premiums feature enabled for this page?', 'required' => true, ) , 'premiums_intro_title' => array( 'name' => 'premiums_intro_title', 'type' => CRM_Utils_Type::T_STRING, 'title' => ts('Title for Premiums section') , 'description' => 'Title for Premiums section.', 'maxlength' => 255, 'size' => CRM_Utils_Type::HUGE, ) , 'premiums_intro_text' => array( 'name' => 'premiums_intro_text', 'type' => CRM_Utils_Type::T_TEXT, 'title' => ts('Premium Introductory Text') , 'description' => 'Displayed in <div> at top of Premiums section of page. Text and HTML allowed.', ) , 'premiums_contact_email' => array( 'name' => 'premiums_contact_email', 'type' => CRM_Utils_Type::T_STRING, 'title' => ts('Premium Contact Email') , 'description' => 'This email address is included in receipts if it is populated and a premium has been selected.', 'maxlength' => 100, 'size' => CRM_Utils_Type::HUGE, ) , 'premiums_contact_phone' => array( 'name' => 'premiums_contact_phone', 'type' => CRM_Utils_Type::T_STRING, 'title' => ts('Premiums Contact Phone') , 'description' => 'This phone number is included in receipts if it is populated and a premium has been selected.', 'maxlength' => 50, 'size' => CRM_Utils_Type::BIG, ) , 'premiums_display_min_contribution' => array( 'name' => 'premiums_display_min_contribution', 'type' => CRM_Utils_Type::T_BOOLEAN, 'title' => ts('Display Minimum Contribution?') , 'description' => 'Boolean. Should we automatically display minimum contribution amount text after the premium descriptions.', 'required' => true, ) , 'premiums_nothankyou_label' => array( 'name' => 'premiums_nothankyou_label', 'type' => CRM_Utils_Type::T_STRING, 'title' => ts('No Thank-you Text') , 'description' => 'Label displayed for No Thank-you option in premiums block (e.g. No thank you)', 'maxlength' => 255, 'size' => CRM_Utils_Type::HUGE, ) , 'premiums_nothankyou_position' => array( 'name' => 'premiums_nothankyou_position', 'type' => CRM_Utils_Type::T_INT, 'title' => ts('No Thank-you Position') , 'default' => '1', ) , ); } return self::$_fields; } /** * Returns an array containing, for each field, the arary key used for that * field in self::$_fields. * * @return array */ static function &fieldKeys() { if (!(self::$_fieldKeys)) { self::$_fieldKeys = array( 'id' => 'id', 'entity_table' => 'entity_table', 'entity_id' => 'entity_id', 'premiums_active' => 'premiums_active', 'premiums_intro_title' => 'premiums_intro_title', 'premiums_intro_text' => 'premiums_intro_text', 'premiums_contact_email' => 'premiums_contact_email', 'premiums_contact_phone' => 'premiums_contact_phone', 'premiums_display_min_contribution' => 'premiums_display_min_contribution', 'premiums_nothankyou_label' => 'premiums_nothankyou_label', 'premiums_nothankyou_position' => 'premiums_nothankyou_position', ); } return self::$_fieldKeys; } /** * Returns the names of this table * * @return string */ static function getTableName() { return CRM_Core_DAO::getLocaleTableName(self::$_tableName); } /** * Returns if this table needs to be logged * * @return boolean */ function getLog() { return self::$_log; } /** * Returns the list of fields that can be imported * * @param bool $prefix * * @return array */ static function &import($prefix = false) { if (!(self::$_import)) { self::$_import = array(); $fields = self::fields(); foreach($fields as $name => $field) { if (CRM_Utils_Array::value('import', $field)) { if ($prefix) { self::$_import['premiums'] = & $fields[$name]; } else { self::$_import[$name] = & $fields[$name]; } } } } return self::$_import; } /** * Returns the list of fields that can be exported * * @param bool $prefix * * @return array */ static function &export($prefix = false) { if (!(self::$_export)) { self::$_export = array(); $fields = self::fields(); foreach($fields as $name => $field) { if (CRM_Utils_Array::value('export', $field)) { if ($prefix) { self::$_export['premiums'] = & $fields[$name]; } else { self::$_export[$name] = & $fields[$name]; } } } } return self::$_export; } }
eastoncat/cm.eastoncat
sites/all/modules/contrib/civicrm/CRM/Contribute/DAO/Premium.php
PHP
gpl-2.0
10,862
<?php /** * EXHIBIT A. Common Public Attribution License Version 1.0 * The contents of this file are subject to the Common Public Attribution License Version 1.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.oxwall.org/license. The License is based on the Mozilla Public License Version 1.1 * but Sections 14 and 15 have been added to cover use of software over a computer network and provide for * limited attribution for the Original Developer. In addition, Exhibit A has been modified to be consistent * with Exhibit B. Software distributed under the License is distributed on an “AS IS” basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language * governing rights and limitations under the License. The Original Code is Oxwall software. * The Initial Developer of the Original Code is Oxwall Foundation (http://www.oxwall.org/foundation). * All portions of the code written by Oxwall Foundation are Copyright (c) 2011. All Rights Reserved. * EXHIBIT B. Attribution Information * Attribution Copyright Notice: Copyright 2011 Oxwall Foundation. All rights reserved. * Attribution Phrase (not exceeding 10 words): Powered by Oxwall community software * Attribution URL: http://www.oxwall.org/ * Graphic Image as provided in the Covered Code. * Display of Attribution Information is required in Larger Works which are defined in the CPAL as a work * which combines Covered Code or portions thereof with code not governed by the terms of the CPAL. */ /** * Collector event * * @author Sergey Kambalin <[email protected]> * @package ow_system_plugins.base.bol * @since 1.0 */ class BASE_CLASS_EventCollector extends OW_Event { public function __construct( $name, $params = array() ) { parent::__construct($name, $params); $this->data = array(); } public function add( $item ) { $this->data[] = $item; } public function setData( $data ) { throw new LogicException("Can't set data in collector event `" . $this->getName() . "`!"); } }
locthdev/shopthoitrang-oxwall
ow_system_plugins/base/classes/event_collector.php
PHP
gpl-2.0
2,181
package org.mo.game.editor.face.apl.logic.report; import org.mo.jfa.common.page.FAbstractFormPage; public class FWebReportPage extends FAbstractFormPage{ private static final long serialVersionUID = 1L; private String _tempName; public String getTempName(){ return _tempName; } public void setTempName(String tempName){ _tempName = tempName; } }
favedit/MoPlatform
mo-gm-develop/src/editor-face/org/mo/game/editor/face/apl/logic/report/FWebReportPage.java
Java
gpl-2.0
389
import xml.etree.ElementTree as ET import requests from flask import Flask import batalha import pokemon import ataque class Cliente: def __init__(self, execute = False, ip = '127.0.0.1', port = 5000, npc = False): self.ip = ip self.port = port self.npc = npc if (execute): self.iniciaBatalha() def writeXML(self, pkmn): #Escreve um XML a partir de um pokemon root = ET.Element('battle_state') ET.SubElement(root, "pokemon") poke = root.find('pokemon') ET.SubElement(poke, "name") poke.find('name').text = pkmn.getNome() ET.SubElement(poke, "level") poke.find('level').text = str(pkmn.getLvl()) ET.SubElement(poke, "attributes") poke_att = poke.find('attributes') ET.SubElement(poke_att, "health") poke_att.find('health').text = str(pkmn.getHp()) ET.SubElement(poke_att, "attack") poke_att.find('attack').text = str(pkmn.getAtk()) ET.SubElement(poke_att, "defense") poke_att.find('defense').text = str(pkmn.getDefe()) ET.SubElement(poke_att, "speed") poke_att.find('speed').text = str(pkmn.getSpd()) ET.SubElement(poke_att, "special") poke_att.find('special').text = str(pkmn.getSpc()) ET.SubElement(poke, "type") ET.SubElement(poke, "type") tipos = poke.findall('type') tipos[0].text = str(pkmn.getTyp1()) tipos[1].text = str(pkmn.getTyp2()) for i in range(0, 4): atk = pkmn.getAtks(i) if (atk is not None): ET.SubElement(poke, "attacks") poke_atk = poke.findall('attacks') ET.SubElement(poke_atk[-1], "id") poke_atk[-1].find('id').text = str(i + 1) ET.SubElement(poke_atk[-1], "name") poke_atk[-1].find('name').text = atk.getNome() ET.SubElement(poke_atk[-1], "type") poke_atk[-1].find('type').text = str(atk.getTyp()) ET.SubElement(poke_atk[-1], "power") poke_atk[-1].find('power').text = str(atk.getPwr()) ET.SubElement(poke_atk[-1], "accuracy") poke_atk[-1].find('accuracy').text = str(atk.getAcu()) ET.SubElement(poke_atk[-1], "power_points") poke_atk[-1].find('power_points').text = str(atk.getPpAtual()) s = ET.tostring(root) return s def iniciaBatalha(self): pkmn = pokemon.Pokemon() xml = self.writeXML(pkmn) try: self.battle_state = requests.post('http://{}:{}/battle/'.format(self.ip, self.port), data = xml).text except requests.exceptions.ConnectionError: print("Não foi possível conectar ao servidor.") return None pkmn2 = pokemon.lePokemonXML(1, self.battle_state) self.batalha = batalha.Batalha([pkmn, pkmn2]) if (self.npc): self.batalha.pkmn[0].npc = True print("Eu sou um NPC") self.batalha.turno = 0 self.batalha.display.showPokemon(self.batalha.pkmn[0]) self.batalha.display.showPokemon(self.batalha.pkmn[1]) return self.atualizaBatalha() def atualizaBatalha(self): self.batalha.AlternaTurno() root = ET.fromstring(self.battle_state) for i in range(0,2): pkmnXML = root[i] atksXML = root[i].findall('attacks') pkmn = self.batalha.pkmn[i] pkmn.setHpAtual(int(pkmnXML.find('attributes').find('health').text)) self.batalha.showStatus() if (not self.batalha.isOver()): self.batalha.AlternaTurno() if (self.batalha.pkmn[self.batalha.turno].npc): id = self.batalha.EscolheAtaqueInteligente() else: id = self.batalha.EscolheAtaque() self.batalha.pkmn[0].getAtks(id).decreasePp() if (id == 4): self.battle_state = requests.post('http://{}:{}/battle/attack/{}'.format(self.ip, self.port, 0)).text else: self.battle_state = requests.post('http://{}:{}/battle/attack/{}'.format(self.ip, self.port, id + 1)).text self.simulaAtaque(id) self.atualizaBatalha() else: self.batalha.showResults() return 'FIM' def sendShutdownSignal(self): requests.post('http://{}:{}/shutdown'.format(self.ip, self.port)) def simulaAtaque(self, idCliente): disp = self.batalha.display root = ET.fromstring(self.battle_state) pkmnCXML = root[0] pkmnC = self.batalha.pkmn[0] pkmnSXML = root[1] pkmnS = self.batalha.pkmn[1] atksXML = pkmnSXML.findall('attacks') idServidor = self.descobreAtaqueUsado(atksXML, pkmnS) if (int(pkmnSXML.find('attributes').find('health').text) > 0): if (idCliente != 4): if (idServidor != 4): dmg = pkmnS.getHpAtual() - int(pkmnSXML.find('attributes').find('health').text) if (dmg == 0): disp.miss(pkmnC, pkmnS, pkmnC.getAtks(idCliente)) else: disp.hit(pkmnC, pkmnS, pkmnC.getAtks(idCliente), dmg) dmg = pkmnC.getHpAtual() - int(pkmnCXML.find('attributes').find('health').text) if (dmg == 0): disp.miss(pkmnS, pkmnC, pkmnS.getAtks(idServidor)) else: disp.hit(pkmnS, pkmnC, pkmnS.getAtks(idServidor), dmg) else: dmgStruggle = pkmnC.getHpAtual() - int(pkmnCXML.find('attributes').find('health').text) dmg = pkmnS.getHpAtual() - int(pkmnSXML.find('attributes').find('health').text) + round(dmgStruggle / 2, 0) if (dmg == 0): disp.miss(pkmnC, pkmnS, pkmnC.getAtks(idCliente)) else: disp.hit(pkmnC, pkmnS, pkmnC.getAtks(idCliente), dmg) disp.hit(pkmnS, pkmnC, pkmnS.getAtks(idServidor), dmgStruggle) disp.hitSelf(pkmnS, round(dmgStruggle / 2, 0)) else: if (idServidor != 4): dmgStruggle = pkmnS.getHpAtual() - int(pkmnSXML.find('attributes').find('health').text) disp.hit(pkmnC, pkmnS, pkmnC.getAtks(idCliente), dmgStruggle) disp.hitSelf(pkmnC, round(dmgStruggle / 2, 0)) dmg = pkmnC.getHpAtual() - int(pkmnCXML.find('attributes').find('health').text) + round(dmgStruggle / 2, 0) if (dmg == 0): disp.miss(pkmnS, pkmnC, pkmnS.getAtks(idServidor)) else: disp.hit(pkmnS, pkmnC, pkmnS.getAtks(idServidor), dmg) else: print('Ambos usam e se machucam com Struggle!') else: if (idCliente != 4): dmg = pkmnS.getHpAtual() - int(pkmnSXML.find('attributes').find('health').text) if (dmg == 0): disp.miss(pkmnC, pkmnS, pkmnC.getAtks(idCliente)) else: disp.hit(pkmnC, pkmnS, pkmnC.getAtks(idCliente), dmg) else: dmgStruggle = pkmnC.getHpAtual() - int(pkmnCXML.find('attributes').find('health').text) disp.hit(pkmnC, pkmnS, pkmnC.getAtks(idServidor), dmgStruggle * 2) disp.hitSelf(pkmnC, round(dmgStruggle, 0)) def descobreAtaqueUsado(self, atksXML, pkmn): for i in range(0, len(atksXML)): id = int(atksXML[i].find('id').text) - 1 ppXML = int(atksXML[i].find('power_points').text) pp = pkmn.getAtks(id).getPpAtual() if (pp != ppXML): pkmn.getAtks(id).decreasePp() return id return id
QuartetoFantastico/projetoPokemon
cliente.py
Python
gpl-2.0
6,564
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Text; using System.Windows.Forms; using System.Threading; using System.Net; using System.Collections; using System.Web; using System.Xml; using System.Reflection; using Microsoft.Win32; using System.Globalization; using Microsoft.FlightSimulator.SimConnect; using System.Runtime.InteropServices; namespace FSX_Google_Earth_Tracker { public partial class Form1 : Form { #region Global Variables bool bErrorOnLoad = false; Form2 frmAdd = new Form2(); String szAppPath = ""; //String szCommonPath = ""; String szUserAppPath = ""; String szFilePathPub = ""; String szFilePathData = ""; String szServerPath = ""; IPAddress[] ipalLocal1 = null; IPAddress[] ipalLocal2 = null; System.Object lockIPAddressList = new System.Object(); string /* szPathGE , */ szPathFSX; const string szRegKeyRun = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run"; //const int iOnlineVersionCheckRawDataLength = 64; //WebRequest wrOnlineVersionCheck; //WebResponse wrespOnlineVersionCheck; //private byte[] bOnlineVersionCheckRawData = new byte[iOnlineVersionCheckRawDataLength]; //String szOnlineVersionCheckData = ""; XmlTextReader xmlrSeetingsFile; XmlTextWriter xmlwSeetingsFile; XmlDocument xmldSettings; GlobalFixConfiguration gconffixCurrent = new GlobalFixConfiguration(); GlobalChangingConfiguration gconfchCurrent; System.Object lockChConf = new System.Object(); bool bClose = false; bool bConnected = false; //bool bServerUp = false; bool bRestartRequired = false; const int WM_USER_SIMCONNECT = 0x0402; SimConnect simconnect = null; Icon icActive, icDisabled, icReceive; Image imgAtcLabel; HttpListener listener; System.Object lockListenerControl = new System.Object(); uint uiUserAircraftID = 0; bool bUserAircraftIDSet = false; System.Object lockUserAircraftID = new System.Object(); StructBasicMovingSceneryObject suadCurrent; System.Object lockKmlUserAircraft = new System.Object(); String szKmlUserAircraftPath = ""; System.Object lockKmlUserPath = new System.Object(); PathPosition ppPos1, ppPos2; String szKmlUserPrediction = ""; List<PathPositionStored> listKmlPredictionPoints; System.Object lockKmlUserPrediction = new System.Object(); System.Object lockKmlPredictionPoints = new System.Object(); DataRequestReturn drrAIPlanes; System.Object lockDrrAiPlanes = new System.Object(); DataRequestReturn drrAIHelicopters; System.Object lockDrrAiHelicopters = new System.Object(); DataRequestReturn drrAIBoats; System.Object lockDrrAiBoats = new System.Object(); DataRequestReturn drrAIGround; System.Object lockDrrAiGround = new System.Object(); List<ObjectImage> listIconsGE; List<ObjectImage> listImgUnitsAir, listImgUnitsWater, listImgUnitsGround; //List<FlightPlan> listFlightPlans; //System.Object lockFlightPlanList = new System.Object(); byte[] imgNoImage; #endregion #region Structs & Enums enum DEFINITIONS { StructBasicMovingSceneryObject, }; enum DATA_REQUESTS { REQUEST_USER_AIRCRAFT, REQUEST_USER_PATH, REQUEST_USER_PREDICTION, REQUEST_AI_HELICOPTER, REQUEST_AI_PLANE, REQUEST_AI_BOAT, REQUEST_AI_GROUND }; enum KML_FILES { REQUEST_USER_AIRCRAFT, REQUEST_USER_PATH, REQUEST_USER_PREDICTION, REQUEST_AI_HELICOPTER, REQUEST_AI_PLANE, REQUEST_AI_BOAT, REQUEST_AI_GROUND, REQUEST_FLIGHT_PLANS }; enum KML_ACCESS_MODES { MODE_SERVER, MODE_FILE_LOCAL, MODE_FILE_USERDEFINED }; enum KML_IMAGE_TYPES { AIRCRAFT, WATER, GROUND }; enum KML_ICON_TYPES { USER_AIRCRAFT_POSITION, USER_PREDICTION_POINT, AI_AIRCRAFT_PREDICTION_POINT, AI_HELICOPTER_PREDICTION_POINT, AI_BOAT_PREDICTION_POINT, AI_GROUND_PREDICTION_POINT, AI_AIRCRAFT, AI_HELICOPTER, AI_BOAT, AI_GROUND_UNIT, PLAN_VOR, PLAN_NDB, PLAN_USER, PLAN_PORT, PLAN_INTER, ATC_LABEL, UNKNOWN }; [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)] struct StructBasicMovingSceneryObject { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public String szTitle; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public String szATCType; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public String szATCModel; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public String szATCID; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)] public String szATCAirline; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public String szATCFlightNumber; public double dLatitude; public double dLongitude; public double dAltitude; public double dSpeed; public double dVSpeed; //public double dSpeedX; //public double dSpeedY; //public double dSpeedZ; public double dTime; }; struct DataRequestReturn { public List<DataRequestReturnObject> listFirst; public List<DataRequestReturnObject> listSecond; public uint uiLastEntryNumber; public uint uiCurrentDataSet; public bool bClearOnNextRun; }; struct DataRequestReturnObject { public uint uiObjectID; public StructBasicMovingSceneryObject bmsoObject; public String szCoursePrediction; public PathPositionStored[] ppsPredictionPoints; } struct PathPosition { public bool bInitialized; public double dLat; public double dLong; public double dAlt; public double dTime; } struct PathPositionStored { public double dLat; public double dLong; public double dAlt; public double dTime; } struct ObjectImage { public String szTitle; public String szPath; public byte[] bData; }; class GlobalFixConfiguration { public bool bLoadKMLFile; //public bool bCheckForUpdates; public long iServerPort; public uint uiServerAccessLevel; public String szUserdefinedPath; public bool bQueryUserAircraft; public long iTimerUserAircraft; public bool bQueryUserPath; public long iTimerUserPath; public bool bUserPathPrediction; public long iTimerUserPathPrediction; public double[] dPredictionTimes; public bool bQueryAIObjects; public bool bQueryAIAircrafts; public long iTimerAIAircrafts; public long iRangeAIAircrafts; public bool bPredictAIAircrafts; public bool bPredictPointsAIAircrafts; public bool bQueryAIHelicopters; public long iTimerAIHelicopters; public long iRangeAIHelicopters; public bool bPredictAIHelicopters; public bool bPredictPointsAIHelicopters; public bool bQueryAIBoats; public long iTimerAIBoats; public long iRangeAIBoats; public bool bPredictAIBoats; public bool bPredictPointsAIBoats; public bool bQueryAIGroundUnits; public long iTimerAIGroundUnits; public long iRangeAIGroundUnits; public bool bPredictAIGroundUnits; public bool bPredictPointsAIGroundUnits; public long iUpdateGEUserAircraft; public long iUpdateGEUserPath; public long iUpdateGEUserPrediction; public long iUpdateGEAIAircrafts; public long iUpdateGEAIHelicopters; public long iUpdateGEAIBoats; public long iUpdateGEAIGroundUnits; public bool bFsxConnectionIsLocal; public String szFsxConnectionProtocol; public String szFsxConnectionHost; public String szFsxConnectionPort; public bool bExitOnFsxExit; private Object lock_utUnits = new Object(); private UnitType priv_utUnits; public UnitType utUnits { get { lock (lock_utUnits) { return priv_utUnits; } } set { lock (lock_utUnits) { priv_utUnits = value; } } } //public bool bLoadFlightPlans; }; struct GlobalChangingConfiguration { public bool bEnabled; public bool bShowBalloons; }; struct ListBoxPredictionTimesItem { public double dTime; public override String ToString() { if (dTime < 60) return "ETA " + dTime + " sec"; else if (dTime < 3600) return "ETA " + Math.Round(dTime / 60.0, 1) + " min"; else return "ETA " + Math.Round(dTime / 3600.0, 2) + " hrs"; } } enum UnitType { METERS, FEET }; //struct ListViewFlightPlansItem //{ // public String szName; // public int iID; // public override String ToString() // { // return szName.ToString(); // } //} //struct FlightPlan //{ // public int uiID; // public String szName; // public XmlDocument xmldPlan; //} #endregion #region Form Functions public Form1() { //As this method doesn't start any other threads we don't need to lock anything here (especially not the config file xml document) InitializeComponent(); Text = AssemblyTitle; thrConnect = new Thread(new ThreadStart(openConnectionThreadFunction)); text = Text; // Set data for the about page this.labelProductName.Text = AssemblyProduct; this.labelVersion.Text = String.Format("Version {0}", AssemblyVersion); this.labelCopyright.Text = AssemblyCopyright; this.labelCompanyName.Text = AssemblyCompany; // Set file path #if DEBUG szAppPath = Application.StartupPath + "\\..\\.."; szUserAppPath = szAppPath + "\\AppData\\" + AssemblyVersion; #else szAppPath = Application.StartupPath; szUserAppPath = Application.UserAppDataPath; #endif szFilePathPub = szAppPath + "\\pub"; szFilePathData = szAppPath + "\\data"; // Check if config file for current user exists if (!File.Exists(szUserAppPath + "\\settings.cfg")) { if (!Directory.Exists(szUserAppPath)) Directory.CreateDirectory(szUserAppPath); File.Copy(szAppPath + "\\data\\settings.default", szUserAppPath + "\\settings.cfg"); File.SetAttributes(szUserAppPath + "\\settings.cfg", FileAttributes.Normal); } // Load config file into memory xmlrSeetingsFile = new XmlTextReader(szUserAppPath + "\\settings.cfg"); xmldSettings = new XmlDocument(); xmldSettings.PreserveWhitespace = true; xmldSettings.Load(xmlrSeetingsFile); xmlrSeetingsFile.Close(); xmlrSeetingsFile = null; // Make sure we have a config file for the right version // (future version should contain better checks and update from old config files to new version) String szConfigVersion = ""; bool bUpdate = false; try { szConfigVersion = xmldSettings["fsxget"]["settings"].Attributes["version"].Value; } catch { bUpdate = true; } if (bUpdate || !szConfigVersion.Equals(ProductVersion.ToLower())) { try { File.SetAttributes(szUserAppPath + "\\settings.cfg", FileAttributes.Normal); File.Delete(szUserAppPath + "\\settings.cfg"); File.Copy(szAppPath + "\\data\\settings.default", szUserAppPath + "\\settings.cfg"); File.SetAttributes(szUserAppPath + "\\settings.cfg", FileAttributes.Normal); xmlrSeetingsFile = new XmlTextReader(szUserAppPath + "\\settings.cfg"); xmldSettings = new XmlDocument(); xmldSettings.PreserveWhitespace = true; xmldSettings.Load(xmlrSeetingsFile); xmlrSeetingsFile.Close(); xmlrSeetingsFile = null; xmldSettings["fsxget"]["settings"].Attributes["version"].Value = ProductVersion; } catch { MessageBox.Show("The config file for this program cannot be updated. Aborting!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error); bErrorOnLoad = true; return; } } // Mirror values we need from config file in memory to variables try { ConfigMirrorToVariables(); } catch { MessageBox.Show("The config file for this program contains errors. Aborting!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error); bErrorOnLoad = true; return; } // Write SimConnect configuration file try { File.Delete(szAppPath + "\\SimConnect.cfg"); } catch { } if (!gconffixCurrent.bFsxConnectionIsLocal) { try { StreamWriter swSimConnectCfg = File.CreateText(szAppPath + "\\SimConnect.cfg"); swSimConnectCfg.WriteLine("; FSXGET SimConnect client configuration"); swSimConnectCfg.WriteLine(); swSimConnectCfg.WriteLine("[SimConnect]"); swSimConnectCfg.WriteLine("Protocol=" + gconffixCurrent.szFsxConnectionProtocol); swSimConnectCfg.WriteLine("Address=" + gconffixCurrent.szFsxConnectionHost); swSimConnectCfg.WriteLine("Port=" + gconffixCurrent.szFsxConnectionPort); swSimConnectCfg.WriteLine(); swSimConnectCfg.Flush(); swSimConnectCfg.Close(); swSimConnectCfg.Dispose(); } catch { MessageBox.Show("The SimConnect client configuration file could not be written. Aborting!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error); bErrorOnLoad = true; return; } } // Update the notification icon context menu lock (lockChConf) { enableTrackerToolStripMenuItem.Checked = gconfchCurrent.bEnabled; showBalloonTipsToolStripMenuItem.Checked = gconfchCurrent.bShowBalloons; } // Set timer intervals timerFSXConnect.Interval = 1500; timerQueryUserAircraft.Interval = (int)gconffixCurrent.iTimerUserAircraft; timerQueryUserPath.Interval = (int)gconffixCurrent.iTimerUserPath; timerUserPrediction.Interval = (int)gconffixCurrent.iTimerUserPathPrediction; timerQueryAIAircrafts.Interval = (int)gconffixCurrent.iTimerAIAircrafts; timerQueryAIHelicopters.Interval = (int)gconffixCurrent.iTimerAIHelicopters; timerQueryAIBoats.Interval = (int)gconffixCurrent.iTimerAIBoats; timerQueryAIGroundUnits.Interval = (int)gconffixCurrent.iTimerAIGroundUnits; timerIPAddressRefresh.Interval = 10000; // Set server settings szServerPath = "http://+:" + gconffixCurrent.iServerPort.ToString(); listener = new HttpListener(); listener.Prefixes.Add(szServerPath + "/"); // Lookup (in the config file) and load program icons, google earth pins and object images try { // notification icons for (XmlNode xmlnTemp = xmldSettings["fsxget"]["gfx"]["program"]["icons"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling) { if (xmlnTemp.NodeType == XmlNodeType.Whitespace) continue; if (xmlnTemp.Attributes["Name"].Value == "Taskbar - Enabled") icActive = new Icon(szFilePathData + xmlnTemp.Attributes["Img"].Value); else if (xmlnTemp.Attributes["Name"].Value == "Taskbar - Disabled") icDisabled = new Icon(szFilePathData + xmlnTemp.Attributes["Img"].Value); else if (xmlnTemp.Attributes["Name"].Value == "Taskbar - Connected") icReceive = new Icon(szFilePathData + xmlnTemp.Attributes["Img"].Value); } notifyIconMain.Icon = icDisabled; notifyIconMain.Text = this.Text; notifyIconMain.Visible = true; // google earth icons listIconsGE = new List<ObjectImage>(xmldSettings["fsxget"]["gfx"]["ge"]["icons"].ChildNodes.Count); for (XmlNode xmlnTemp = xmldSettings["fsxget"]["gfx"]["ge"]["icons"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling) { if (xmlnTemp.NodeType == XmlNodeType.Whitespace) continue; ObjectImage imgTemp = new ObjectImage(); imgTemp.szTitle = xmlnTemp.Attributes["Name"].Value; imgTemp.bData = File.ReadAllBytes(szFilePathPub + xmlnTemp.Attributes["Img"].Value); listIconsGE.Add(imgTemp); } // no-image image imgNoImage = File.ReadAllBytes(szFilePathPub + xmldSettings["fsxget"]["gfx"]["scenery"]["noimage"].Attributes["Img"].Value); // ATC label base image imgAtcLabel = Image.FromFile(szFilePathData + xmldSettings["fsxget"]["gfx"]["ge"]["atclabel"].Attributes["Img"].Value); // object images listImgUnitsAir = new List<ObjectImage>(xmldSettings["fsxget"]["gfx"]["scenery"]["air"].ChildNodes.Count); for (XmlNode xmlnTemp = xmldSettings["fsxget"]["gfx"]["scenery"]["air"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling) { if (xmlnTemp.NodeType == XmlNodeType.Whitespace) continue; ObjectImage imgTemp = new ObjectImage(); imgTemp.szTitle = xmlnTemp.Attributes["Name"].Value; imgTemp.szPath = xmlnTemp.Attributes["Img"].Value; imgTemp.bData = File.ReadAllBytes(szFilePathPub + xmlnTemp.Attributes["Img"].Value); listImgUnitsAir.Add(imgTemp); } listImgUnitsWater = new List<ObjectImage>(xmldSettings["fsxget"]["gfx"]["scenery"]["water"].ChildNodes.Count); for (XmlNode xmlnTemp = xmldSettings["fsxget"]["gfx"]["scenery"]["water"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling) { if (xmlnTemp.NodeType == XmlNodeType.Whitespace) continue; ObjectImage imgTemp = new ObjectImage(); imgTemp.szTitle = xmlnTemp.Attributes["Name"].Value; imgTemp.szPath = xmlnTemp.Attributes["Img"].Value; imgTemp.bData = File.ReadAllBytes(szFilePathPub + xmlnTemp.Attributes["Img"].Value); listImgUnitsWater.Add(imgTemp); } listImgUnitsGround = new List<ObjectImage>(xmldSettings["fsxget"]["gfx"]["scenery"]["ground"].ChildNodes.Count); for (XmlNode xmlnTemp = xmldSettings["fsxget"]["gfx"]["scenery"]["ground"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling) { if (xmlnTemp.NodeType == XmlNodeType.Whitespace) continue; ObjectImage imgTemp = new ObjectImage(); imgTemp.szTitle = xmlnTemp.Attributes["Name"].Value; imgTemp.szPath = xmlnTemp.Attributes["Img"].Value; imgTemp.bData = File.ReadAllBytes(szFilePathPub + xmlnTemp.Attributes["Img"].Value); listImgUnitsWater.Add(imgTemp); } } catch { MessageBox.Show("Could not load all graphics files probably due to errors in the config file. Aborting!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error); bErrorOnLoad = true; return; } // Initialize some variables clearDrrStructure(ref drrAIPlanes); clearDrrStructure(ref drrAIHelicopters); clearDrrStructure(ref drrAIBoats); clearDrrStructure(ref drrAIGround); clearPPStructure(ref ppPos1); clearPPStructure(ref ppPos2); //listFlightPlans = new List<FlightPlan>(); listKmlPredictionPoints = new List<PathPositionStored>(gconffixCurrent.dPredictionTimes.GetLength(0)); // Test drive the following function which loads data from the config file, as it will be used regularly later on try { ConfigMirrorToForm(); } catch { MessageBox.Show("The config file for this program contains errors. Aborting!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error); bErrorOnLoad = true; return; } // Load FSX and Google Earth path from registry const string szRegKeyFSX = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft Games\\flight simulator\\10.0"; //const string szRegKeyGE = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Google\\Google Earth Plus"; //const string szRegKeyGE2 = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Google\\Google Earth Pro"; //szPathGE = (string)Registry.GetValue(szRegKeyGE, "InstallDir", ""); //if (szPathGE == "") // szPathGE = (string)Registry.GetValue(szRegKeyGE2, "InstallDir", ""); szPathFSX = (string)Registry.GetValue(szRegKeyFSX, "SetupPath", ""); //if (szPathGE != "") //{ // szPathGE += "\\googleearth.exe"; // if (File.Exists(szPathGE)) // runGoogleEarthToolStripMenuItem.Enabled = true; // else // runGoogleEarthToolStripMenuItem.Enabled = false; //} //else // runGoogleEarthToolStripMenuItem.Enabled = false; runGoogleEarthToolStripMenuItem.Enabled = true; if (szPathFSX != "") { szPathFSX += "fsx.exe"; if (File.Exists(szPathFSX)) runMicrosoftFlightSimulatorXToolStripMenuItem.Enabled = true; else runMicrosoftFlightSimulatorXToolStripMenuItem.Enabled = false; } else runMicrosoftFlightSimulatorXToolStripMenuItem.Enabled = false; // Write Google Earth startup KML file String szTempKMLFile = ""; String szTempKMLFileStatic = ""; if (CompileKMLStartUpFileDynamic("localhost", ref szTempKMLFile) && CompileKMLStartUpFileStatic("localhost", ref szTempKMLFileStatic)) { try { if (!Directory.Exists(szUserAppPath + "\\pub")) Directory.CreateDirectory(szUserAppPath + "\\pub"); File.WriteAllText(szUserAppPath + "\\pub\\fsxgetd.kml", szTempKMLFile); File.WriteAllText(szUserAppPath + "\\pub\\fsxgets.kml", szTempKMLFileStatic); } catch { MessageBox.Show("Could not write KML file for google earth. Aborting!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error); bErrorOnLoad = true; return; } } else { MessageBox.Show("Could not write KML file for google earth. Aborting!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error); bErrorOnLoad = true; return; } // Init some never-changing form fields textBoxLocalPubPath.Text = szFilePathPub; // Load flight plans //if (gconffixCurrent.bLoadFlightPlans) // LoadFlightPlans(); // Online Update Check //if (gconffixCurrent.bCheckForUpdates) // checkForProgramUpdate(); } private void Form1_Load(object sender, EventArgs e) { if (bErrorOnLoad) return; } private void Form1_Shown(object sender, EventArgs e) { if (bErrorOnLoad) { bClose = true; Close(); } else { Hide(); lock (lockListenerControl) { listener.Start(); listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener); //bServerUp = true; } globalConnect(); } } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { if (!bClose) { e.Cancel = true; safeHideMainDialog(); } } private void Form1_FormClosed(object sender, FormClosedEventArgs e) { if (bErrorOnLoad) return; notifyIconMain.ContextMenuStrip = null; // Save xml document in memory to config file on disc xmlwSeetingsFile = new XmlTextWriter(szUserAppPath + "\\settings.cfg", null); xmldSettings.PreserveWhitespace = true; xmldSettings.Save(xmlwSeetingsFile); xmlwSeetingsFile.Flush(); xmlwSeetingsFile.Close(); xmldSettings = null; // Disconnect with FSX lock (lockChConf) { gconfchCurrent.bEnabled = false; } globalDisconnect(); // Stop server lock (lockListenerControl) { //bServerUp = false; listener.Stop(); listener.Abort(); timerIPAddressRefresh.Stop(); } // Delete temporary KML file if (File.Exists(szFilePathPub + "\\fsxget.kml")) { try { File.Delete(szFilePathPub + "\\fsxget.kml"); } catch { } } if (File.Exists(szAppPath + "\\SimConnect.cfg")) { try { File.Delete(szAppPath + "\\SimConnect.cfg"); } catch { } } } protected override void DefWndProc(ref Message m) { if (m.Msg == WM_USER_SIMCONNECT) { if (simconnect != null) { try { simconnect.ReceiveMessage(); } catch { #if DEBUG safeShowBalloonTip(3, "Error", "Error receiving data from FSX!", ToolTipIcon.Error); #endif } } } else base.DefWndProc(ref m); } #endregion #region FSX Connection Object lock_ConnectThread = new Object(); String text; public void openConnectionThreadFunction() { while (simconnect == null) { try { simconnect = new SimConnect(text, IntPtr.Zero, WM_USER_SIMCONNECT, null, 0); } catch { } if (simconnect == null) Thread.Sleep(2000); } } private bool openConnection() { if (thrConnect.ThreadState == ThreadState.Unstarted) { thrConnect.Start(); return false; } else if (thrConnect.ThreadState == ThreadState.Stopped) { if (simconnect != null) { try { simconnect.Dispose(); simconnect = null; simconnect = new SimConnect(Text, this.Handle, WM_USER_SIMCONNECT, null, 0); } catch { return false; } if (initDataRequest()) return true; else { simconnect = null; return false; } } else { thrConnect = new Thread(new ThreadStart(openConnectionThreadFunction)); thrConnect.Start(); return false; } } else return false; } private void closeConnection() { if (simconnect != null) { simconnect.Dispose(); simconnect = null; } } private bool initDataRequest() { try { // listen to connect and quit msgs simconnect.OnRecvOpen += new SimConnect.RecvOpenEventHandler(simconnect_OnRecvOpen); simconnect.OnRecvQuit += new SimConnect.RecvQuitEventHandler(simconnect_OnRecvQuit); // listen to exceptions simconnect.OnRecvException += new SimConnect.RecvExceptionEventHandler(simconnect_OnRecvException); // define a data structure simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "Title", null, SIMCONNECT_DATATYPE.STRING256, 0.0f, SimConnect.SIMCONNECT_UNUSED); simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "ATC Type", null, SIMCONNECT_DATATYPE.STRING32, 0.0f, SimConnect.SIMCONNECT_UNUSED); simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "ATC Model", null, SIMCONNECT_DATATYPE.STRING32, 0.0f, SimConnect.SIMCONNECT_UNUSED); simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "ATC ID", null, SIMCONNECT_DATATYPE.STRING32, 0.0f, SimConnect.SIMCONNECT_UNUSED); simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "ATC Airline", null, SIMCONNECT_DATATYPE.STRING64, 0.0f, SimConnect.SIMCONNECT_UNUSED); simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "ATC Flight Number", null, SIMCONNECT_DATATYPE.STRING32, 0.0f, SimConnect.SIMCONNECT_UNUSED); simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "Plane Latitude", "degrees", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED); simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "Plane Longitude", "degrees", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED); simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "Plane Altitude", "meters", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED); simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "Ground Velocity", "knots", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED); simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "Velocity World Y", "meter per second", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED); //simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "Velocity World X", "meter per second", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED); //simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "Velocity World Y", "meter per second", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED); //simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "Velocity World Z", "meter per second", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED); simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "Absolute Time", "seconds", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED); // IMPORTANT: register it with the simconnect managed wrapper marshaller // if you skip this step, you will only receive a uint in the .dwData field. simconnect.RegisterDataDefineStruct<StructBasicMovingSceneryObject>(DEFINITIONS.StructBasicMovingSceneryObject); // catch a simobject data request simconnect.OnRecvSimobjectDataBytype += new SimConnect.RecvSimobjectDataBytypeEventHandler(simconnect_OnRecvSimobjectDataBytype); return true; } catch (COMException ex) { safeShowBalloonTip(3000, Text, "FSX Exception!\n\n" + ex.Message, ToolTipIcon.Error); return false; } } void simconnect_OnRecvOpen(SimConnect sender, SIMCONNECT_RECV_OPEN data) { lock (lockUserAircraftID) { bUserAircraftIDSet = false; } if (gconffixCurrent.bQueryUserAircraft) timerQueryUserAircraft.Start(); if (gconffixCurrent.bQueryUserPath) timerQueryUserPath.Start(); if (gconffixCurrent.bUserPathPrediction) timerUserPrediction.Start(); if (gconffixCurrent.bQueryAIObjects) { if (gconffixCurrent.bQueryAIAircrafts) timerQueryAIAircrafts.Start(); if (gconffixCurrent.bQueryAIHelicopters) timerQueryAIHelicopters.Start(); if (gconffixCurrent.bQueryAIBoats) timerQueryAIBoats.Start(); if (gconffixCurrent.bQueryAIGroundUnits) timerQueryAIGroundUnits.Start(); } timerIPAddressRefresh_Tick(null, null); timerIPAddressRefresh.Start(); } void simconnect_OnRecvQuit(SimConnect sender, SIMCONNECT_RECV data) { globalDisconnect(); if (gconffixCurrent.bExitOnFsxExit && isFsxStartActivated()) { bClose = true; Close(); } } void simconnect_OnRecvException(SimConnect sender, SIMCONNECT_RECV_EXCEPTION data) { safeShowBalloonTip(3000, Text, "FSX Exception!", ToolTipIcon.Error); } void simconnect_OnRecvSimobjectDataBytype(SimConnect sender, SIMCONNECT_RECV_SIMOBJECT_DATA_BYTYPE data) { if (data.dwentrynumber == 0 && data.dwoutof == 0) return; DataRequestReturnObject drroTemp; drroTemp.bmsoObject = (StructBasicMovingSceneryObject)data.dwData[0]; drroTemp.uiObjectID = data.dwObjectID; drroTemp.szCoursePrediction = ""; drroTemp.ppsPredictionPoints = null; switch ((DATA_REQUESTS)data.dwRequestID) { case DATA_REQUESTS.REQUEST_USER_AIRCRAFT: case DATA_REQUESTS.REQUEST_USER_PATH: case DATA_REQUESTS.REQUEST_USER_PREDICTION: lock (lockUserAircraftID) { bUserAircraftIDSet = true; uiUserAircraftID = drroTemp.uiObjectID; } switch ((DATA_REQUESTS)data.dwRequestID) { case DATA_REQUESTS.REQUEST_USER_AIRCRAFT: lock (lockKmlUserAircraft) { suadCurrent = drroTemp.bmsoObject; } break; case DATA_REQUESTS.REQUEST_USER_PATH: lock (lockKmlUserPath) { szKmlUserAircraftPath += drroTemp.bmsoObject.dLongitude.ToString().Replace(",", ".") + "," + drroTemp.bmsoObject.dLatitude.ToString().Replace(",", ".") + "," + drroTemp.bmsoObject.dAltitude.ToString().Replace(",", ".") + "\n"; } break; case DATA_REQUESTS.REQUEST_USER_PREDICTION: lock (lockKmlPredictionPoints) { if (!ppPos1.bInitialized) { ppPos1.dLong = drroTemp.bmsoObject.dLongitude; ppPos1.dLat = drroTemp.bmsoObject.dLatitude; ppPos1.dAlt = drroTemp.bmsoObject.dAltitude; ppPos1.dTime = drroTemp.bmsoObject.dTime; ppPos1.bInitialized = true; return; } else { if (!ppPos2.bInitialized) { ppPos2.dLong = drroTemp.bmsoObject.dLongitude; ppPos2.dLat = drroTemp.bmsoObject.dLatitude; ppPos2.dAlt = drroTemp.bmsoObject.dAltitude; ppPos2.dTime = drroTemp.bmsoObject.dTime; ppPos2.bInitialized = true; } else { ppPos1 = ppPos2; ppPos2.dLong = drroTemp.bmsoObject.dLongitude; ppPos2.dLat = drroTemp.bmsoObject.dLatitude; ppPos2.dAlt = drroTemp.bmsoObject.dAltitude; ppPos2.dTime = drroTemp.bmsoObject.dTime; //ppPos2.bInitialized = true; } } if (ppPos1.dTime != ppPos2.dTime && ppPos1.bInitialized && ppPos2.bInitialized) { lock (lockKmlUserPrediction) { szKmlUserPrediction = drroTemp.bmsoObject.dLongitude.ToString().Replace(",", ".") + "," + drroTemp.bmsoObject.dLatitude.ToString().Replace(",", ".") + "," + drroTemp.bmsoObject.dAltitude.ToString().Replace(",", ".") + "\n"; listKmlPredictionPoints.Clear(); for (uint n = 0; n < gconffixCurrent.dPredictionTimes.GetLength(0); n++) { double dLongNew = 0.0, dLatNew = 0.0, dAltNew = 0.0; calcPositionByTime(ref ppPos1, ref ppPos2, gconffixCurrent.dPredictionTimes[n], ref dLatNew, ref dLongNew, ref dAltNew); PathPositionStored ppsTemp; ppsTemp.dLat = dLatNew; ppsTemp.dLong = dLongNew; ppsTemp.dAlt = dAltNew; ppsTemp.dTime = gconffixCurrent.dPredictionTimes[n]; listKmlPredictionPoints.Add(ppsTemp); szKmlUserPrediction += dLongNew.ToString().Replace(",", ".") + "," + dLatNew.ToString().Replace(",", ".") + "," + dAltNew.ToString().Replace(",", ".") + "\n"; } } } } break; } break; case DATA_REQUESTS.REQUEST_AI_PLANE: case DATA_REQUESTS.REQUEST_AI_HELICOPTER: case DATA_REQUESTS.REQUEST_AI_BOAT: case DATA_REQUESTS.REQUEST_AI_GROUND: lock (lockUserAircraftID) { if (bUserAircraftIDSet && (drroTemp.uiObjectID == uiUserAircraftID)) return; } switch ((DATA_REQUESTS)data.dwRequestID) { case DATA_REQUESTS.REQUEST_AI_PLANE: processDataRequestResultAlternatingly(data.dwentrynumber, data.dwoutof, ref drrAIPlanes, ref lockDrrAiPlanes, ref drroTemp, gconffixCurrent.bPredictAIAircrafts, gconffixCurrent.bPredictPointsAIAircrafts); break; case DATA_REQUESTS.REQUEST_AI_HELICOPTER: processDataRequestResultAlternatingly(data.dwentrynumber, data.dwoutof, ref drrAIHelicopters, ref lockDrrAiHelicopters, ref drroTemp, gconffixCurrent.bPredictAIHelicopters, gconffixCurrent.bPredictPointsAIHelicopters); break; case DATA_REQUESTS.REQUEST_AI_BOAT: processDataRequestResultAlternatingly(data.dwentrynumber, data.dwoutof, ref drrAIBoats, ref lockDrrAiBoats, ref drroTemp, gconffixCurrent.bPredictAIBoats, gconffixCurrent.bPredictPointsAIBoats); break; case DATA_REQUESTS.REQUEST_AI_GROUND: processDataRequestResultAlternatingly(data.dwentrynumber, data.dwoutof, ref drrAIGround, ref lockDrrAiGround, ref drroTemp, gconffixCurrent.bPredictAIGroundUnits, gconffixCurrent.bPredictPointsAIGroundUnits); break; } break; default: #if DEBUG safeShowBalloonTip(3000, Text, "Received unknown data from FSX!", ToolTipIcon.Warning); #endif break; } } Thread thrConnect; private void globalConnect() { lock (lockChConf) { if (!gconfchCurrent.bEnabled) return; } notifyIconMain.Icon = icActive; notifyIconMain.Text = Text + "(Waiting for connection...)"; if (bConnected) return; lock (lockKmlUserAircraft) { szKmlUserAircraftPath = ""; uiUserAircraftID = 0; } if (!timerFSXConnect.Enabled) timerFSXConnect.Start(); } private void globalDisconnect() { if (bConnected) { bConnected = false; // Stop all query timers timerQueryUserAircraft.Stop(); timerQueryUserPath.Stop(); timerUserPrediction.Stop(); timerQueryAIAircrafts.Stop(); timerQueryAIHelicopters.Stop(); timerQueryAIBoats.Stop(); timerQueryAIGroundUnits.Stop(); closeConnection(); lock (lockChConf) { if (gconfchCurrent.bEnabled) safeShowBalloonTip(1000, Text, "Disconnected from FSX!", ToolTipIcon.Info); } } lock (lockChConf) { if (gconfchCurrent.bEnabled) { if (!timerFSXConnect.Enabled) { timerFSXConnect.Start(); notifyIconMain.Icon = icActive; notifyIconMain.Text = Text + "(Waiting for connection...)"; } } else { if (timerFSXConnect.Enabled) { timerFSXConnect.Stop(); thrConnect.Abort(); if (thrConnect.ThreadState != ThreadState.Unstarted) thrConnect.Join(); closeConnection(); } notifyIconMain.Icon = icDisabled; notifyIconMain.Text = Text + "(Disabled)"; } } } #endregion #region Helper Functions #region Old Version //void processDataRequestResultAlternatingly(uint entryNumber, uint entriesCount, ref DataRequestReturn currentRequestStructure, ref object relatedLock, ref StructBasicMovingSceneryObject receivedData, ref String processedData) //{ // lock (relatedLock) // { // if (entryNumber <= currentRequestStructure.uiLastEntryNumber) // { // if (currentRequestStructure.uiCurrentDataSet == 1) // { // currentRequestStructure.szData2 = ""; // currentRequestStructure.uiCurrentDataSet = 2; // } // else // { // currentRequestStructure.szData1 = ""; // currentRequestStructure.uiCurrentDataSet = 1; // } // } // currentRequestStructure.uiLastEntryNumber = entryNumber; // if (currentRequestStructure.uiCurrentDataSet == 1) // currentRequestStructure.szData1 += processedData; // else // currentRequestStructure.szData2 += processedData; // if (entryNumber == entriesCount) // { // if (currentRequestStructure.uiCurrentDataSet == 1) // { // currentRequestStructure.szData2 = ""; // currentRequestStructure.uiCurrentDataSet = 2; // } // else // { // currentRequestStructure.szData1 = ""; // currentRequestStructure.uiCurrentDataSet = 1; // } // currentRequestStructure.uiLastEntryNumber = 0; // } // } //} #endregion void processDataRequestResultAlternatingly(uint entryNumber, uint entriesCount, ref DataRequestReturn currentRequestStructure, ref object relatedLock, ref DataRequestReturnObject receivedData, bool bCoursePrediction, bool bPredictionPoints) { lock (relatedLock) { // In case last data request return aborted unnormally and we're dealing with a new result, switch lists if (entryNumber <= currentRequestStructure.uiLastEntryNumber) { if (currentRequestStructure.uiCurrentDataSet == 1) currentRequestStructure.uiCurrentDataSet = 2; else currentRequestStructure.uiCurrentDataSet = 1; } List<DataRequestReturnObject> listCurrent = currentRequestStructure.uiCurrentDataSet == 1 ? currentRequestStructure.listFirst : currentRequestStructure.listSecond; List<DataRequestReturnObject> listOld = currentRequestStructure.uiCurrentDataSet == 1 ? currentRequestStructure.listSecond : currentRequestStructure.listFirst; // In case we have switched lists, clear new list and resize if necessary if (currentRequestStructure.bClearOnNextRun) { currentRequestStructure.bClearOnNextRun = false; listCurrent.Clear(); if (listCurrent.Capacity < entriesCount) listCurrent.Capacity = (int)((double)entriesCount * 1.1); } // Calculate course prediction if (bCoursePrediction) { foreach (DataRequestReturnObject drroTemp in listOld) { if (drroTemp.uiObjectID == receivedData.uiObjectID) { if (drroTemp.bmsoObject.dTime != receivedData.bmsoObject.dTime) { if (bPredictionPoints) receivedData.ppsPredictionPoints = new PathPositionStored[gconffixCurrent.dPredictionTimes.GetLength(0)]; receivedData.szCoursePrediction = receivedData.bmsoObject.dLongitude.ToString().Replace(",", ".") + "," + receivedData.bmsoObject.dLatitude.ToString().Replace(",", ".") + "," + receivedData.bmsoObject.dAltitude.ToString().Replace(",", ".") + "\n"; for (uint n = 0; n < gconffixCurrent.dPredictionTimes.GetLength(0); n++) { PathPosition ppOld, ppCurrent; double dLongNew = 0.0, dLatNew = 0.0, dAltNew = 0.0; ppOld.bInitialized = true; ppOld.dLat = drroTemp.bmsoObject.dLatitude; ppOld.dLong = drroTemp.bmsoObject.dLongitude; ppOld.dAlt = drroTemp.bmsoObject.dAltitude; ppOld.dTime = drroTemp.bmsoObject.dTime; ppCurrent.bInitialized = true; ppCurrent.dLat = receivedData.bmsoObject.dLatitude; ppCurrent.dLong = receivedData.bmsoObject.dLongitude; ppCurrent.dAlt = receivedData.bmsoObject.dAltitude; ppCurrent.dTime = receivedData.bmsoObject.dTime; calcPositionByTime(ref ppOld, ref ppCurrent, gconffixCurrent.dPredictionTimes[n], ref dLatNew, ref dLongNew, ref dAltNew); receivedData.szCoursePrediction += dLongNew.ToString().Replace(",", ".") + "," + dLatNew.ToString().Replace(",", ".") + "," + dAltNew.ToString().Replace(",", ".") + "\n"; if (bPredictionPoints) { PathPositionStored ppsTemp; ppsTemp.dLat = dLatNew; ppsTemp.dLong = dLongNew; ppsTemp.dAlt = dAltNew; ppsTemp.dTime = gconffixCurrent.dPredictionTimes[n]; receivedData.ppsPredictionPoints[n] = ppsTemp; } } } else { receivedData.szCoursePrediction = drroTemp.szCoursePrediction; receivedData.ppsPredictionPoints = drroTemp.ppsPredictionPoints; } break; } } } // Set current entry number currentRequestStructure.uiLastEntryNumber = entryNumber; // Insert new data into the list if (currentRequestStructure.uiCurrentDataSet == 1) currentRequestStructure.listFirst.Add(receivedData); else currentRequestStructure.listSecond.Add(receivedData); // If this is the last entry from the current return, switch lists, so that http server can work with the just completed list if (entryNumber == entriesCount) { if (currentRequestStructure.uiCurrentDataSet == 1) currentRequestStructure.uiCurrentDataSet = 2; else currentRequestStructure.uiCurrentDataSet = 1; currentRequestStructure.uiLastEntryNumber = 0; currentRequestStructure.bClearOnNextRun = true; } } } private List<DataRequestReturnObject> GetCurrentList(ref DataRequestReturn drrnCurrent) { if (drrnCurrent.uiCurrentDataSet == 1) return drrnCurrent.listSecond; else return drrnCurrent.listFirst; } private void safeShowBalloonTip(int timeout, String tipTitle, String tipText, ToolTipIcon tipIcon) { lock (lockChConf) { if (!gconfchCurrent.bShowBalloons) return; } notifyIconMain.ShowBalloonTip(timeout, tipTitle, tipText, tipIcon); } private void safeShowMainDialog(int iTab) { notifyIconMain.ContextMenuStrip = null; ConfigMirrorToForm(); // Check startup options if (isAutoStartActivated()) radioButton8.Checked = true; else if (isFsxStartActivated() && szPathFSX != "") radioButton9.Checked = true; else radioButton10.Checked = true; if (szPathFSX == "") radioButton9.Enabled = false; bRestartRequired = false; tabControl1.SelectedIndex = iTab; Show(); } private void safeHideMainDialog() { notifyIconMain.ContextMenuStrip = contextMenuStripNotifyIcon; Hide(); } private void clearDrrStructure(ref DataRequestReturn drrToClear) { if (drrToClear.listFirst == null) drrToClear.listFirst = new List<DataRequestReturnObject>(); if (drrToClear.listSecond == null) drrToClear.listSecond = new List<DataRequestReturnObject>(); drrToClear.listFirst.Clear(); drrToClear.listSecond.Clear(); drrToClear.uiLastEntryNumber = 0; drrToClear.uiCurrentDataSet = 1; drrToClear.bClearOnNextRun = true; } private void clearPPStructure(ref PathPosition ppToClear) { ppToClear.bInitialized = false; ppToClear.dAlt = ppToClear.dLong = ppToClear.dAlt = 0.0; } private bool IsLocalHostIP(IPAddress ipaRequest) { lock (lockIPAddressList) { if (ipalLocal1 != null) { foreach (IPAddress ipaTemp in ipalLocal1) { if (ipaTemp.Equals(ipaRequest)) return true; } } if (ipalLocal2 != null) { foreach (IPAddress ipaTemp in ipalLocal2) { if (ipaTemp.Equals(ipaRequest)) return true; } } } return false; } private bool CompileKMLStartUpFileDynamic(String szIPAddress, ref String szResult) { try { string szTempKMLFile = File.ReadAllText(szFilePathData + "\\fsxget.template"); szTempKMLFile = szTempKMLFile.Replace("%FSXU%", gconffixCurrent.bQueryUserAircraft ? File.ReadAllText(szFilePathData + "\\fsxget-fsxu.part") : ""); szTempKMLFile = szTempKMLFile.Replace("%FSXP%", gconffixCurrent.bQueryUserPath ? File.ReadAllText(szFilePathData + "\\fsxget-fsxp.part") : ""); szTempKMLFile = szTempKMLFile.Replace("%FSXPRE%", gconffixCurrent.bUserPathPrediction ? File.ReadAllText(szFilePathData + "\\fsxget-fsxpre.part") : ""); szTempKMLFile = szTempKMLFile.Replace("%FSXAIP%", gconffixCurrent.bQueryAIAircrafts ? File.ReadAllText(szFilePathData + "\\fsxget-fsxaip.part") : ""); szTempKMLFile = szTempKMLFile.Replace("%FSXAIH%", gconffixCurrent.bQueryAIHelicopters ? File.ReadAllText(szFilePathData + "\\fsxget-fsxaih.part") : ""); szTempKMLFile = szTempKMLFile.Replace("%FSXAIB%", gconffixCurrent.bQueryAIBoats ? File.ReadAllText(szFilePathData + "\\fsxget-fsxaib.part") : ""); szTempKMLFile = szTempKMLFile.Replace("%FSXAIG%", gconffixCurrent.bQueryAIGroundUnits ? File.ReadAllText(szFilePathData + "\\fsxget-fsxaig.part") : ""); //szTempKMLFile = szTempKMLFile.Replace("%FSXFLIGHTPLAN%", gconffixCurrent.bLoadFlightPlans ? File.ReadAllText(szFilePathData + "\\fsxget-fsxflightplan.part") : ""); szTempKMLFile = szTempKMLFile.Replace("%PATH%", "http://" + szIPAddress + ":" + gconffixCurrent.iServerPort.ToString()); szResult = szTempKMLFile; return true; } catch { return false; } } private bool CompileKMLStartUpFileStatic(String szIPAddress, ref String szResult) { try { string szTempKMLFile = File.ReadAllText(szFilePathData + "\\fsxgets.template"); //szTempKMLFile = szTempKMLFile.Replace("%FSXU%", ""); //szTempKMLFile = szTempKMLFile.Replace("%FSXP%", ""); //szTempKMLFile = szTempKMLFile.Replace("%FSXPRE%", ""); //szTempKMLFile = szTempKMLFile.Replace("%FSXAIP%", ""); //szTempKMLFile = szTempKMLFile.Replace("%FSXAIH%", ""); //szTempKMLFile = szTempKMLFile.Replace("%FSXAIB%", ""); //szTempKMLFile = szTempKMLFile.Replace("%FSXAIG%", ""); //szTempKMLFile = szTempKMLFile.Replace("%FSXFLIGHTPLAN%", gconffixCurrent.bLoadFlightPlans ? File.ReadAllText(szFilePathData + "\\fsxget-fsxflightplan.part") : ""); //szTempKMLFile = szTempKMLFile.Replace("%PATH%", "http://" + szIPAddress + ":" + gconffixCurrent.iServerPort.ToString()); szResult = szTempKMLFile; return true; } catch { return false; } } private void UpdateCheckBoxStates() { checkBoxQueryAIObjects_CheckedChanged(null, null); radioButton7_CheckedChanged(null, null); radioButton6_CheckedChanged(null, null); radioButton8_CheckedChanged(null, null); radioButton9_CheckedChanged(null, null); radioButton10_CheckedChanged(null, null); } private void UpdateButtonStates() { if (listBoxPathPrediction.SelectedItems.Count == 1) button2.Enabled = true; else button2.Enabled = false; } private double ConvertDegToDouble(String szDeg) { String szTemp = szDeg; szTemp = szTemp.Replace("N", "+"); szTemp = szTemp.Replace("S", "-"); szTemp = szTemp.Replace("E", "+"); szTemp = szTemp.Replace("W", "-"); szTemp = szTemp.Replace(" ", ""); szTemp = szTemp.Replace("\"", ""); szTemp = szTemp.Replace("'", "/"); szTemp = szTemp.Replace("°", "/"); char[] szSeperator = { '/' }; String[] szParts = szTemp.Split(szSeperator); if (szParts.GetLength(0) != 3) { throw new System.Exception("Wrong coordinate format!"); } double d1 = System.Double.Parse(szParts[0], System.Globalization.NumberFormatInfo.InvariantInfo); int iSign = Math.Sign(d1); d1 = Math.Abs(d1); double d2 = System.Double.Parse(szParts[1], System.Globalization.NumberFormatInfo.InvariantInfo); double d3 = System.Double.Parse(szParts[2], System.Globalization.NumberFormatInfo.InvariantInfo); return iSign * (d1 + (d2 * 60.0 + d3) / 3600.0); } private bool isAutoStartActivated() { string szRun = (string)Registry.GetValue(szRegKeyRun, AssemblyTitle, ""); return (szRun.ToLower() == Application.ExecutablePath.ToLower()); } private bool AutoStartActivate() { try { Registry.SetValue(szRegKeyRun, AssemblyTitle, Application.ExecutablePath); } catch { return false; } return true; } private bool AutoStartDeactivate() { try { RegistryKey regkTemp = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run", true); regkTemp.DeleteValue(AssemblyTitle); } catch { return false; } return true; } private bool isFsxStartActivated() { String szAppDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Microsoft\\FSX"; if (File.Exists(szAppDataFolder + "\\EXE.xml")) { XmlTextReader xmlrFsxFile = new XmlTextReader(szAppDataFolder + "\\EXE.xml"); XmlDocument xmldSettings = new XmlDocument(); try { xmldSettings.Load(xmlrFsxFile); } catch { xmlrFsxFile.Close(); xmlrFsxFile = null; return false; } xmlrFsxFile.Close(); xmlrFsxFile = null; try { for (XmlNode xmlnTemp = xmldSettings["SimBase.Document"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling) { if (xmlnTemp.Name.ToLower() == "launch.addon") { try { if (Path.GetFullPath(xmlnTemp["Path"].InnerText).ToLower() == (Path.GetFullPath(szAppPath) + "\\starter.exe").ToLower()) return true; } catch { } } } return false; } catch { return false; } } else return false; } private bool FsxStartActivate() { String szAppDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Microsoft\\FSX"; if (File.Exists(szAppDataFolder + "\\EXE.xml")) { bool bLoadError = false; XmlTextReader xmlrFsxFile = new XmlTextReader(szAppDataFolder + "\\EXE.xml"); XmlDocument xmldSettings = new XmlDocument(); try { xmldSettings.Load(xmlrFsxFile); } catch { bLoadError = true; } xmlrFsxFile.Close(); xmlrFsxFile = null; // TODO: One could improve this function not just replacing the document if ["SimBase.Document"] doesn't exist, // but just find and use the document's root element whatever it may be called. This would increase compatibility // with future FS version. (Same should be done for other functions dealing with this document) if (bLoadError || xmldSettings["SimBase.Document"] == null) { try { File.Delete(szAppDataFolder + "\\EXE.xml"); return FsxStartActivate(); } catch { return false; } } else { if (xmldSettings["SimBase.Document"]["Disabled"] == null) { XmlNode nodeTemp = xmldSettings.CreateElement("Disabled"); nodeTemp.InnerText = "False"; xmldSettings["SimBase.Document"].AppendChild(nodeTemp); } else if (xmldSettings["SimBase.Document"]["Disabled"].InnerText.ToLower() == "true") xmldSettings["SimBase.Document"]["Disabled"].InnerText = "False"; xmlrFsxFile = new XmlTextReader(szAppPath + "\\data\\EXE.xml"); XmlDocument xmldTemplate = new XmlDocument(); xmldTemplate.Load(xmlrFsxFile); xmlrFsxFile.Close(); xmlrFsxFile = null; XmlNode nodeFsxget = xmldTemplate["SimBase.Document"]["Launch.Addon"]; XmlNode nodeTemp2 = xmldSettings.CreateElement(nodeFsxget.Name); nodeTemp2.InnerXml = nodeFsxget.InnerXml.Replace("%PATH%", Path.GetFullPath(szAppPath) + "\\starter.exe"); xmldSettings["SimBase.Document"].AppendChild(nodeTemp2); try { File.Delete(szAppDataFolder + "\\EXE.xml"); xmldSettings.Save(szAppDataFolder + "\\EXE.xml"); return true; } catch { return false; } } } else { try { StreamWriter swFsxFile = File.CreateText(szAppDataFolder + "\\EXE.xml"); StreamReader srFsxFileTemplate = File.OpenText(szAppPath + "\\data\\EXE.xml"); swFsxFile.Write(srFsxFileTemplate.ReadToEnd().Replace("%PATH%", Path.GetFullPath(szAppPath) + "\\starter.exe")); swFsxFile.Flush(); swFsxFile.Close(); swFsxFile.Dispose(); srFsxFileTemplate.Close(); srFsxFileTemplate.Dispose(); return true; } catch { return false; } } } private bool FsxStartDeactivate() { String szAppDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Microsoft\\FSX"; if (File.Exists(szAppDataFolder + "\\EXE.xml")) { XmlTextReader xmlrFsxFile = new XmlTextReader(szAppDataFolder + "\\EXE.xml"); XmlDocument xmldSettings = new XmlDocument(); xmldSettings.Load(xmlrFsxFile); xmlrFsxFile.Close(); xmlrFsxFile = null; try { bool bChanges = false; for (XmlNode xmlnTemp = xmldSettings["SimBase.Document"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling) { if (xmlnTemp.Name.ToLower() == "launch.addon") { if (xmlnTemp["Path"] != null) { if (Path.GetFullPath(xmlnTemp["Path"].InnerText).ToLower() == (Path.GetFullPath(szAppPath) + "\\starter.exe").ToLower()) { xmldSettings["SimBase.Document"].RemoveChild(xmlnTemp); bChanges = true; } } } } if (bChanges) { try { File.Delete(szAppDataFolder + "\\EXE.xml"); xmldSettings.Save(szAppDataFolder + "\\EXE.xml"); } catch { return false; } } return true; } catch { return true; } } else return true; } private double getValueInUnit(double dValueInMeters, UnitType Unit) { switch (Unit) { case UnitType.METERS: return dValueInMeters; case UnitType.FEET: return dValueInMeters * 3.2808399; default: throw new Exception("Unknown unit type"); } } private double getValueInCurrentUnit(double dValueInMeters) { return getValueInUnit(dValueInMeters, gconffixCurrent.utUnits); } private String getCurrentUnitNameShort() { switch (gconffixCurrent.utUnits) { case UnitType.METERS: return "m"; case UnitType.FEET: return "ft"; default: return "--"; } } private String getCurrentUnitName() { switch (gconffixCurrent.utUnits) { case UnitType.METERS: return "Meters"; case UnitType.FEET: return "Feet"; default: return "Unknown Unit"; } } private void RestartApp() { Program.bRestart = true; bClose = true; Close(); } protected static byte[] BitmapToPngBytes(Bitmap bmp) { byte[] bufferPng = null; if (bmp != null) { byte[] buffer = new byte[1024 + bmp.Height * bmp.Width * 4]; MemoryStream s = new MemoryStream(buffer); bmp.Save(s, System.Drawing.Imaging.ImageFormat.Png); int nSize = (int)s.Position; s.Close(); bufferPng = new byte[nSize]; for (int i = 0; i < nSize; i++) bufferPng[i] = buffer[i]; } return bufferPng; } #endregion #region Calucaltion private void calcPositionByTime(ref PathPosition ppOld, ref PathPosition ppNew, double dSeconds, ref double dResultLat, ref double dResultLong, ref double dResultAlt) { double dTimeElapsed = ppNew.dTime - ppOld.dTime; double dScale = dSeconds / dTimeElapsed; dResultLat = ppNew.dLat + dScale * (ppNew.dLat - ppOld.dLat); dResultLong = ppNew.dLong + dScale * (ppNew.dLong - ppOld.dLong); dResultAlt = ppNew.dAlt + dScale * (ppNew.dAlt - ppOld.dAlt); } #region Old Calculation //private void calcPositionByTime(double dLong, double dLat, double dAlt, double dSpeedX, double dSpeedY, double dSpeedZ, double dSeconds, ref double dResultLat, ref double dResultLong, ref double dResultAlt) //{ // const double dRadEarth = 6371000.8; // dResultLat = dLat + dSpeedZ * dSeconds / 1852.0; // dResultAlt = dAlt + dSpeedY * dSeconds; // double dLatMiddle = dLat + (dSpeedZ * dSeconds / 1852.0 / 2.0); // dResultLong = dLong + (dSpeedX * dSeconds / (2.0 * Math.PI * dRadEarth / 360.0 * Math.Cos(dLatMiddle * Math.PI / 180.0))); // //double dNewPosX = dSpeedX * dSeconds; // //double dNewPosY = dSpeedY * dSeconds; // //double dNewPosZ = dSpeedZ * dSeconds; // //double dCosAngle = (dNewPosY * 1.0 + dNewPosZ * 0.0) / (Math.Sqrt(Math.Pow(dNewPosY, 2.0) + Math.Pow(dNewPosZ, 2.0)) * Math.Sqrt(Math.Pow(0.0, 2.0) + Math.Pow(1.0, 2.0))); // //dResultLat = dLat + Math.Acos(dCosAngle / 180.0 * Math.PI); // //// East-West-Position // //dCosAngle = (dNewPosX * 1.0 + dNewPosY * 0.0) / (Math.Sqrt(Math.Pow(dNewPosX, 2.0) + Math.Pow(dNewPosY, 2.0)) * Math.Sqrt(Math.Pow(1.0, 2.0) + Math.Pow(0.0, 2.0))); // //dResultLong = dLong + Math.Acos(dCosAngle / 180.0 * Math.PI); // //// Altitude // //dResultAlt = dAlt + Math.Sqrt(Math.Pow(dNewPosX, 2.0) + Math.Pow(dNewPosY, 2.0) + Math.Pow(dNewPosZ, 2.0)); // //const double dRadEarth = 6371000.8; // ////x' = cos(theta)*x - sin(theta)*y // ////y' = sin(theta)*x + cos(theta)*y // //// Calculate North-South-Position // //double dTempX = dAlt + dRadEarth; // //double dTempY = 0.0; // //double dPosY = Math.Cos(dLat) * dTempX - Math.Sin(dLat) * dTempY; // //double dPosZ = Math.Sin(dLat) * dTempX - Math.Cos(dLat) * dTempY; // //// Calculate East-West-Position // //dTempX = dAlt + dRadEarth; // //dTempY = 0; // //double dPosX = Math.Cos(dLong) * dTempX - Math.Sin(dLong) * dTempY; // ////dPosZ = Math.Sin(dLat) * dTempX - Math.Cos(dLat) * dTempY; // //// Normalize // //double dLength = Math.Sqrt(Math.Pow(dPosX, 2.0) + Math.Pow(dPosY, 2.0) + Math.Pow(dPosZ, 2.0)); // //dPosX = dPosX / dLength * (dAlt + dRadEarth); // //dPosY = dPosY / dLength * (dAlt + dRadEarth); // //dPosZ = dPosZ / dLength * (dAlt + dRadEarth); // //double dTest = Math.Sqrt(Math.Pow(dPosX, 2.0) + Math.Pow(dPosY, 2.0) + Math.Pow(dPosZ, 2.0)) - dRadEarth; // //// Calculate position after given time // //double dNewPosX = dPosX + dSpeedX * dSeconds; // //double dNewPosY = dPosY + dSpeedY * dSeconds; // //double dNewPosZ = dPosZ + dSpeedZ * dSeconds; // //// Now again translate into lat-long-coordinates // //// North-South-Position // //double dCosAngle = (dNewPosY * dPosY + dNewPosZ * dPosZ) / (Math.Sqrt(Math.Pow(dNewPosY, 2.0) + Math.Pow(dNewPosZ, 2.0)) * Math.Sqrt(Math.Pow(dPosY, 2.0) + Math.Pow(dPosZ, 2.0))); // //dResultLat = dLat + Math.Acos(dCosAngle / 180.0 * Math.PI); // //// East-West-Position // //dCosAngle = (dNewPosX * dPosX + dNewPosY * dPosY) / (Math.Sqrt(Math.Pow(dNewPosX, 2.0) + Math.Pow(dNewPosY, 2.0)) * Math.Sqrt(Math.Pow(dPosX, 2.0) + Math.Pow(dPosY, 2.0))); // //dResultLong = dLong + Math.Acos(dCosAngle / 180.0 * Math.PI); // //// Altitude // //dResultAlt = Math.Sqrt(Math.Pow(dNewPosX, 2.0) + Math.Pow(dNewPosY, 2.0) + Math.Pow(dNewPosZ, 2.0)) - dRadEarth; //} #endregion #endregion #region Server public void ListenerCallback(IAsyncResult result) { lock (lockListenerControl) { HttpListener listener = (HttpListener)result.AsyncState; if (!listener.IsListening) return; HttpListenerContext context = listener.EndGetContext(result); HttpListenerRequest request = context.Request; HttpListenerResponse response = context.Response; // This code using the objects IsLocal property doesn't work for some reason ... //if (gconffixCurrent.uiServerAccessLevel == 0 && !request.IsLocal) //{ // response.Abort(); // return; //} // ... so I'm using my own code. if (gconffixCurrent.uiServerAccessLevel == 0 && !IsLocalHostIP(request.RemoteEndPoint.Address)) { response.Abort(); return; } byte[] buffer = System.Text.Encoding.UTF8.GetBytes(""); String szHeader = ""; bool bContentSet = false; if (request.Url.PathAndQuery.ToLower().StartsWith("/gfx/scenery/air/")) { String szTemp = request.Url.PathAndQuery.Substring(17); if (szTemp.Length >= 4) { // Cut the .png suffix from the url szTemp = szTemp.Substring(0, szTemp.Length - 4); foreach (ObjectImage aimgCurrent in listImgUnitsAir) { String szTemp2 = HttpUtility.UrlDecode(szTemp); if (aimgCurrent.szTitle.ToLower() == HttpUtility.UrlDecode(szTemp).ToLower()) { buffer = aimgCurrent.bData; szHeader = "image/png"; bContentSet = true; break; } } if (!bContentSet) { buffer = imgNoImage; szHeader = "image/png"; bContentSet = true; } } } else if (request.Url.PathAndQuery.ToLower().StartsWith("/gfx/scenery/water/")) { String szTemp = request.Url.PathAndQuery.Substring(19); if (szTemp.Length >= 4) { // Cut the .png suffix from the url szTemp = szTemp.Substring(0, szTemp.Length - 4); foreach (ObjectImage aimgCurrent in listImgUnitsWater) { String szTemp2 = HttpUtility.UrlDecode(szTemp); if (aimgCurrent.szTitle.ToLower() == HttpUtility.UrlDecode(szTemp).ToLower()) { buffer = aimgCurrent.bData; szHeader = "image/png"; bContentSet = true; break; } } if (!bContentSet) { buffer = imgNoImage; szHeader = "image/png"; bContentSet = true; } } } else if (request.Url.PathAndQuery.ToLower().StartsWith("/gfx/scenery/ground/")) { String szTemp = request.Url.PathAndQuery.Substring(20); if (szTemp.Length >= 4) { // Cut the .png suffix from the url szTemp = szTemp.Substring(0, szTemp.Length - 4); foreach (ObjectImage aimgCurrent in listImgUnitsGround) { String szTemp2 = HttpUtility.UrlDecode(szTemp); if (aimgCurrent.szTitle.ToLower() == HttpUtility.UrlDecode(szTemp).ToLower()) { buffer = aimgCurrent.bData; szHeader = "image/png"; bContentSet = true; break; } } if (!bContentSet) { buffer = imgNoImage; szHeader = "image/png"; bContentSet = true; } } } else if (request.Url.PathAndQuery.ToLower().StartsWith("/gfx/ge/icons/")) { String szTemp = request.Url.PathAndQuery.Substring(14); if (szTemp.Length >= 4) { // Cut the .png suffix from the url szTemp = szTemp.Substring(0, szTemp.Length - 4); buffer = null; foreach (ObjectImage oimgTemp in listIconsGE) { if (oimgTemp.szTitle.ToLower() == szTemp.ToLower()) { szHeader = "image/png"; buffer = oimgTemp.bData; bContentSet = true; break; } } if (!bContentSet) { buffer = imgNoImage; szHeader = "image/png"; bContentSet = true; } } } else if (request.Url.PathAndQuery.ToLower() == "/fsxu.kml") { bContentSet = true; szHeader = "application/vnd.google-earth.kml+xml"; buffer = System.Text.Encoding.UTF8.GetBytes(KmlGenFile(KML_FILES.REQUEST_USER_AIRCRAFT, KML_ACCESS_MODES.MODE_SERVER, true, (uint)gconffixCurrent.iUpdateGEUserAircraft, request.UserHostName)); } else if (request.Url.PathAndQuery.ToLower() == "/fsxp.kml") { bContentSet = true; szHeader = "application/vnd.google-earth.kml+xml"; buffer = System.Text.Encoding.UTF8.GetBytes(KmlGenFile(KML_FILES.REQUEST_USER_PATH, KML_ACCESS_MODES.MODE_SERVER, true, (uint)gconffixCurrent.iUpdateGEUserPath, request.UserHostName)); } else if (request.Url.PathAndQuery.ToLower() == "/fsxpre.kml") { bContentSet = true; szHeader = "application/vnd.google-earth.kml+xml"; buffer = System.Text.Encoding.UTF8.GetBytes(KmlGenFile(KML_FILES.REQUEST_USER_PREDICTION, KML_ACCESS_MODES.MODE_SERVER, true, (uint)gconffixCurrent.iUpdateGEUserPrediction, request.UserHostName)); } else if (request.Url.PathAndQuery.ToLower() == "/fsxaip.kml") { bContentSet = true; szHeader = "application/vnd.google-earth.kml+xml"; buffer = System.Text.Encoding.UTF8.GetBytes(KmlGenFile(KML_FILES.REQUEST_AI_PLANE, KML_ACCESS_MODES.MODE_SERVER, true, (uint)gconffixCurrent.iUpdateGEAIAircrafts, request.UserHostName)); } else if (request.Url.PathAndQuery.ToLower() == "/fsxaih.kml") { bContentSet = true; szHeader = "application/vnd.google-earth.kml+xml"; buffer = System.Text.Encoding.UTF8.GetBytes(KmlGenFile(KML_FILES.REQUEST_AI_HELICOPTER, KML_ACCESS_MODES.MODE_SERVER, true, (uint)gconffixCurrent.iUpdateGEAIHelicopters, request.UserHostName)); } else if (request.Url.PathAndQuery.ToLower() == "/fsxaib.kml") { bContentSet = true; szHeader = "application/vnd.google-earth.kml+xml"; buffer = System.Text.Encoding.UTF8.GetBytes(KmlGenFile(KML_FILES.REQUEST_AI_BOAT, KML_ACCESS_MODES.MODE_SERVER, true, (uint)gconffixCurrent.iUpdateGEAIBoats, request.UserHostName)); } else if (request.Url.PathAndQuery.ToLower() == "/fsxaig.kml") { bContentSet = true; szHeader = "application/vnd.google-earth.kml+xml"; buffer = System.Text.Encoding.UTF8.GetBytes(KmlGenFile(KML_FILES.REQUEST_AI_GROUND, KML_ACCESS_MODES.MODE_SERVER, true, (uint)gconffixCurrent.iUpdateGEAIGroundUnits, request.UserHostName)); } else if (request.Url.PathAndQuery.ToLower() == "/fsxflightplans.kml") { bContentSet = true; szHeader = "application/vnd.google-earth.kml+xml"; buffer = System.Text.Encoding.UTF8.GetBytes(KmlGenFile(KML_FILES.REQUEST_FLIGHT_PLANS, KML_ACCESS_MODES.MODE_SERVER, false, 0, request.UserHostName)); } else if (request.Url.AbsolutePath.ToLower() == "/gfx/ge/label.png") { bContentSet = true; szHeader = "image/png"; buffer = KmlGenAtcLabel(request.QueryString["code"], request.QueryString["fl"], request.QueryString["aircraft"], request.QueryString["speed"], request.QueryString["vspeed"]); } else bContentSet = false; if (bContentSet) { response.AddHeader("Content-type", szHeader); response.ContentLength64 = buffer.Length; System.IO.Stream output = response.OutputStream; output.Write(buffer, 0, buffer.Length); output.Close(); } else { response.StatusCode = 404; response.Close(); } listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener); } } private String KmlGenFile(KML_FILES kmlfWanted, KML_ACCESS_MODES AccessMode, bool bExpires, uint uiSeconds, String szSever) { String szTemp = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><kml xmlns=\"http://earth.google.com/kml/2.1\">" + KmlGetExpireString(bExpires, uiSeconds) + "<Document>"; switch (kmlfWanted) { case KML_FILES.REQUEST_USER_AIRCRAFT: szTemp += KmlGenUserPosition(AccessMode, szSever); break; case KML_FILES.REQUEST_USER_PATH: szTemp += KmlGenUserPath(AccessMode, szSever); break; case KML_FILES.REQUEST_USER_PREDICTION: szTemp += KmlGenUserPrediction(AccessMode, szSever); break; case KML_FILES.REQUEST_AI_PLANE: szTemp += KmlGenAIAircraft(AccessMode, szSever); break; case KML_FILES.REQUEST_AI_HELICOPTER: szTemp += KmlGenAIHelicopter(AccessMode, szSever); break; case KML_FILES.REQUEST_AI_BOAT: szTemp += KmlGenAIBoat(AccessMode, szSever); break; case KML_FILES.REQUEST_AI_GROUND: szTemp += KmlGenAIGroundUnit(AccessMode, szSever); break; //case KML_FILES.REQUEST_FLIGHT_PLANS: // szTemp += KmlGenFlightPlans(AccessMode, szSever); // break; default: break; } szTemp += "</Document></kml>"; return szTemp; } private String KmlGetExpireString(bool bExpires, uint uiSeconds) { if (!bExpires) return ""; DateTime date = DateTime.Now; date = date.AddSeconds(uiSeconds); date = date.ToUniversalTime(); return "<NetworkLinkControl><expires>" + date.ToString("yyyy") + "-" + date.ToString("MM") + "-" + date.ToString("dd") + "T" + date.ToString("HH") + ":" + date.ToString("mm") + ":" + date.ToString("ss") + "Z" + "</expires></NetworkLinkControl>"; } private String KmlGetImageLink(KML_ACCESS_MODES AccessMode, KML_IMAGE_TYPES ImageType, String szTitle, String szServer) { if (AccessMode == KML_ACCESS_MODES.MODE_SERVER) { String szPrefix = ""; switch (ImageType) { case KML_IMAGE_TYPES.AIRCRAFT: szPrefix = "/gfx/scenery/air/"; break; case KML_IMAGE_TYPES.WATER: szPrefix = "/gfx/scenery/water/"; break; case KML_IMAGE_TYPES.GROUND: szPrefix = "/gfx/scenery/ground/"; break; } return "http://" + szServer + szPrefix + szTitle + ".png"; } else { List<ObjectImage> listTemp; switch (ImageType) { case KML_IMAGE_TYPES.AIRCRAFT: listTemp = listImgUnitsAir; break; case KML_IMAGE_TYPES.WATER: listTemp = listImgUnitsWater; break; case KML_IMAGE_TYPES.GROUND: listTemp = listImgUnitsGround; break; default: return ""; } foreach (ObjectImage oimgTemp in listTemp) { if (oimgTemp.szTitle.ToLower() == szTitle.ToLower()) { if (AccessMode == KML_ACCESS_MODES.MODE_FILE_LOCAL) return szFilePathPub + oimgTemp.szPath; else if (AccessMode == KML_ACCESS_MODES.MODE_FILE_USERDEFINED) return gconffixCurrent.szUserdefinedPath + oimgTemp.szPath; } } return ""; } } private String KmlGetIconLink(KML_ACCESS_MODES AccessMode, KML_ICON_TYPES IconType, String szServer) { String szIcon = ""; switch (IconType) { case KML_ICON_TYPES.USER_AIRCRAFT_POSITION: szIcon = "fsxu"; break; case KML_ICON_TYPES.USER_PREDICTION_POINT: szIcon = "fsxpm"; break; case KML_ICON_TYPES.AI_AIRCRAFT: szIcon = "fsxaip"; break; case KML_ICON_TYPES.AI_HELICOPTER: szIcon = "fsxaih"; break; case KML_ICON_TYPES.AI_BOAT: szIcon = "fsxaib"; break; case KML_ICON_TYPES.AI_GROUND_UNIT: szIcon = "fsxaig"; break; case KML_ICON_TYPES.AI_AIRCRAFT_PREDICTION_POINT: szIcon = "fsxaippp"; break; case KML_ICON_TYPES.AI_HELICOPTER_PREDICTION_POINT: szIcon = "fsxaihpp"; break; case KML_ICON_TYPES.AI_BOAT_PREDICTION_POINT: szIcon = "fsxaibpp"; break; case KML_ICON_TYPES.AI_GROUND_PREDICTION_POINT: szIcon = "fsxaigpp"; break; case KML_ICON_TYPES.PLAN_INTER: szIcon = "plan-inter"; break; case KML_ICON_TYPES.PLAN_NDB: szIcon = "plan-ndb"; break; case KML_ICON_TYPES.PLAN_PORT: szIcon = "plan-port"; break; case KML_ICON_TYPES.PLAN_USER: szIcon = "plan-user"; break; case KML_ICON_TYPES.PLAN_VOR: szIcon = "plan-vor"; break; case KML_ICON_TYPES.ATC_LABEL: return "http://" + szServer + "/gfx/ge/label.png"; } if (AccessMode == KML_ACCESS_MODES.MODE_SERVER) { return "http://" + szServer + "/gfx/ge/icons/" + szIcon + ".png"; } else { foreach (ObjectImage oimgTemp in listIconsGE) { if (oimgTemp.szTitle.ToLower() == szIcon.ToLower()) { if (AccessMode == KML_ACCESS_MODES.MODE_FILE_LOCAL) return szFilePathPub + oimgTemp.szPath; else if (AccessMode == KML_ACCESS_MODES.MODE_FILE_USERDEFINED) return gconffixCurrent.szUserdefinedPath + oimgTemp.szPath; } } return ""; } } private String KmlGenETAPoints(ref PathPositionStored[] ppsCurrent, bool bGenerate, KML_ACCESS_MODES AccessMode, KML_ICON_TYPES Icon, String szServer) { if (ppsCurrent == null) return ""; if (bGenerate) { String szTemp = "<Folder><name>ETA Points</name>"; for (uint n = 0; n < ppsCurrent.GetLength(0); n++) szTemp += "<Placemark>" + "<name>ETA " + ((ppsCurrent[n].dTime < 60.0) ? (((int)ppsCurrent[n].dTime).ToString() + " sec") : (ppsCurrent[n].dTime / 60.0 + " min")) + "</name><visibility>1</visibility><open>0</open>" + "<description><![CDATA[Esitmated Position]]></description>" + "<Style>" + "<IconStyle><Icon><href>" + KmlGetIconLink(AccessMode, Icon, szServer) + "</href></Icon><scale>0.2</scale></IconStyle>" + "<LabelStyle><scale>0.4</scale></LabelStyle>" + "</Style>" + "<Point><altitudeMode>absolute</altitudeMode><coordinates>" + ppsCurrent[n].dLong.ToString().Replace(",", ".") + "," + ppsCurrent[n].dLat.ToString().Replace(",", ".") + "," + ppsCurrent[n].dAlt.ToString().Replace(",", ".") + "</coordinates><extrude>1</extrude></Point></Placemark>"; return szTemp + "</Folder>"; } else return ""; } private String KmlGenUserPosition(KML_ACCESS_MODES AccessMode, String szServer) { lock (lockKmlUserAircraft) { return "<Placemark>" + "<name>User Aircraft Position</name><visibility>1</visibility><open>0</open>" + "<description><![CDATA[Microsoft Flight Simulator X - User Aircraft<br>&nbsp;<br>" + "<b>Title:</b> " + suadCurrent.szTitle + "<br>&nbsp;<br>" + "<b>Type:</b> " + suadCurrent.szATCType + "<br>" + "<b>Model:</b> " + suadCurrent.szATCModel + "<br>&nbsp;<br>" + "<b>Identification:</b> " + suadCurrent.szATCID + "<br>&nbsp;<br>" + "<b>Flight Number:</b> " + suadCurrent.szATCFlightNumber + "<br>" + "<b>Airline:</b> " + suadCurrent.szATCAirline + "<br>&nbsp;<br>" + "<b>Altitude:</b> " + ((int)getValueInCurrentUnit(suadCurrent.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "<br>&nbsp;<br>" + "<center><img src=\"" + KmlGetImageLink(AccessMode, KML_IMAGE_TYPES.AIRCRAFT, suadCurrent.szTitle, szServer) + "\"></center>]]></description>" + "<Snippet>" + suadCurrent.szATCType + " " + suadCurrent.szATCModel + " (" + suadCurrent.szTitle + "), " + suadCurrent.szATCID + "\nAltitude: " + ((int)getValueInCurrentUnit(suadCurrent.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "</Snippet>" + "<Style>" + "<IconStyle><Icon><href>" + KmlGetIconLink(AccessMode, KML_ICON_TYPES.USER_AIRCRAFT_POSITION, szServer) + "</href></Icon><scale>0.8</scale></IconStyle>" + "<LabelStyle><scale>1.0</scale></LabelStyle>" + "</Style>" + "<Point><altitudeMode>absolute</altitudeMode><coordinates>" + suadCurrent.dLongitude.ToString().Replace(",", ".") + "," + suadCurrent.dLatitude.ToString().Replace(",", ".") + "," + suadCurrent.dAltitude.ToString().Replace(",", ".") + "</coordinates><extrude>1</extrude></Point></Placemark>"; } } private String KmlGenUserPath(KML_ACCESS_MODES AccessMode, String szServer) { lock (lockKmlUserPath) { return "<Placemark><name>User Aircraft Path</name><description>Path of the user aircraft since tracking started.</description><visibility>1</visibility><open>0</open><Style><LineStyle><color>9fffffff</color><width>2</width></LineStyle></Style><LineString><altitudeMode>absolute</altitudeMode><coordinates>" + szKmlUserAircraftPath + "</coordinates></LineString></Placemark>"; } } private String KmlGenUserPrediction(KML_ACCESS_MODES AccessMode, String szServer) { String szTemp = ""; lock (lockKmlUserPrediction) { szTemp = "<Placemark><name>User Aircraft Path Prediction</name><description>Path prediction of the user aircraft.</description><visibility>1</visibility><open>0</open><Style><LineStyle><color>9f00ffff</color><width>2</width></LineStyle></Style><LineString><altitudeMode>absolute</altitudeMode><coordinates>" + szKmlUserPrediction + "</coordinates></LineString></Placemark>" + "<Folder><name>ETA Points</name>"; foreach (PathPositionStored ppsTemp in listKmlPredictionPoints) { szTemp += "<Placemark>" + "<name>ETA " + ((ppsTemp.dTime < 60.0) ? (((int)ppsTemp.dTime).ToString() + " sec") : (ppsTemp.dTime / 60.0 + " min")) + "</name><visibility>1</visibility><open>0</open>" + "<description><![CDATA[Esitmated Position]]></description>" + "<Style>" + "<IconStyle><Icon><href>" + KmlGetIconLink(AccessMode, KML_ICON_TYPES.USER_PREDICTION_POINT, szServer) + "</href></Icon><scale>0.2</scale></IconStyle>" + "<LabelStyle><scale>0.4</scale></LabelStyle>" + "</Style>" + "<Point><altitudeMode>absolute</altitudeMode><coordinates>" + ppsTemp.dLong.ToString().Replace(",", ".") + "," + ppsTemp.dLat.ToString().Replace(",", ".") + "," + ppsTemp.dAlt.ToString().Replace(",", ".") + "</coordinates><extrude>1</extrude></Point></Placemark>"; } } return szTemp + "</Folder>"; } private String KmlGenAIAircraft(KML_ACCESS_MODES AccessMode, String szServer) { String szTemp = "<Folder><name>Aircraft Positions</name>"; lock (lockDrrAiPlanes) { List<DataRequestReturnObject> listTemp = GetCurrentList(ref drrAIPlanes); foreach (DataRequestReturnObject bmsoTemp in listTemp) { //szTemp += "<Placemark>" + // "<name>" + bmsoTemp.bmsoObject.szATCType + " " + bmsoTemp.bmsoObject.szATCModel + " (" + bmsoTemp.bmsoObject.szATCID + ")</name><visibility>1</visibility><open>0</open>" + // "<description><![CDATA[Microsoft Flight Simulator X - AI Plane<br>&nbsp;<br>" + // "<b>Title:</b> " + bmsoTemp.bmsoObject.szTitle + "<br>&nbsp;<br>" + // "<b>Type:</b> " + bmsoTemp.bmsoObject.szATCType + "<br>" + // "<b>Model:</b> " + bmsoTemp.bmsoObject.szATCModel + "<br>&nbsp;<br>" + // "<b>Identification:</b> " + bmsoTemp.bmsoObject.szATCID + "<br>&nbsp;<br>" + // "<b>Flight Number:</b> " + bmsoTemp.bmsoObject.szATCFlightNumber + "<br>" + // "<b>Airline:</b> " + bmsoTemp.bmsoObject.szATCAirline + "<br>&nbsp;<br>" + // "<b>Altitude:</b> " + ((int)getValueInCurrentUnit(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "<br>&nbsp;<br>" + // "<center><img src=\"" + KmlGetImageLink(AccessMode, KML_IMAGE_TYPES.AIRCRAFT, bmsoTemp.bmsoObject.szTitle, szServer) + "\"></center>]]></description>" + // "<Snippet>" + bmsoTemp.bmsoObject.szTitle + "\nAltitude: " + ((int)getValueInCurrentUnit(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "</Snippet>" + // "<Style>" + // "<IconStyle><Icon><href>" + KmlGetIconLink(AccessMode, KML_ICON_TYPES.AI_AIRCRAFT, szServer) + "</href></Icon><scale>0.6</scale></IconStyle>" + // "<LabelStyle><scale>0.6</scale></LabelStyle>" + // "</Style>" + // "<Point><altitudeMode>absolute</altitudeMode><coordinates>" + bmsoTemp.bmsoObject.dLongitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dLatitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dAltitude.ToString().Replace(",", ".") + "</coordinates><extrude>1</extrude></Point></Placemark>"; int FL = (int)Math.Round(getValueInUnit(bmsoTemp.bmsoObject.dAltitude, UnitType.FEET) / 100.0, 0); int FLRound = FL - (FL % 10); szTemp += "<Placemark>" + "<name>" + bmsoTemp.bmsoObject.szATCType + " " + bmsoTemp.bmsoObject.szATCModel + " (" + bmsoTemp.bmsoObject.szATCID + ")</name><visibility>1</visibility><open>0</open>" + "<description><![CDATA[Microsoft Flight Simulator X - AI Plane<br>&nbsp;<br>" + "<b>Title:</b> " + bmsoTemp.bmsoObject.szTitle + "<br>&nbsp;<br>" + "<b>Type:</b> " + bmsoTemp.bmsoObject.szATCType + "<br>" + "<b>Model:</b> " + bmsoTemp.bmsoObject.szATCModel + "<br>&nbsp;<br>" + "<b>Identification:</b> " + bmsoTemp.bmsoObject.szATCID + "<br>&nbsp;<br>" + "<b>Flight Number:</b> " + bmsoTemp.bmsoObject.szATCFlightNumber + "<br>" + "<b>Airline:</b> " + bmsoTemp.bmsoObject.szATCAirline + "<br>&nbsp;<br>" + "<b>Altitude:</b> " + ((int)getValueInCurrentUnit(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "<br>&nbsp;<br>" + "<center><img src=\"" + KmlGetImageLink(AccessMode, KML_IMAGE_TYPES.AIRCRAFT, bmsoTemp.bmsoObject.szTitle, szServer) + "\"></center>]]></description>" + "<Snippet>" + bmsoTemp.bmsoObject.szTitle + "\nAltitude: " + ((int)getValueInCurrentUnit(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "</Snippet>" + "<Style>" + "<IconStyle><Icon><href>" + KmlGetIconLink(AccessMode, KML_ICON_TYPES.ATC_LABEL, szServer) + "?code=" + bmsoTemp.bmsoObject.szATCID + "&amp;fl=FL" + FLRound.ToString() + "&amp;speed=" + Math.Round(bmsoTemp.bmsoObject.dSpeed, 0).ToString() + " kn&amp;vspeed=" + (bmsoTemp.bmsoObject.dVSpeed > 0.0 ? "%2F%5C" : (bmsoTemp.bmsoObject.dVSpeed == 0.0 ? "-" : "%5C%2F")) + "&amp;aircraft=" + bmsoTemp.bmsoObject.szATCModel + "</href></Icon><scale>2.5</scale> <hotSpot x=\"30\" y=\"50\" xunits=\"pixels\" yunits=\"pixels\"/></IconStyle>" + "<LabelStyle><scale>0.6</scale></LabelStyle>" + "</Style>" + "<Point><altitudeMode>absolute</altitudeMode><coordinates>" + bmsoTemp.bmsoObject.dLongitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dLatitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dAltitude.ToString().Replace(",", ".") + "</coordinates><extrude>1</extrude></Point></Placemark>"; } szTemp += "</Folder>"; if (gconffixCurrent.bPredictAIAircrafts) { szTemp += "<Folder><name>Aircraft Courses</name>"; foreach (DataRequestReturnObject bmsoTemp in listTemp) { if (bmsoTemp.szCoursePrediction == "") continue; szTemp += "<Placemark><name>" + bmsoTemp.bmsoObject.szATCType + " " + bmsoTemp.bmsoObject.szATCModel + " (" + bmsoTemp.bmsoObject.szATCID + ")</name><description>Course prediction of the aircraft.</description><visibility>1</visibility><open>0</open><Style><LineStyle><color>9fd20091</color><width>2</width></LineStyle></Style><LineString><altitudeMode>absolute</altitudeMode><coordinates>" + bmsoTemp.szCoursePrediction + "</coordinates></LineString></Placemark>"; PathPositionStored[] ppsTemp = bmsoTemp.ppsPredictionPoints; szTemp += KmlGenETAPoints(ref ppsTemp, gconffixCurrent.bPredictPointsAIAircrafts, AccessMode, KML_ICON_TYPES.AI_AIRCRAFT_PREDICTION_POINT, szServer); } szTemp += "</Folder>"; } } return szTemp; } private String KmlGenAIHelicopter(KML_ACCESS_MODES AccessMode, String szServer) { String szTemp = "<Folder><name>Helicopter Positions</name>"; lock (lockDrrAiHelicopters) { List<DataRequestReturnObject> listTemp = GetCurrentList(ref drrAIHelicopters); foreach (DataRequestReturnObject bmsoTemp in listTemp) { szTemp += "<Placemark>" + "<name>" + bmsoTemp.bmsoObject.szATCType + " " + bmsoTemp.bmsoObject.szATCModel + " (" + bmsoTemp.bmsoObject.szATCID + ")</name><visibility>1</visibility><open>0</open>" + "<description><![CDATA[Microsoft Flight Simulator X - AI Helicopter<br>&nbsp;<br>" + "<b>Title:</b> " + bmsoTemp.bmsoObject.szTitle + "<br>&nbsp;<br>" + "<b>Type:</b> " + bmsoTemp.bmsoObject.szATCType + "<br>" + "<b>Model:</b> " + bmsoTemp.bmsoObject.szATCModel + "<br>&nbsp;<br>" + "<b>Identification:</b> " + bmsoTemp.bmsoObject.szATCID + "<br>&nbsp;<br>" + "<b>Flight Number:</b> " + bmsoTemp.bmsoObject.szATCFlightNumber + "<br>" + "<b>Airline:</b> " + bmsoTemp.bmsoObject.szATCAirline + "<br>&nbsp;<br>" + "<b>Altitude:</b> " + ((int)getValueInCurrentUnit(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "<br>&nbsp;<br>" + "<center><img src=\"" + KmlGetImageLink(AccessMode, KML_IMAGE_TYPES.AIRCRAFT, bmsoTemp.bmsoObject.szTitle, szServer) + "\"></center>]]></description>" + "<Snippet>" + bmsoTemp.bmsoObject.szTitle + "\nAltitude: " + ((int)getValueInCurrentUnit(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "</Snippet>" + "<Style>" + "<IconStyle><Icon><href>" + KmlGetIconLink(AccessMode, KML_ICON_TYPES.AI_HELICOPTER, szServer) + "</href></Icon><scale>0.6</scale></IconStyle>" + "<LabelStyle><scale>0.6</scale></LabelStyle>" + "</Style>" + "<Point><altitudeMode>absolute</altitudeMode><coordinates>" + bmsoTemp.bmsoObject.dLongitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dLatitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dAltitude.ToString().Replace(",", ".") + "</coordinates><extrude>1</extrude></Point></Placemark>"; } szTemp += "</Folder>"; if (gconffixCurrent.bPredictAIHelicopters) { szTemp += "<Folder><name>Helicopter Courses</name>"; foreach (DataRequestReturnObject bmsoTemp in listTemp) { if (bmsoTemp.szCoursePrediction == "") continue; szTemp += "<Placemark><name>" + bmsoTemp.bmsoObject.szATCType + " " + bmsoTemp.bmsoObject.szATCModel + " (" + bmsoTemp.bmsoObject.szATCID + ")</name><description>Course prediction of the helicopter.</description><visibility>1</visibility><open>0</open><Style><LineStyle><color>9fd20091</color><width>2</width></LineStyle></Style><LineString><altitudeMode>absolute</altitudeMode><coordinates>" + bmsoTemp.szCoursePrediction + "</coordinates></LineString></Placemark>"; PathPositionStored[] ppsTemp = bmsoTemp.ppsPredictionPoints; szTemp += KmlGenETAPoints(ref ppsTemp, gconffixCurrent.bPredictPointsAIHelicopters, AccessMode, KML_ICON_TYPES.AI_HELICOPTER_PREDICTION_POINT, szServer); } szTemp += "</Folder>"; } } return szTemp; } private String KmlGenAIBoat(KML_ACCESS_MODES AccessMode, String szServer) { String szTemp = "<Folder><name>Boat Positions</name>"; lock (lockDrrAiBoats) { List<DataRequestReturnObject> listTemp = GetCurrentList(ref drrAIBoats); foreach (DataRequestReturnObject bmsoTemp in listTemp) { szTemp += "<Placemark>" + "<name>" + bmsoTemp.bmsoObject.szTitle + "</name><visibility>1</visibility><open>0</open>" + "<description><![CDATA[Microsoft Flight Simulator X - AI Boat<br>&nbsp;<br>" + "<b>Title:</b> " + bmsoTemp.bmsoObject.szTitle + "<br>&nbsp;<br>" + "<b>Altitude:</b> " + ((int)getValueInCurrentUnit(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "<br>&nbsp;<br>" + "<center><img src=\"" + KmlGetImageLink(AccessMode, KML_IMAGE_TYPES.WATER, bmsoTemp.bmsoObject.szTitle, szServer) + "\"></center>]]></description>" + "<Snippet>Altitude: " + ((int)getValueInCurrentUnit(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "</Snippet>" + "<Style>" + "<IconStyle><Icon><href>" + KmlGetIconLink(AccessMode, KML_ICON_TYPES.AI_BOAT, szServer) + "</href></Icon><scale>0.6</scale></IconStyle>" + "<LabelStyle><scale>0.6</scale></LabelStyle>" + "</Style>" + "<Point><altitudeMode>absolute</altitudeMode><coordinates>" + bmsoTemp.bmsoObject.dLongitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dLatitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dAltitude.ToString().Replace(",", ".") + "</coordinates><extrude>1</extrude></Point></Placemark>"; } szTemp += "</Folder>"; if (gconffixCurrent.bPredictAIBoats) { szTemp += "<Folder><name>Boat Courses</name>"; foreach (DataRequestReturnObject bmsoTemp in listTemp) { if (bmsoTemp.szCoursePrediction == "") continue; szTemp += "<Placemark><name>" + bmsoTemp.bmsoObject.szTitle + "</name><description>Course prediction of the boat.</description><visibility>1</visibility><open>0</open><Style><LineStyle><color>9f00b545</color><width>2</width></LineStyle></Style><LineString><altitudeMode>absolute</altitudeMode><coordinates>" + bmsoTemp.szCoursePrediction + "</coordinates></LineString></Placemark>"; PathPositionStored[] ppsTemp = bmsoTemp.ppsPredictionPoints; szTemp += KmlGenETAPoints(ref ppsTemp, gconffixCurrent.bPredictPointsAIBoats, AccessMode, KML_ICON_TYPES.AI_BOAT_PREDICTION_POINT, szServer); } szTemp += "</Folder>"; } } return szTemp; } private String KmlGenAIGroundUnit(KML_ACCESS_MODES AccessMode, String szServer) { String szTemp = "<Folder><name>Ground Vehicle Positions</name>"; lock (lockDrrAiGround) { List<DataRequestReturnObject> listTemp = GetCurrentList(ref drrAIGround); foreach (DataRequestReturnObject bmsoTemp in listTemp) { szTemp += "<Placemark>" + "<name>" + bmsoTemp.bmsoObject.szTitle + "</name><visibility>1</visibility><open>0</open>" + "<description><![CDATA[Microsoft Flight Simulator X - AI Vehicle<br>&nbsp;<br>" + "<b>Title:</b> " + bmsoTemp.bmsoObject.szTitle + "<br>&nbsp;<br>" + "<b>Altitude:</b> " + ((int)getValueInCurrentUnit(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "<br>&nbsp;<br>" + "<center><img src=\"" + KmlGetImageLink(AccessMode, KML_IMAGE_TYPES.GROUND, bmsoTemp.bmsoObject.szTitle, szServer) + "\"></center>]]></description>" + "<Snippet>Altitude: " + ((int)getValueInCurrentUnit(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "</Snippet>" + "<Style>" + "<IconStyle><Icon><href>" + KmlGetIconLink(AccessMode, KML_ICON_TYPES.AI_GROUND_UNIT, szServer) + "</href></Icon><scale>0.6</scale></IconStyle>" + "<LabelStyle><scale>0.6</scale></LabelStyle>" + "</Style>" + "<Point><altitudeMode>absolute</altitudeMode><coordinates>" + bmsoTemp.bmsoObject.dLongitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dLatitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dAltitude.ToString().Replace(",", ".") + "</coordinates><extrude>1</extrude></Point></Placemark>"; } szTemp += "</Folder>"; if (gconffixCurrent.bPredictAIGroundUnits) { szTemp += "<Folder><name>Ground Vehicle Courses</name>"; foreach (DataRequestReturnObject bmsoTemp in listTemp) { if (bmsoTemp.szCoursePrediction == "") continue; szTemp += "<Placemark><name>" + bmsoTemp.bmsoObject.szTitle + "</name><description>Course prediction of the ground vehicle.</description><visibility>1</visibility><open>0</open><Style><LineStyle><color>9f00b545</color><width>2</width></LineStyle></Style><LineString><altitudeMode>absolute</altitudeMode><coordinates>" + bmsoTemp.szCoursePrediction + "</coordinates></LineString></Placemark>"; PathPositionStored[] ppsTemp = bmsoTemp.ppsPredictionPoints; szTemp += KmlGenETAPoints(ref ppsTemp, gconffixCurrent.bPredictPointsAIGroundUnits, AccessMode, KML_ICON_TYPES.AI_GROUND_PREDICTION_POINT, szServer); } szTemp += "</Folder>"; } } return szTemp; } private byte[] KmlGenAtcLabel(String CallSign, String FL, String Aircraft, String Speed, String VerticalSpeed) { Bitmap bmp = new Bitmap(imgAtcLabel); Graphics g = Graphics.FromImage(bmp); Pen pen = new Pen(Color.FromArgb(81, 255, 147)); Brush brush = new SolidBrush(Color.FromArgb(81, 255, 147)); Font font = new Font("Courier New", 10, FontStyle.Bold); Font font_small = new Font("Courier New", 6, FontStyle.Bold); float fX = 72; float fY = 13; g.DrawString(CallSign, font, brush, new PointF(fX, fY)); fY += g.MeasureString(CallSign, font).Height; g.DrawString(FL + " " + VerticalSpeed, font, brush, new PointF(fX, fY)); fY += g.MeasureString(FL + " " + VerticalSpeed, font).Height; g.DrawString(Aircraft, font, brush, new PointF(fX, fY)); return BitmapToPngBytes(bmp); } //private String KmlGenFlightPlans(KML_ACCESS_MODES AccessMode, String szServer) //{ // String szTemp = ""; // lock (lockFlightPlanList) // { // foreach (FlightPlan fpTemp in listFlightPlans) // { // XmlDocument xmldTemp = fpTemp.xmldPlan; // String szTempInner = ""; // String szTempWaypoints = ""; // String szPath = ""; // try // { // for (XmlNode xmlnTemp = xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling) // { // if (xmlnTemp.Name.ToLower() != "atcwaypoint") // continue; // KML_ICON_TYPES iconType; // String szType = xmlnTemp["ATCWaypointType"].InnerText.ToLower(); // if (szType == "intersection") // iconType = KML_ICON_TYPES.PLAN_INTER; // else if (szType == "ndb") // iconType = KML_ICON_TYPES.PLAN_NDB; // else if (szType == "vor") // iconType = KML_ICON_TYPES.PLAN_VOR; // else if (szType == "user") // iconType = KML_ICON_TYPES.PLAN_USER; // else if (szType == "airport") // iconType = KML_ICON_TYPES.PLAN_PORT; // else // iconType = KML_ICON_TYPES.UNKNOWN; // char[] szSeperator = { ',' }; // String[] szCoordinates = xmlnTemp["WorldPosition"].InnerText.Split(szSeperator); // if (szCoordinates.GetLength(0) != 3) // throw new System.Exception("Invalid position value"); // String szAirway = "", szICAOIdent = "", szICAORegion = ""; // if (xmlnTemp["ATCAirway"] != null) // szAirway = xmlnTemp["ATCAirway"].InnerText; // if (xmlnTemp["ICAO"] != null) // { // if (xmlnTemp["ICAO"]["ICAOIdent"] != null) // szICAOIdent = xmlnTemp["ICAO"]["ICAOIdent"].InnerText; // if (xmlnTemp["ICAO"]["ICAORegion"] != null) // szICAORegion = xmlnTemp["ICAO"]["ICAORegion"].InnerText; // } // double dCurrentLong = ConvertDegToDouble(szCoordinates[1]); // double dCurrentLat = ConvertDegToDouble(szCoordinates[0]); // double dCurrentAlt = System.Double.Parse(szCoordinates[2]); // szTempWaypoints += "<Placemark>" + // "<name>" + xmlnTemp["ATCWaypointType"].InnerText + " (" + xmlnTemp.Attributes["id"].Value + ")</name><visibility>1</visibility><open>0</open>" + // "<description><![CDATA[Flight Plane Element<br>&nbsp;<br>" + // "<b>Waypoint Type:</b> " + xmlnTemp["ATCWaypointType"].InnerText + "<br>&nbsp;<br>" + // (szAirway != "" ? "<b>ATC Airway:</b> " + szAirway + "<br>&nbsp;<br>" : "") + // (szICAOIdent != "" ? "<b>ICAO Identification:</b> " + szICAOIdent + "<br>" : "") + // (szICAORegion != "" ? "<b>ICAO Region:</b> " + szICAORegion : "") + // "]]></description>" + // "<Snippet>Waypoint Type: " + xmlnTemp["ATCWaypointType"].InnerText + (szAirway != "" ? "\nAirway: " + szAirway : "") + "</Snippet>" + // "<Style>" + // "<IconStyle><Icon><href>" + KmlGetIconLink(AccessMode, iconType, szServer) + "</href></Icon><scale>1.0</scale></IconStyle>" + // "<LabelStyle><scale>0.6</scale></LabelStyle>" + // "</Style>" + // "<Point><altitudeMode>clampToGround</altitudeMode><coordinates>" + dCurrentLong.ToString().Replace(",", ".") + "," + dCurrentLat.ToString().Replace(",", ".") + "," + dCurrentAlt.ToString().Replace(",", ".") + "</coordinates><extrude>1</extrude></Point></Placemark>"; // szPath += dCurrentLong.ToString().Replace(",", ".") + "," + dCurrentLat.ToString().Replace(",", ".") + "," + dCurrentAlt.ToString().Replace(",", ".") + "\n"; // } // szTempInner = "<Folder><open>0</open>" + // "<name>" + (xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["Title"] != null ? xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["Title"].InnerText : "n/a") + "</name>" + // "<description><![CDATA[" + // "Type: " + (xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["FPType"] != null ? xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["FPType"].InnerText : "n/a") + " (" + (xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["RouteType"] != null ? xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["RouteType"].InnerText : "n/a") + ")<br>" + // "Flight from " + (xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["DepartureName"] != null ? xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["DepartureName"].InnerText : "n/a") + " to " + (xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["DestinationName"] != null ? xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["DestinationName"].InnerText : "n/a") + ".<br>&nbsp;<br>" + // "Altitude: " + (xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["CruisingAlt"] != null ? xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["CruisingAlt"].InnerText : "n/a") + // "]]></description>" + // "<Placemark><name>Path</name><Style><LineStyle><color>9f1ab6ff</color><width>2</width></LineStyle></Style><LineString><tessellate>1</tessellate><altitudeMode>clampToGround</altitudeMode><coordinates>" + szPath + "</coordinates></LineString></Placemark>" + // "<Folder><open>0</open><name>Waypoints</name>" + szTempWaypoints + "</Folder>" + // "</Folder>"; // } // catch // { // szTemp += "<Folder><name>Invalid Flight Plan</name><snippet>Error loading flight plan.</snippet></Folder>"; // continue; // } // szTemp += szTempInner; // } // } // return szTemp; //} #endregion #region Update Check // private void checkForProgramUpdate() // { // try // { // szOnlineVersionCheckData = ""; // wrOnlineVersionCheck = WebRequest.Create("http://juergentreml.online.de/fsxget/provide/version.txt"); // wrOnlineVersionCheck.BeginGetResponse(new AsyncCallback(RespCallback), wrOnlineVersionCheck); // } // catch // { //#if DEBUG // notifyIconMain.ShowBalloonTip(5, Text, "Couldn't check for program update online!", ToolTipIcon.Warning); //#endif // } // } // private void RespCallback(IAsyncResult asynchronousResult) // { // try // { // WebRequest myWebRequest = (WebRequest)asynchronousResult.AsyncState; // wrespOnlineVersionCheck = myWebRequest.EndGetResponse(asynchronousResult); // Stream responseStream = wrespOnlineVersionCheck.GetResponseStream(); // responseStream.BeginRead(bOnlineVersionCheckRawData, 0, iOnlineVersionCheckRawDataLength, new AsyncCallback(ReadCallBack), responseStream); // } // catch // { //#if DEBUG // notifyIconMain.ShowBalloonTip(5, Text, "Couldn't check for program update online!", ToolTipIcon.Warning); //#endif // } // } // private void ReadCallBack(IAsyncResult asyncResult) // { // try // { // Stream responseStream = (Stream)asyncResult.AsyncState; // int iRead = responseStream.EndRead(asyncResult); // if (iRead > 0) // { // szOnlineVersionCheckData += Encoding.ASCII.GetString(bOnlineVersionCheckRawData, 0, iRead); // responseStream.BeginRead(bOnlineVersionCheckRawData, 0, iOnlineVersionCheckRawDataLength, new AsyncCallback(ReadCallBack), responseStream); // } // else // { // responseStream.Close(); // wrespOnlineVersionCheck.Close(); // char[] szSeperator = { '.' }; // String[] szVersionLocal = Application.ProductVersion.Split(szSeperator); // String[] szVersionOnline = szOnlineVersionCheckData.Split(szSeperator); // for (int i = 0; i < Math.Min(szVersionLocal.GetLength(0), szVersionOnline.GetLength(0)); i++) // { // if (Int64.Parse(szVersionOnline[i]) > Int64.Parse(szVersionLocal[i])) // { // notifyIconMain.ShowBalloonTip(30, Text, "A new program version is available!\n\nLatest Version:\t" + szOnlineVersionCheckData + "\nYour Version:\t" + Application.ProductVersion, ToolTipIcon.Info); // break; // } // else if (Int64.Parse(szVersionOnline[i]) < Int64.Parse(szVersionLocal[i])) // break; // } // } // } // catch // { //#if DEBUG // notifyIconMain.ShowBalloonTip(5, Text, "Couldn't check for program update online!", ToolTipIcon.Warning); //#endif // } // } #endregion #region Timers private void timerFSXConnect_Tick(object sender, EventArgs e) { if (openConnection()) { timerFSXConnect.Stop(); bConnected = true; notifyIconMain.Icon = icReceive; notifyIconMain.Text = Text + "(Waiting for connection...)"; safeShowBalloonTip(1000, Text, "Connected to FSX!", ToolTipIcon.Info); } } private void timerIPAddressRefresh_Tick(object sender, EventArgs e) { IPHostEntry ipheLocalhost1 = Dns.GetHostEntry(Dns.GetHostName()); IPHostEntry ipheLocalhost2 = Dns.GetHostEntry("localhost"); lock (lockIPAddressList) { ipalLocal1 = ipheLocalhost1.AddressList; ipalLocal2 = ipheLocalhost2.AddressList; } } private void timerQueryUserAircraft_Tick(object sender, EventArgs e) { simconnect.RequestDataOnSimObjectType(DATA_REQUESTS.REQUEST_USER_AIRCRAFT, DEFINITIONS.StructBasicMovingSceneryObject, 0, SIMCONNECT_SIMOBJECT_TYPE.USER); } private void timerQueryUserPath_Tick(object sender, EventArgs e) { simconnect.RequestDataOnSimObjectType(DATA_REQUESTS.REQUEST_USER_PATH, DEFINITIONS.StructBasicMovingSceneryObject, 0, SIMCONNECT_SIMOBJECT_TYPE.USER); } private void timerUserPrediction_Tick(object sender, EventArgs e) { simconnect.RequestDataOnSimObjectType(DATA_REQUESTS.REQUEST_USER_PREDICTION, DEFINITIONS.StructBasicMovingSceneryObject, 0, SIMCONNECT_SIMOBJECT_TYPE.USER); } private void timerQueryAIAircrafts_Tick(object sender, EventArgs e) { simconnect.RequestDataOnSimObjectType(DATA_REQUESTS.REQUEST_AI_PLANE, DEFINITIONS.StructBasicMovingSceneryObject, (uint)gconffixCurrent.iRangeAIAircrafts, SIMCONNECT_SIMOBJECT_TYPE.AIRCRAFT); } private void timerQueryAIHelicopters_Tick(object sender, EventArgs e) { simconnect.RequestDataOnSimObjectType(DATA_REQUESTS.REQUEST_AI_HELICOPTER, DEFINITIONS.StructBasicMovingSceneryObject, (uint)gconffixCurrent.iRangeAIHelicopters, SIMCONNECT_SIMOBJECT_TYPE.HELICOPTER); } private void timerQueryAIBoats_Tick(object sender, EventArgs e) { simconnect.RequestDataOnSimObjectType(DATA_REQUESTS.REQUEST_AI_BOAT, DEFINITIONS.StructBasicMovingSceneryObject, (uint)gconffixCurrent.iRangeAIBoats, SIMCONNECT_SIMOBJECT_TYPE.BOAT); } private void timerQueryAIGroundUnits_Tick(object sender, EventArgs e) { simconnect.RequestDataOnSimObjectType(DATA_REQUESTS.REQUEST_AI_GROUND, DEFINITIONS.StructBasicMovingSceneryObject, (uint)gconffixCurrent.iRangeAIGroundUnits, SIMCONNECT_SIMOBJECT_TYPE.GROUND); } #endregion #region Config File Read & Write private void ConfigMirrorToVariables() { gconffixCurrent.bExitOnFsxExit = (xmldSettings["fsxget"]["settings"]["options"]["general"]["application-startup"].Attributes["Exit"].Value.ToLower() == "true"); lock (lockChConf) { gconfchCurrent.bEnabled = (xmldSettings["fsxget"]["settings"]["options"]["general"]["enable-on-startup"].Attributes["Enabled"].Value == "1"); gconfchCurrent.bShowBalloons = (xmldSettings["fsxget"]["settings"]["options"]["general"]["show-balloon-tips"].Attributes["Enabled"].Value == "1"); } gconffixCurrent.bLoadKMLFile = (xmldSettings["fsxget"]["settings"]["options"]["general"]["load-kml-file"].Attributes["Enabled"].Value == "1"); //gconffixCurrent.bCheckForUpdates = (xmldSettings["fsxget"]["settings"]["options"]["general"]["update-check"].Attributes["Enabled"].Value == "1"); gconffixCurrent.iTimerUserAircraft = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-aircraft"].Attributes["Interval"].Value); gconffixCurrent.bQueryUserAircraft = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-aircraft"].Attributes["Enabled"].Value == "1"); gconffixCurrent.iTimerUserPath = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-path"].Attributes["Interval"].Value); gconffixCurrent.bQueryUserPath = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-path"].Attributes["Enabled"].Value == "1"); gconffixCurrent.iTimerUserPathPrediction = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["user-path-prediction"].Attributes["Interval"].Value); gconffixCurrent.bUserPathPrediction = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["user-path-prediction"].Attributes["Enabled"].Value == "1"); int iCount = 0; for (XmlNode xmlnTemp = xmldSettings["fsxget"]["settings"]["options"]["fsx"]["user-path-prediction"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling) { if (xmlnTemp.Name == "prediction-point") iCount++; } gconffixCurrent.dPredictionTimes = new double[iCount]; iCount = 0; for (XmlNode xmlnTemp = xmldSettings["fsxget"]["settings"]["options"]["fsx"]["user-path-prediction"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling) { if (xmlnTemp.Name == "prediction-point") { gconffixCurrent.dPredictionTimes[iCount] = System.Int64.Parse(xmlnTemp.Attributes["Time"].Value); iCount++; } } gconffixCurrent.iTimerAIAircrafts = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Interval"].Value); gconffixCurrent.iRangeAIAircrafts = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Range"].Value); gconffixCurrent.bQueryAIAircrafts = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Enabled"].Value == "1"); gconffixCurrent.bPredictAIAircrafts = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Prediction"].Value == "1"); gconffixCurrent.bPredictPointsAIAircrafts = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["PredictionPoints"].Value == "1"); gconffixCurrent.iTimerAIHelicopters = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["Interval"].Value); gconffixCurrent.iRangeAIHelicopters = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["Range"].Value); gconffixCurrent.bQueryAIHelicopters = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["Enabled"].Value == "1"); gconffixCurrent.bPredictAIHelicopters = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["Prediction"].Value == "1"); gconffixCurrent.bPredictPointsAIHelicopters = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["PredictionPoints"].Value == "1"); gconffixCurrent.iTimerAIBoats = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Interval"].Value); gconffixCurrent.iRangeAIBoats = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Range"].Value); gconffixCurrent.bQueryAIBoats = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Enabled"].Value == "1"); gconffixCurrent.bPredictAIBoats = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Prediction"].Value == "1"); gconffixCurrent.bPredictPointsAIBoats = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["PredictionPoints"].Value == "1"); gconffixCurrent.iTimerAIGroundUnits = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["Interval"].Value); gconffixCurrent.iRangeAIGroundUnits = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["Range"].Value); gconffixCurrent.bQueryAIGroundUnits = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["Enabled"].Value == "1"); gconffixCurrent.bPredictAIGroundUnits = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["Prediction"].Value == "1"); gconffixCurrent.bPredictPointsAIGroundUnits = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["PredictionPoints"].Value == "1"); gconffixCurrent.bQueryAIObjects = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"].Attributes["Enabled"].Value == "1"); gconffixCurrent.iUpdateGEUserAircraft = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["user-aircraft"].Attributes["Interval"].Value); gconffixCurrent.iUpdateGEUserPath = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["user-path"].Attributes["Interval"].Value); gconffixCurrent.iUpdateGEUserPrediction = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["user-path-prediction"].Attributes["Interval"].Value); gconffixCurrent.iUpdateGEAIAircrafts = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-aircrafts"].Attributes["Interval"].Value); gconffixCurrent.iUpdateGEAIHelicopters = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-helicopters"].Attributes["Interval"].Value); gconffixCurrent.iUpdateGEAIBoats = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-boats"].Attributes["Interval"].Value); gconffixCurrent.iUpdateGEAIGroundUnits = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-ground-units"].Attributes["Interval"].Value); gconffixCurrent.iServerPort = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["server-settings"]["port"].Attributes["Value"].Value); gconffixCurrent.uiServerAccessLevel = (uint)System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["server-settings"]["access-level"].Attributes["Value"].Value); gconffixCurrent.bFsxConnectionIsLocal = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Local"].Value.ToLower() == "true"); gconffixCurrent.szFsxConnectionHost = xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Host"].Value; gconffixCurrent.szFsxConnectionPort = xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Port"].Value; gconffixCurrent.szFsxConnectionProtocol = xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Protocol"].Value; //gconffixCurrent.bLoadFlightPlans = (xmldSettings["fsxget"]["settings"]["options"]["flightplans"].Attributes["Enabled"].Value == "1"); gconffixCurrent.utUnits = (UnitType)System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["units"].InnerText); gconffixCurrent.szUserdefinedPath = ""; } private void ConfigMirrorToForm() { checkBox1.Checked = (xmldSettings["fsxget"]["settings"]["options"]["general"]["application-startup"].Attributes["Exit"].Value.ToLower() == "true"); checkEnableOnStartup.Checked = (xmldSettings["fsxget"]["settings"]["options"]["general"]["enable-on-startup"].Attributes["Enabled"].Value == "1"); checkShowInfoBalloons.Checked = (xmldSettings["fsxget"]["settings"]["options"]["general"]["show-balloon-tips"].Attributes["Enabled"].Value == "1"); checkBoxLoadKMLFile.Checked = (xmldSettings["fsxget"]["settings"]["options"]["general"]["load-kml-file"].Attributes["Enabled"].Value == "1"); //checkBoxUpdateCheck.Checked = (xmldSettings["fsxget"]["settings"]["options"]["general"]["update-check"].Attributes["Enabled"].Value == "1"); numericUpDownQueryUserAircraft.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-aircraft"].Attributes["Interval"].Value); checkQueryUserAircraft.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-aircraft"].Attributes["Enabled"].Value == "1"); numericUpDownQueryUserPath.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-path"].Attributes["Interval"].Value); checkQueryUserPath.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-path"].Attributes["Enabled"].Value == "1"); numericUpDownUserPathPrediction.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["user-path-prediction"].Attributes["Interval"].Value); checkBoxUserPathPrediction.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["user-path-prediction"].Attributes["Enabled"].Value == "1"); listBoxPathPrediction.Items.Clear(); for (XmlNode xmlnTemp = xmldSettings["fsxget"]["settings"]["options"]["fsx"]["user-path-prediction"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling) { if (xmlnTemp.Name == "prediction-point") { ListBoxPredictionTimesItem lbptiTemp = new ListBoxPredictionTimesItem(); lbptiTemp.dTime = System.Int64.Parse(xmlnTemp.Attributes["Time"].Value); bool bInserted = false; for (int n = 0; n < listBoxPathPrediction.Items.Count; n++) { if (((ListBoxPredictionTimesItem)listBoxPathPrediction.Items[n]).dTime > lbptiTemp.dTime) { listBoxPathPrediction.Items.Insert(n, lbptiTemp); bInserted = true; break; } } if (!bInserted) listBoxPathPrediction.Items.Add(lbptiTemp); } } numericUpDownQueryAIAircraftsInterval.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Interval"].Value); numericUpDownQueryAIAircraftsRadius.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Range"].Value); checkBoxAIAircraftsPredictPoints.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["PredictionPoints"].Value == "1"); checkBoxAIAircraftsPredict.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Prediction"].Value == "1"); checkBoxAIAircraftsPredict_CheckedChanged(null, null); checkBoxQueryAIAircrafts.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Enabled"].Value == "1"); checkBoxQueryAIAircrafts_CheckedChanged(null, null); numericUpDownQueryAIHelicoptersInterval.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["Interval"].Value); numericUpDownQueryAIHelicoptersRadius.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["Range"].Value); checkBoxAIHelicoptersPredictPoints.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["PredictionPoints"].Value == "1"); checkBoxAIHelicoptersPredict.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["Prediction"].Value == "1"); checkBoxAIHelicoptersPredict_CheckedChanged(null, null); checkBoxQueryAIHelicopters.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["Enabled"].Value == "1"); checkBoxQueryAIHelicopters_CheckedChanged(null, null); numericUpDownQueryAIBoatsInterval.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Interval"].Value); numericUpDownQueryAIBoatsRadius.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Range"].Value); checkBoxAIBoatsPredictPoints.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["PredictionPoints"].Value == "1"); checkBoxAIBoatsPredict.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Prediction"].Value == "1"); checkBoxAIBoatsPredict_CheckedChanged(null, null); checkBoxQueryAIBoats.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Enabled"].Value == "1"); checkBoxQueryAIBoats_CheckedChanged(null, null); numericUpDownQueryAIGroudUnitsInterval.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["Interval"].Value); numericUpDownQueryAIGroudUnitsRadius.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["Range"].Value); checkBoxAIGroundPredictPoints.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["PredictionPoints"].Value == "1"); checkBoxAIGroundPredict.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["Prediction"].Value == "1"); checkBoxAIGroundPredict_CheckedChanged(null, null); checkBoxQueryAIGroudUnits.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["Enabled"].Value == "1"); checkBoxQueryAIGroudUnits_CheckedChanged(null, null); checkBoxQueryAIObjects.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"].Attributes["Enabled"].Value == "1"); numericUpDownRefreshUserAircraft.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["user-aircraft"].Attributes["Interval"].Value); numericUpDownRefreshUserPath.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["user-path"].Attributes["Interval"].Value); numericUpDownRefreshUserPrediction.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["user-path-prediction"].Attributes["Interval"].Value); numericUpDownRefreshAIAircrafts.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-aircrafts"].Attributes["Interval"].Value); numericUpDownRefreshAIHelicopter.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-helicopters"].Attributes["Interval"].Value); numericUpDownRefreshAIBoats.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-boats"].Attributes["Interval"].Value); numericUpDownRefreshAIGroundUnits.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-ground-units"].Attributes["Interval"].Value); numericUpDownServerPort.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["server-settings"]["port"].Attributes["Value"].Value); if (System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["server-settings"]["access-level"].Attributes["Value"].Value) == 1) radioButtonAccessRemote.Checked = true; else radioButtonAccessLocalOnly.Checked = true; //checkBoxLoadFlightPlans.Checked = (xmldSettings["fsxget"]["settings"]["options"]["flightplans"].Attributes["Enabled"].Value == "1"); //listViewFlightPlans.Items.Clear(); //int iCount = 0; //for (XmlNode xmlnTemp = xmldSettings["fsxget"]["settings"]["options"]["flightplans"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling) //{ // ListViewItem lviTemp = listViewFlightPlans.Items.Insert(iCount, xmlnTemp.Attributes["Name"].Value); // lviTemp.Checked = (xmlnTemp.Attributes["Show"].Value == "1" ? true : false); // lviTemp.SubItems.Add(xmlnTemp.Attributes["File"].Value); // iCount++; //} radioButton7.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Local"].Value.ToLower() == "true"); radioButton6.Checked = !radioButton7.Checked; textBox1.Text = xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Host"].Value; textBox3.Text = xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Port"].Value; comboBox1.SelectedIndex = comboBox1.FindString(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Protocol"].Value); comboBox2.SelectedIndex = int.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["units"].InnerText); UpdateCheckBoxStates(); UpdateButtonStates(); } private void ConfigRetrieveFromForm() { xmldSettings["fsxget"]["settings"]["options"]["general"]["application-startup"].Attributes["Exit"].Value = checkBox1.Checked ? "True" : "False"; xmldSettings["fsxget"]["settings"]["options"]["general"]["enable-on-startup"].Attributes["Enabled"].Value = checkEnableOnStartup.Checked ? "1" : "0"; xmldSettings["fsxget"]["settings"]["options"]["general"]["show-balloon-tips"].Attributes["Enabled"].Value = checkShowInfoBalloons.Checked ? "1" : "0"; xmldSettings["fsxget"]["settings"]["options"]["general"]["load-kml-file"].Attributes["Enabled"].Value = checkBoxLoadKMLFile.Checked ? "1" : "0"; //xmldSettings["fsxget"]["settings"]["options"]["general"]["update-check"].Attributes["Enabled"].Value = checkBoxUpdateCheck.Checked ? "1" : "0"; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-aircraft"].Attributes["Interval"].Value = numericUpDownQueryUserAircraft.Value.ToString(); xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-aircraft"].Attributes["Enabled"].Value = checkQueryUserAircraft.Checked ? "1" : "0"; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-path"].Attributes["Interval"].Value = numericUpDownQueryUserPath.Value.ToString(); xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-path"].Attributes["Enabled"].Value = checkQueryUserPath.Checked ? "1" : "0"; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["user-path-prediction"].Attributes["Interval"].Value = numericUpDownUserPathPrediction.Value.ToString(); xmldSettings["fsxget"]["settings"]["options"]["fsx"]["user-path-prediction"].Attributes["Enabled"].Value = checkBoxUserPathPrediction.Checked ? "1" : "0"; XmlNode xmlnTempLoop = xmldSettings["fsxget"]["settings"]["options"]["fsx"]["user-path-prediction"].FirstChild; while (xmlnTempLoop != null) { XmlNode xmlnDelete = xmlnTempLoop; xmlnTempLoop = xmlnTempLoop.NextSibling; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["user-path-prediction"].RemoveChild(xmlnDelete); } for (int n = 0; n < listBoxPathPrediction.Items.Count; n++) { XmlNode xmlnTemp = xmldSettings.CreateElement("prediction-point"); XmlAttribute xmlaTemp = xmldSettings.CreateAttribute("Time"); xmlaTemp.Value = ((ListBoxPredictionTimesItem)listBoxPathPrediction.Items[n]).dTime.ToString(); xmlnTemp.Attributes.Append(xmlaTemp); xmldSettings["fsxget"]["settings"]["options"]["fsx"]["user-path-prediction"].AppendChild(xmlnTemp); } xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Interval"].Value = numericUpDownQueryAIAircraftsInterval.Value.ToString(); xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Range"].Value = numericUpDownQueryAIAircraftsRadius.Value.ToString(); xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Enabled"].Value = checkBoxQueryAIAircrafts.Checked ? "1" : "0"; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Prediction"].Value = checkBoxAIAircraftsPredict.Checked ? "1" : "0"; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["PredictionPoints"].Value = checkBoxAIAircraftsPredictPoints.Checked ? "1" : "0"; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["Interval"].Value = numericUpDownQueryAIHelicoptersInterval.Value.ToString(); xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["Range"].Value = numericUpDownQueryAIHelicoptersRadius.Value.ToString(); xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["Enabled"].Value = checkBoxQueryAIHelicopters.Checked ? "1" : "0"; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["Prediction"].Value = checkBoxAIHelicoptersPredict.Checked ? "1" : "0"; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["PredictionPoints"].Value = checkBoxAIHelicoptersPredictPoints.Checked ? "1" : "0"; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Interval"].Value = numericUpDownQueryAIBoatsInterval.Value.ToString(); xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Range"].Value = numericUpDownQueryAIBoatsRadius.Value.ToString(); xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Enabled"].Value = checkBoxQueryAIBoats.Checked ? "1" : "0"; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Prediction"].Value = checkBoxAIBoatsPredict.Checked ? "1" : "0"; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["PredictionPoints"].Value = checkBoxAIBoatsPredictPoints.Checked ? "1" : "0"; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["Interval"].Value = numericUpDownQueryAIGroudUnitsInterval.Value.ToString(); xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["Range"].Value = numericUpDownQueryAIGroudUnitsRadius.Value.ToString(); xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["Enabled"].Value = checkBoxQueryAIGroudUnits.Checked ? "1" : "0"; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["Prediction"].Value = checkBoxAIGroundPredict.Checked ? "1" : "0"; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["PredictionPoints"].Value = checkBoxAIGroundPredictPoints.Checked ? "1" : "0"; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"].Attributes["Enabled"].Value = checkBoxQueryAIObjects.Checked ? "1" : "0"; xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["user-aircraft"].Attributes["Interval"].Value = numericUpDownRefreshUserAircraft.Value.ToString(); xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["user-path"].Attributes["Interval"].Value = numericUpDownRefreshUserPath.Value.ToString(); xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["user-path-prediction"].Attributes["Interval"].Value = numericUpDownRefreshUserPrediction.Value.ToString(); xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-aircrafts"].Attributes["Interval"].Value = numericUpDownRefreshAIAircrafts.Value.ToString(); xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-helicopters"].Attributes["Interval"].Value = numericUpDownRefreshAIHelicopter.Value.ToString(); xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-boats"].Attributes["Interval"].Value = numericUpDownRefreshAIBoats.Value.ToString(); xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-ground-units"].Attributes["Interval"].Value = numericUpDownRefreshAIGroundUnits.Value.ToString(); xmldSettings["fsxget"]["settings"]["options"]["ge"]["server-settings"]["port"].Attributes["Value"].Value = numericUpDownServerPort.Value.ToString(); if (radioButtonAccessRemote.Checked) xmldSettings["fsxget"]["settings"]["options"]["ge"]["server-settings"]["access-level"].Attributes["Value"].Value = "1"; else xmldSettings["fsxget"]["settings"]["options"]["ge"]["server-settings"]["access-level"].Attributes["Value"].Value = "0"; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Local"].Value = radioButton7.Checked ? "True" : "False"; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Protocol"].Value = comboBox1.SelectedItem.ToString(); xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Host"].Value = textBox1.Text; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Port"].Value = textBox3.Text; xmldSettings["fsxget"]["settings"]["options"]["ge"]["units"].InnerXml = comboBox2.SelectedIndex.ToString(); //xmldSettings["fsxget"]["settings"]["options"]["flightplans"].Attributes["Enabled"].Value = checkBoxLoadFlightPlans.Checked ? "1" : "0"; } //private void LoadFlightPlans() //{ // bool bError = false; // FlightPlan fpTemp; // XmlDocument xmldTemp = new XmlDocument(); // try // { // int iCount = 0; // fpTemp.szName = ""; // fpTemp.uiID = 0; // fpTemp.xmldPlan = null; // for (XmlNode xmlnTemp = xmldSettings["fsxget"]["settings"]["options"]["flightplans"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling) // { // try // { // if (xmlnTemp.Attributes["Show"].Value == "0") // continue; // XmlReader xmlrTemp = new XmlTextReader(xmlnTemp.Attributes["File"].Value); // fpTemp.uiID = iCount; // fpTemp.xmldPlan = new XmlDocument(); // fpTemp.xmldPlan.Load(xmlrTemp); // xmlrTemp.Close(); // xmlrTemp = null; // } // catch // { // bError = true; // continue; // } // lock (lockFlightPlanList) // { // listFlightPlans.Add(fpTemp); // } // iCount++; // } // } // catch // { // MessageBox.Show("Could not read flight plan list from settings file! No flight plans will be loaded.", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning); // } // if (bError) // MessageBox.Show("There were errors loading some of the flight plans! These flight plans will not be shown.\n\nThis problem might be due to incorrect or no longer existing flight plan files.\nPlease remove them from the flight plan list in the options dialog.", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning); //} #endregion #region Assembly Attribute Accessors public string AssemblyTitle { get { // Get all Title attributes on this assembly object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false); // If there is at least one Title attribute if (attributes.Length > 0) { // Select the first one AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute)attributes[0]; // If it is not an empty string, return it if (titleAttribute.Title != "") return titleAttribute.Title; } // If there was no Title attribute, or if the Title attribute was the empty string, return the .exe name return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase); } } public string AssemblyVersion { get { return Assembly.GetExecutingAssembly().GetName().Version.ToString(); } } public string AssemblyDescription { get { // Get all Description attributes on this assembly object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false); // If there aren't any Description attributes, return an empty string if (attributes.Length == 0) return ""; // If there is a Description attribute, return its value return ((AssemblyDescriptionAttribute)attributes[0]).Description; } } public string AssemblyProduct { get { // Get all Product attributes on this assembly object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false); // If there aren't any Product attributes, return an empty string if (attributes.Length == 0) return ""; // If there is a Product attribute, return its value return ((AssemblyProductAttribute)attributes[0]).Product; } } public string AssemblyCopyright { get { // Get all Copyright attributes on this assembly object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false); // If there aren't any Copyright attributes, return an empty string if (attributes.Length == 0) return ""; // If there is a Copyright attribute, return its value return ((AssemblyCopyrightAttribute)attributes[0]).Copyright; } } public string AssemblyCompany { get { // Get all Company attributes on this assembly object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute), false); // If there aren't any Company attributes, return an empty string if (attributes.Length == 0) return ""; // If there is a Company attribute, return its value return ((AssemblyCompanyAttribute)attributes[0]).Company; } } #endregion #region User Interface Handlers private void exitToolStripMenuItem_Click(object sender, EventArgs e) { bClose = true; Close(); } private void optionsToolStripMenuItem_Click(object sender, EventArgs e) { safeShowMainDialog(0); } private void enableTrackerToolStripMenuItem_Click(object sender, EventArgs e) { bool bTemp = enableTrackerToolStripMenuItem.Checked; lock (lockChConf) { if (bTemp != gconfchCurrent.bEnabled) { gconfchCurrent.bEnabled = bTemp; if (gconfchCurrent.bEnabled) globalConnect(); else globalDisconnect(); } } } private void showBalloonTipsToolStripMenuItem_Click(object sender, EventArgs e) { lock (lockChConf) { gconfchCurrent.bShowBalloons = showBalloonTipsToolStripMenuItem.Checked; } // This call is safe as the existence of this key has been checked by calling configMirrorToForm at startup. xmldSettings["fsxget"]["settings"]["options"]["general"]["show-balloon-tips"].Attributes["Enabled"].Value = showBalloonTipsToolStripMenuItem.Checked ? "1" : "0"; } private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { safeShowMainDialog(5); } private void clearUserAircraftPathToolStripMenuItem_Click(object sender, EventArgs e) { lock (lockKmlUserPath) { szKmlUserAircraftPath = ""; } lock (lockKmlUserPrediction) { szKmlUserPrediction = ""; listKmlPredictionPoints.Clear(); } lock (lockKmlPredictionPoints) { clearPPStructure(ref ppPos1); clearPPStructure(ref ppPos2); } } private void runMicrosoftFlightSimulatorXToolStripMenuItem_Click(object sender, EventArgs e) { try { System.Diagnostics.Process.Start(szPathFSX); } catch { MessageBox.Show("An error occured while trying to start Microsoft Flight Simulator X.", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } private void runGoogleEarthToolStripMenuItem_Click(object sender, EventArgs e) { try { lock (lockListenerControl) { if (gconffixCurrent.bLoadKMLFile && bConnected) System.Diagnostics.Process.Start(szUserAppPath + "\\pub\\fsxgetd.kml"); else System.Diagnostics.Process.Start(szUserAppPath + "\\pub\\fsxgets.kml"); } } catch { MessageBox.Show("An error occured while trying to start Google Earth.", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } private void notifyIcon1_MouseClick(object sender, MouseEventArgs e) { if (notifyIconMain.ContextMenuStrip == null) this.Activate(); } private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { try { linkLabel1.LinkVisited = true; System.Diagnostics.Process.Start("http://www.juergentreml.de/fsxget/"); } catch { MessageBox.Show("Unable to open http://www.juergentreml.de/fsxget/!"); } } private void checkBoxQueryAIObjects_CheckedChanged(object sender, EventArgs e) { checkBoxQueryAIAircrafts.Enabled = checkBoxQueryAIBoats.Enabled = checkBoxQueryAIGroudUnits.Enabled = checkBoxQueryAIHelicopters.Enabled = checkBoxQueryAIObjects.Checked; bRestartRequired = true; } private void checkBoxQueryAIAircrafts_CheckedChanged(object sender, EventArgs e) { checkBoxQueryAIAircrafts_EnabledChanged(null, null); bRestartRequired = true; } private void checkBoxQueryAIAircrafts_EnabledChanged(object sender, EventArgs e) { checkBoxAIAircraftsPredict.Enabled = numericUpDownQueryAIAircraftsInterval.Enabled = numericUpDownQueryAIAircraftsRadius.Enabled = (checkBoxQueryAIAircrafts.Enabled & checkBoxQueryAIAircrafts.Checked); } private void checkBoxQueryAIHelicopters_CheckedChanged(object sender, EventArgs e) { checkBoxQueryAIHelicopters_EnabledChanged(null, null); bRestartRequired = true; } private void checkBoxQueryAIHelicopters_EnabledChanged(object sender, EventArgs e) { checkBoxAIHelicoptersPredict.Enabled = numericUpDownQueryAIHelicoptersInterval.Enabled = numericUpDownQueryAIHelicoptersRadius.Enabled = (checkBoxQueryAIHelicopters.Enabled & checkBoxQueryAIHelicopters.Checked); } private void checkBoxQueryAIBoats_CheckedChanged(object sender, EventArgs e) { checkBoxQueryAIBoats_EnabledChanged(null, null); bRestartRequired = true; } private void checkBoxQueryAIBoats_EnabledChanged(object sender, EventArgs e) { checkBoxAIBoatsPredict.Enabled = numericUpDownQueryAIBoatsInterval.Enabled = numericUpDownQueryAIBoatsRadius.Enabled = (checkBoxQueryAIBoats.Enabled & checkBoxQueryAIBoats.Checked); } private void checkBoxQueryAIGroudUnits_CheckedChanged(object sender, EventArgs e) { checkBoxQueryAIGroudUnits_EnabledChanged(null, null); bRestartRequired = true; } private void checkBoxQueryAIGroudUnits_EnabledChanged(object sender, EventArgs e) { checkBoxAIGroundPredict.Enabled = numericUpDownQueryAIGroudUnitsInterval.Enabled = numericUpDownQueryAIGroudUnitsRadius.Enabled = (checkBoxQueryAIGroudUnits.Enabled & checkBoxQueryAIGroudUnits.Checked); } private void checkQueryUserAircraft_CheckedChanged(object sender, EventArgs e) { numericUpDownQueryUserAircraft.Enabled = checkQueryUserAircraft.Checked; bRestartRequired = true; } private void checkQueryUserPath_CheckedChanged(object sender, EventArgs e) { numericUpDownQueryUserPath.Enabled = checkQueryUserPath.Checked; bRestartRequired = true; } private void buttonOK_Click(object sender, EventArgs e) { // Set startup options if necessary if (radioButton8.Checked) { if (!isAutoStartActivated()) if (!AutoStartActivate()) MessageBox.Show("Couldn't change autorun value in registry!", AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning); if (isFsxStartActivated()) if (!FsxStartDeactivate()) MessageBox.Show("Couldn't change FSX startup options!", AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning); } else if (radioButton9.Checked) { if (!isFsxStartActivated()) if (!FsxStartActivate()) MessageBox.Show("Couldn't change FSX startup options!", AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning); if (isAutoStartActivated()) if (!AutoStartDeactivate()) MessageBox.Show("Couldn't change autorun value in registry!", AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { if (isFsxStartActivated()) if (!FsxStartDeactivate()) MessageBox.Show("Couldn't change FSX startup options!", AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning); if (isAutoStartActivated()) if (!AutoStartDeactivate()) MessageBox.Show("Couldn't change autorun value in registry!", AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning); } //string szRun = (string)Registry.GetValue(szRegKeyRun, AssemblyTitle, ""); ConfigRetrieveFromForm(); showBalloonTipsToolStripMenuItem.Checked = checkShowInfoBalloons.Checked; notifyIconMain.ContextMenuStrip = contextMenuStripNotifyIcon; gconffixCurrent.utUnits = (UnitType)comboBox2.SelectedIndex; if (bRestartRequired) if (MessageBox.Show("Some of the changes you made require a restart. Do you want to restart " + Text + " now for those changes to take effect.", Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) RestartApp(); Hide(); } private void buttonCancel_Click(object sender, EventArgs e) { safeHideMainDialog(); } private void numericUpDownQueryUserAircraft_ValueChanged(object sender, EventArgs e) { bRestartRequired = true; } private void numericUpDownQueryUserPath_ValueChanged(object sender, EventArgs e) { bRestartRequired = true; } private void numericUpDownQueryAIAircraftsInterval_ValueChanged(object sender, EventArgs e) { bRestartRequired = true; } private void numericUpDownQueryAIHelicoptersInterval_ValueChanged(object sender, EventArgs e) { bRestartRequired = true; } private void numericUpDownQueryAIBoatsInterval_ValueChanged(object sender, EventArgs e) { bRestartRequired = true; } private void numericUpDownQueryAIGroudUnitsInterval_ValueChanged(object sender, EventArgs e) { bRestartRequired = true; } private void numericUpDownQueryAIAircraftsRadius_ValueChanged(object sender, EventArgs e) { bRestartRequired = true; } private void numericUpDownQueryAIHelicoptersRadius_ValueChanged(object sender, EventArgs e) { bRestartRequired = true; } private void numericUpDownQueryAIBoatsRadius_ValueChanged(object sender, EventArgs e) { bRestartRequired = true; } private void numericUpDownQueryAIGroudUnitsRadius_ValueChanged(object sender, EventArgs e) { bRestartRequired = true; } private void numericUpDownRefreshUserAircraft_ValueChanged(object sender, EventArgs e) { bRestartRequired = true; } private void numericUpDownRefreshUserPath_ValueChanged(object sender, EventArgs e) { bRestartRequired = true; } private void numericUpDownRefreshAIAircrafts_ValueChanged(object sender, EventArgs e) { bRestartRequired = true; } private void numericUpDownRefreshAIHelicopter_ValueChanged(object sender, EventArgs e) { bRestartRequired = true; } private void numericUpDownRefreshAIBoats_ValueChanged(object sender, EventArgs e) { bRestartRequired = true; } private void numericUpDownRefreshAIGroundUnits_ValueChanged(object sender, EventArgs e) { bRestartRequired = true; } private void numericUpDownServerPort_ValueChanged(object sender, EventArgs e) { bRestartRequired = true; } private void checkBoxLoadKMLFile_CheckedChanged(object sender, EventArgs e) { gconffixCurrent.bLoadKMLFile = checkBoxLoadKMLFile.Checked; } private void checkBoxUserPathPrediction_CheckedChanged(object sender, EventArgs e) { numericUpDownUserPathPrediction.Enabled = checkBoxUserPathPrediction.Checked; bRestartRequired = true; } private void numericUpDownUserPathPrediction_ValueChanged(object sender, EventArgs e) { bRestartRequired = true; } private void numericUpDownRefreshUserPrediction_ValueChanged(object sender, EventArgs e) { bRestartRequired = true; } private void checkBoxSaveLog_CheckedChanged(object sender, EventArgs e) { checkBoxSubFoldersForLog.Enabled = (checkBoxSaveLog.Checked); } private void radioButtonAccessLocalOnly_CheckedChanged(object sender, EventArgs e) { bRestartRequired = true; } private void radioButtonAccessRemote_CheckedChanged(object sender, EventArgs e) { bRestartRequired = true; } private void checkBoxAIAircraftsPredict_CheckedChanged(object sender, EventArgs e) { checkBoxAIAircraftsPredict_EnabledChanged(null, null); bRestartRequired = true; } private void checkBoxAIAircraftsPredict_EnabledChanged(object sender, EventArgs e) { checkBoxAIAircraftsPredictPoints.Enabled = (checkBoxAIAircraftsPredict.Enabled & checkBoxAIAircraftsPredict.Checked); } private void checkBoxAIHelicoptersPredict_CheckedChanged(object sender, EventArgs e) { checkBoxAIHelicoptersPredict_EnabledChanged(null, null); bRestartRequired = true; } private void checkBoxAIHelicoptersPredict_EnabledChanged(object sender, EventArgs e) { checkBoxAIHelicoptersPredictPoints.Enabled = (checkBoxAIHelicoptersPredict.Enabled & checkBoxAIHelicoptersPredict.Checked); } private void checkBoxAIBoatsPredict_CheckedChanged(object sender, EventArgs e) { checkBoxAIBoatsPredict_EnabledChanged(null, null); bRestartRequired = true; } private void checkBoxAIBoatsPredict_EnabledChanged(object sender, EventArgs e) { checkBoxAIBoatsPredictPoints.Enabled = (checkBoxAIBoatsPredict.Enabled & checkBoxAIBoatsPredict.Checked); } private void checkBoxAIGroundPredict_CheckedChanged(object sender, EventArgs e) { checkBoxAIGroundPredict_EnabledChanged(null, null); bRestartRequired = true; } private void checkBoxAIGroundPredict_EnabledChanged(object sender, EventArgs e) { checkBoxAIGroundPredictPoints.Enabled = (checkBoxAIGroundPredict.Enabled & checkBoxAIGroundPredict.Checked); } private void checkBoxAIAircraftsPredictPoints_CheckedChanged(object sender, EventArgs e) { bRestartRequired = true; } private void checkBoxAIHelicoptersPredictPoints_CheckedChanged(object sender, EventArgs e) { bRestartRequired = true; } private void checkBoxAIBoatsPredictPoints_CheckedChanged(object sender, EventArgs e) { bRestartRequired = true; } private void checkBoxAIGroundPredictPoints_CheckedChanged(object sender, EventArgs e) { bRestartRequired = true; } private void createGoogleEarthKMLFileToolStripMenuItem_DropDownIPClick(object sender, EventArgs e) { String szTemp = sender.ToString(); if (szTemp.Length < 7) return; szTemp = szTemp.Substring(7); String szKMLFile = ""; if (CompileKMLStartUpFileDynamic(szTemp, ref szKMLFile)) { safeShowMainDialog(0); if (saveFileDialogKMLFile.ShowDialog() == DialogResult.OK) { try { File.WriteAllText(saveFileDialogKMLFile.FileName, szKMLFile); } catch { MessageBox.Show("Could not save KML file!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error); } } safeHideMainDialog(); } } private void contextMenuStripNotifyIcon_Opening(object sender, CancelEventArgs e) { createGoogleEarthKMLFileToolStripMenuItem.DropDown.Items.Clear(); lock (lockIPAddressList) { bool bAddressFound = false; if (ipalLocal1 != null) { foreach (IPAddress ipaTemp in ipalLocal1) { bAddressFound = true; createGoogleEarthKMLFileToolStripMenuItem.DropDown.Items.Add("For IP " + ipaTemp.ToString(), null, createGoogleEarthKMLFileToolStripMenuItem_DropDownIPClick); } } if (ipalLocal2 != null) { foreach (IPAddress ipaTemp in ipalLocal2) { bAddressFound = true; createGoogleEarthKMLFileToolStripMenuItem.DropDown.Items.Add("For IP " + ipaTemp.ToString(), null, createGoogleEarthKMLFileToolStripMenuItem_DropDownIPClick); } } if (!bAddressFound) createGoogleEarthKMLFileToolStripMenuItem.Enabled = false; else createGoogleEarthKMLFileToolStripMenuItem.Enabled = true; } } private void button3_Click(object sender, EventArgs e) { if (MessageBox.Show("Are you sure you want to remove the selected items?", Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { //foreach (ListViewItem lviTemp in listViewFlightPlans.SelectedItems) //{ // listViewFlightPlans.Items.Remove(lviTemp); //} } } private void radioButton7_CheckedChanged(object sender, EventArgs e) { comboBox1.Enabled = textBox1.Enabled = textBox3.Enabled = !radioButton7.Checked; bRestartRequired = true; } private void radioButton6_CheckedChanged(object sender, EventArgs e) { comboBox1.Enabled = textBox1.Enabled = textBox3.Enabled = radioButton6.Checked; bRestartRequired = true; } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { bRestartRequired = true; } private void textBox1_TextChanged(object sender, EventArgs e) { bRestartRequired = true; } private void textBox3_TextChanged(object sender, EventArgs e) { bRestartRequired = true; } private void radioButton10_CheckedChanged(object sender, EventArgs e) { if (radioButton10.Checked) radioButton8.Checked = radioButton9.Checked = checkBox1.Enabled = false; } private void radioButton9_CheckedChanged(object sender, EventArgs e) { checkBox1.Enabled = radioButton9.Checked; } private void radioButton8_CheckedChanged(object sender, EventArgs e) { if (radioButton10.Checked) radioButton8.Checked = radioButton9.Checked = checkBox1.Enabled = false; } private void checkEnableOnStartup_CheckedChanged(object sender, EventArgs e) { } private void checkBox1_CheckedChanged(object sender, EventArgs e) { gconffixCurrent.bExitOnFsxExit = checkBox1.Checked; } private void checkShowInfoBalloons_CheckedChanged(object sender, EventArgs e) { } private void listBoxPathPrediction_SelectedIndexChanged(object sender, EventArgs e) { UpdateButtonStates(); } private void button2_Click(object sender, EventArgs e) { if (listBoxPathPrediction.SelectedItems.Count == 1) { int iIndex = listBoxPathPrediction.SelectedIndex; listBoxPathPrediction.Items.RemoveAt(iIndex); if (listBoxPathPrediction.SelectedItems.Count == 0) { if (listBoxPathPrediction.Items.Count > iIndex) listBoxPathPrediction.SelectedIndex = iIndex; else if (listBoxPathPrediction.Items.Count > 0) listBoxPathPrediction.SelectedIndex = listBoxPathPrediction.Items.Count - 1; } bRestartRequired = true; } } private void button1_Click(object sender, EventArgs e) { int iSeconds; if (frmAdd.ShowDialog(out iSeconds) == DialogResult.Cancel) return; ListBoxPredictionTimesItem lbptiTemp = new ListBoxPredictionTimesItem(); lbptiTemp.dTime = iSeconds; bool bInserted = false; for (int n = 0; n < listBoxPathPrediction.Items.Count; n++) { if (((ListBoxPredictionTimesItem)listBoxPathPrediction.Items[n]).dTime > lbptiTemp.dTime) { listBoxPathPrediction.Items.Insert(n, lbptiTemp); bInserted = true; break; } } if (!bInserted) listBoxPathPrediction.Items.Add(lbptiTemp); bRestartRequired = true; } #endregion } }
jtreml/fsxget
FSX Google Earth Tracker/Form1.cs
C#
gpl-2.0
158,843
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_ANDROID_EXTENSIONS_EXTENSION_INSTALL_UI_ANDROID_H_ #define CHROME_BROWSER_UI_ANDROID_EXTENSIONS_EXTENSION_INSTALL_UI_ANDROID_H_ #include "base/basictypes.h" #include "base/compiler_specific.h" #include "chrome/browser/extensions/extension_install_ui.h" class ExtensionInstallUIAndroid : public ExtensionInstallUI { public: ExtensionInstallUIAndroid(); virtual ~ExtensionInstallUIAndroid(); virtual void OnInstallSuccess(const extensions::Extension* extension, SkBitmap* icon) OVERRIDE; virtual void OnInstallFailure( const extensions::CrxInstallerError& error) OVERRIDE; private: DISALLOW_COPY_AND_ASSIGN(ExtensionInstallUIAndroid); }; #endif
qtekfun/htcDesire820Kernel
external/chromium_org/chrome/browser/ui/android/extensions/extension_install_ui_android.h
C
gpl-2.0
899
/* * linux/drivers/mmc/core/core.c * * Copyright (C) 2003-2004 Russell King, All Rights Reserved. * SD support Copyright (C) 2004 Ian Molton, All Rights Reserved. * Copyright (C) 2005-2008 Pierre Ossman, All Rights Reserved. * MMCv4 support Copyright (C) 2006 Philip Langdale, All Rights Reserved. * Copyright (C) 2016 XiaoMi, Inc. * * 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. */ #include <linux/module.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/completion.h> #include <linux/devfreq.h> #include <linux/device.h> #include <linux/delay.h> #include <linux/pagemap.h> #include <linux/err.h> #include <linux/leds.h> #include <linux/scatterlist.h> #include <linux/log2.h> #include <linux/regulator/consumer.h> #include <linux/pm_runtime.h> #include <linux/pm_wakeup.h> #include <linux/suspend.h> #include <linux/fault-inject.h> #include <linux/random.h> #include <linux/slab.h> #include <linux/of.h> #include <linux/pm.h> #include <linux/jiffies.h> #include <trace/events/mmc.h> #include <linux/mmc/card.h> #include <linux/mmc/host.h> #include <linux/mmc/mmc.h> #include <linux/mmc/sd.h> #include <linux/mmc/slot-gpio.h> #include "core.h" #include "bus.h" #include "host.h" #include "sdio_bus.h" #include "mmc_ops.h" #include "sd_ops.h" #include "sdio_ops.h" /* If the device is not responding */ #define MMC_CORE_TIMEOUT_MS (10 * 60 * 1000) /* 10 minute timeout */ /* * Background operations can take a long time, depending on the housekeeping * operations the card has to perform. */ #define MMC_BKOPS_MAX_TIMEOUT (30 * 1000) /* max time to wait in ms */ static struct workqueue_struct *workqueue; static const unsigned freqs[] = { 400000, 300000, 200000, 100000 }; /* * Enabling software CRCs on the data blocks can be a significant (30%) * performance cost, and for other reasons may not always be desired. * So we allow it it to be disabled. */ bool use_spi_crc = 1; module_param(use_spi_crc, bool, 0); /* * Internal function. Schedule delayed work in the MMC work queue. */ static int mmc_schedule_delayed_work(struct delayed_work *work, unsigned long delay) { return queue_delayed_work(workqueue, work, delay); } /* * Internal function. Flush all scheduled work from the MMC work queue. */ static void mmc_flush_scheduled_work(void) { flush_workqueue(workqueue); } #ifdef CONFIG_FAIL_MMC_REQUEST /* * Internal function. Inject random data errors. * If mmc_data is NULL no errors are injected. */ static void mmc_should_fail_request(struct mmc_host *host, struct mmc_request *mrq) { struct mmc_command *cmd = mrq->cmd; struct mmc_data *data = mrq->data; static const int data_errors[] = { -ETIMEDOUT, -EILSEQ, -EIO, }; if (!data) return; if (cmd->error || data->error || !should_fail(&host->fail_mmc_request, data->blksz * data->blocks)) return; data->error = data_errors[prandom_u32() % ARRAY_SIZE(data_errors)]; data->bytes_xfered = (prandom_u32() % (data->bytes_xfered >> 9)) << 9; data->fault_injected = true; } #else /* CONFIG_FAIL_MMC_REQUEST */ static inline void mmc_should_fail_request(struct mmc_host *host, struct mmc_request *mrq) { } #endif /* CONFIG_FAIL_MMC_REQUEST */ static bool mmc_is_data_request(struct mmc_request *mmc_request) { switch (mmc_request->cmd->opcode) { case MMC_READ_SINGLE_BLOCK: case MMC_READ_MULTIPLE_BLOCK: case MMC_WRITE_BLOCK: case MMC_WRITE_MULTIPLE_BLOCK: return true; default: return false; } } static void mmc_clk_scaling_start_busy(struct mmc_host *host, bool lock_needed) { struct mmc_devfeq_clk_scaling *clk_scaling = &host->clk_scaling; if (!clk_scaling->enable) return; if (lock_needed) spin_lock_bh(&clk_scaling->lock); clk_scaling->start_busy = ktime_get(); clk_scaling->is_busy_started = true; if (lock_needed) spin_unlock_bh(&clk_scaling->lock); } static void mmc_clk_scaling_stop_busy(struct mmc_host *host, bool lock_needed) { struct mmc_devfeq_clk_scaling *clk_scaling = &host->clk_scaling; if (!clk_scaling->enable) return; if (lock_needed) spin_lock_bh(&clk_scaling->lock); if (!clk_scaling->is_busy_started) { WARN_ON(1); goto out; } clk_scaling->total_busy_time_us += ktime_to_us(ktime_sub(ktime_get(), clk_scaling->start_busy)); pr_debug("%s: accumulated busy time is %lu usec\n", mmc_hostname(host), clk_scaling->total_busy_time_us); clk_scaling->is_busy_started = false; out: if (lock_needed) spin_unlock_bh(&clk_scaling->lock); } /** * mmc_cmdq_clk_scaling_start_busy() - start busy timer for data requests * @host: pointer to mmc host structure * @lock_needed: flag indication if locking is needed * * This function starts the busy timer in case it was not already started. */ void mmc_cmdq_clk_scaling_start_busy(struct mmc_host *host, bool lock_needed) { if (!host->clk_scaling.enable) return; if (lock_needed) spin_lock_bh(&host->clk_scaling.lock); if (!host->clk_scaling.is_busy_started && !test_bit(CMDQ_STATE_DCMD_ACTIVE, &host->cmdq_ctx.curr_state)) { host->clk_scaling.start_busy = ktime_get(); host->clk_scaling.is_busy_started = true; } if (lock_needed) spin_unlock_bh(&host->clk_scaling.lock); } EXPORT_SYMBOL(mmc_cmdq_clk_scaling_start_busy); /** * mmc_cmdq_clk_scaling_stop_busy() - stop busy timer for last data requests * @host: pointer to mmc host structure * @lock_needed: flag indication if locking is needed * * This function stops the busy timer in case it is the last data request. * In case the current request is not the last one, the busy time till * now will be accumulated and the counter will be restarted. */ void mmc_cmdq_clk_scaling_stop_busy(struct mmc_host *host, bool lock_needed, bool is_cmdq_dcmd) { if (!host->clk_scaling.enable) return; if (lock_needed) spin_lock_bh(&host->clk_scaling.lock); /* * For CQ mode: In completion of DCMD request, start busy time in * case of pending data requests */ if (is_cmdq_dcmd) { if (host->cmdq_ctx.data_active_reqs) { host->clk_scaling.is_busy_started = true; host->clk_scaling.start_busy = ktime_get(); } goto out; } host->clk_scaling.total_busy_time_us += ktime_to_us(ktime_sub(ktime_get(), host->clk_scaling.start_busy)); if (host->cmdq_ctx.data_active_reqs) { host->clk_scaling.is_busy_started = true; host->clk_scaling.start_busy = ktime_get(); } else { host->clk_scaling.is_busy_started = false; } out: if (lock_needed) spin_unlock_bh(&host->clk_scaling.lock); } EXPORT_SYMBOL(mmc_cmdq_clk_scaling_stop_busy); /** * mmc_can_scale_clk() - Check clock scaling capability * @host: pointer to mmc host structure */ bool mmc_can_scale_clk(struct mmc_host *host) { if (!host) { pr_err("bad host parameter\n"); WARN_ON(1); return false; } return host->caps2 & MMC_CAP2_CLK_SCALE; } EXPORT_SYMBOL(mmc_can_scale_clk); static int mmc_devfreq_get_dev_status(struct device *dev, struct devfreq_dev_status *status) { struct mmc_host *host = container_of(dev, struct mmc_host, class_dev); struct mmc_devfeq_clk_scaling *clk_scaling; if (!host) { pr_err("bad host parameter\n"); WARN_ON(1); return -EINVAL; } clk_scaling = &host->clk_scaling; if (!clk_scaling->enable) return 0; spin_lock_bh(&clk_scaling->lock); /* accumulate the busy time of ongoing work */ memset(status, 0, sizeof(*status)); if (clk_scaling->is_busy_started) { if (mmc_card_cmdq(host->card)) { /* the "busy-timer" will be restarted in case there * are pending data requests */ mmc_cmdq_clk_scaling_stop_busy(host, false, false); } else { mmc_clk_scaling_stop_busy(host, false); mmc_clk_scaling_start_busy(host, false); } } status->busy_time = clk_scaling->total_busy_time_us; status->total_time = ktime_to_us(ktime_sub(ktime_get(), clk_scaling->measure_interval_start)); clk_scaling->total_busy_time_us = 0; status->current_frequency = clk_scaling->curr_freq; clk_scaling->measure_interval_start = ktime_get(); pr_debug("%s: status: load = %lu%% - total_time=%lu busy_time = %lu, clk=%lu\n", mmc_hostname(host), (status->busy_time*100)/status->total_time, status->total_time, status->busy_time, status->current_frequency); spin_unlock_bh(&clk_scaling->lock); return 0; } static bool mmc_is_valid_state_for_clk_scaling(struct mmc_host *host) { struct mmc_card *card = host->card; u32 status; /* * If the current partition type is RPMB, clock switching may not * work properly as sending tuning command (CMD21) is illegal in * this mode. */ if (!card || (mmc_card_mmc(card) && (card->part_curr == EXT_CSD_PART_CONFIG_ACC_RPMB || mmc_card_doing_bkops(card)))) return false; if (mmc_send_status(card, &status)) { pr_err("%s: Get card status fail\n", mmc_hostname(card->host)); return false; } return R1_CURRENT_STATE(status) == R1_STATE_TRAN; } int mmc_cmdq_halt_on_empty_queue(struct mmc_host *host) { int err = 0; err = wait_event_interruptible(host->cmdq_ctx.queue_empty_wq, (!host->cmdq_ctx.active_reqs)); if (host->cmdq_ctx.active_reqs) { pr_err("%s: %s: unexpected active requests (%lu)\n", mmc_hostname(host), __func__, host->cmdq_ctx.active_reqs); return -EPERM; } err = mmc_cmdq_halt(host, true); if (err) { pr_err("%s: %s: mmc_cmdq_halt failed (%d)\n", mmc_hostname(host), __func__, err); goto out; } out: return err; } EXPORT_SYMBOL(mmc_cmdq_halt_on_empty_queue); int mmc_clk_update_freq(struct mmc_host *host, unsigned long freq, enum mmc_load state) { int err = 0; bool cmdq_mode; if (!host) { pr_err("bad host parameter\n"); WARN_ON(1); return -EINVAL; } mmc_host_clk_hold(host); cmdq_mode = mmc_card_cmdq(host->card); /* make sure the card supports the frequency we want */ if (unlikely(freq > host->card->clk_scaling_highest)) { freq = host->card->clk_scaling_highest; pr_warn("%s: %s: frequency was overridden to %lu\n", mmc_hostname(host), __func__, host->card->clk_scaling_highest); } if (unlikely(freq < host->card->clk_scaling_lowest)) { freq = host->card->clk_scaling_lowest; pr_warn("%s: %s: frequency was overridden to %lu\n", mmc_hostname(host), __func__, host->card->clk_scaling_lowest); } if (freq == host->clk_scaling.curr_freq) goto out; if (host->ops->notify_load) { err = host->ops->notify_load(host, state); if (err) { pr_err("%s: %s: fail on notify_load\n", mmc_hostname(host), __func__); goto out; } } if (cmdq_mode) { err = mmc_cmdq_halt_on_empty_queue(host); if (err) { pr_err("%s: %s: failed halting queue (%d)\n", mmc_hostname(host), __func__, err); goto halt_failed; } } if (!mmc_is_valid_state_for_clk_scaling(host)) { pr_debug("%s: invalid state for clock scaling - skipping", mmc_hostname(host)); goto invalid_state; } err = host->bus_ops->change_bus_speed(host, &freq); if (!err) host->clk_scaling.curr_freq = freq; else pr_err("%s: %s: failed (%d) at freq=%lu\n", mmc_hostname(host), __func__, err, freq); invalid_state: if (cmdq_mode) { if (mmc_cmdq_halt(host, false)) pr_err("%s: %s: cmdq unhalt failed\n", mmc_hostname(host), __func__); } halt_failed: if (err) { /* restore previous state */ if (host->ops->notify_load) if (host->ops->notify_load(host, host->clk_scaling.state)) pr_err("%s: %s: fail on notify_load restore\n", mmc_hostname(host), __func__); } out: mmc_host_clk_release(host); return err; } EXPORT_SYMBOL(mmc_clk_update_freq); static int mmc_devfreq_set_target(struct device *dev, unsigned long *freq, u32 devfreq_flags) { struct mmc_host *host = container_of(dev, struct mmc_host, class_dev); struct mmc_devfeq_clk_scaling *clk_scaling; int err = 0; int abort; if (!(host && freq)) { pr_err("%s: unexpected host/freq parameter\n", __func__); err = -EINVAL; goto out; } clk_scaling = &host->clk_scaling; if (!clk_scaling->enable) goto out; pr_debug("%s: target freq = %lu (%s)\n", mmc_hostname(host), *freq, current->comm); if ((clk_scaling->curr_freq == *freq) || clk_scaling->skip_clk_scale_freq_update) goto out; /* No need to scale the clocks if they are gated */ if (!host->ios.clock) goto out; spin_lock_bh(&clk_scaling->lock); if (clk_scaling->clk_scaling_in_progress) { pr_debug("%s: clocks scaling is already in-progress by mmc thread\n", mmc_hostname(host)); spin_unlock_bh(&clk_scaling->lock); goto out; } clk_scaling->need_freq_change = true; clk_scaling->target_freq = *freq; clk_scaling->state = *freq < clk_scaling->curr_freq ? MMC_LOAD_LOW : MMC_LOAD_HIGH; spin_unlock_bh(&clk_scaling->lock); abort = __mmc_claim_host(host, &clk_scaling->devfreq_abort); if (abort) goto out; /* * In case we were able to claim host there is no need to * defer the frequency change. It will be done now */ clk_scaling->need_freq_change = false; mmc_host_clk_hold(host); err = mmc_clk_update_freq(host, *freq, clk_scaling->state); if (err && err != -EAGAIN) pr_err("%s: clock scale to %lu failed with error %d\n", mmc_hostname(host), *freq, err); else pr_debug("%s: clock change to %lu finished successfully (%s)\n", mmc_hostname(host), *freq, current->comm); mmc_host_clk_release(host); mmc_release_host(host); out: return err; } /** * mmc_deferred_scaling() - scale clocks from data path (mmc thread context) * @host: pointer to mmc host structure * * This function does clock scaling in case "need_freq_change" flag was set * by the clock scaling logic. */ void mmc_deferred_scaling(struct mmc_host *host) { unsigned long target_freq; int err; if (!host->clk_scaling.enable) return; spin_lock_bh(&host->clk_scaling.lock); if (host->clk_scaling.clk_scaling_in_progress || !(host->clk_scaling.need_freq_change)) { spin_unlock_bh(&host->clk_scaling.lock); return; } atomic_inc(&host->clk_scaling.devfreq_abort); target_freq = host->clk_scaling.target_freq; host->clk_scaling.clk_scaling_in_progress = true; host->clk_scaling.need_freq_change = false; spin_unlock_bh(&host->clk_scaling.lock); pr_debug("%s: doing deferred frequency change (%lu) (%s)\n", mmc_hostname(host), target_freq, current->comm); err = mmc_clk_update_freq(host, target_freq, host->clk_scaling.state); if (err && err != -EAGAIN) pr_err("%s: failed on deferred scale clocks (%d)\n", mmc_hostname(host), err); else pr_debug("%s: clocks were successfully scaled to %lu (%s)\n", mmc_hostname(host), target_freq, current->comm); host->clk_scaling.clk_scaling_in_progress = false; atomic_dec(&host->clk_scaling.devfreq_abort); } EXPORT_SYMBOL(mmc_deferred_scaling); static int mmc_devfreq_create_freq_table(struct mmc_host *host) { int i; struct mmc_devfeq_clk_scaling *clk_scaling = &host->clk_scaling; pr_debug("%s: supported: lowest=%lu, highest=%lu\n", mmc_hostname(host), host->card->clk_scaling_lowest, host->card->clk_scaling_highest); if (!clk_scaling->freq_table) { pr_debug("%s: no frequency table defined - setting default\n", mmc_hostname(host)); clk_scaling->freq_table = kzalloc( 2*sizeof(*(clk_scaling->freq_table)), GFP_KERNEL); if (!clk_scaling->freq_table) return -ENOMEM; clk_scaling->freq_table[0] = host->card->clk_scaling_lowest; clk_scaling->freq_table[1] = host->card->clk_scaling_highest; clk_scaling->freq_table_sz = 2; goto out; } if (host->card->clk_scaling_lowest > clk_scaling->freq_table[0]) pr_debug("%s: frequency table undershot possible freq\n", mmc_hostname(host)); if (strcmp(mmc_hostname(host), "mmc1") == 0) { clk_scaling->freq_table[0] = host->card->clk_scaling_highest; } else { for (i = 0; i < clk_scaling->freq_table_sz; i++) { if (clk_scaling->freq_table[i] < host->card->clk_scaling_highest) { continue; } else { break; } } clk_scaling->freq_table[i] = host->card->clk_scaling_highest; clk_scaling->freq_table_sz = i + 1; } out: clk_scaling->devfreq_profile.freq_table = clk_scaling->freq_table; clk_scaling->devfreq_profile.max_state = clk_scaling->freq_table_sz; for (i = 0; i < clk_scaling->freq_table_sz; i++) pr_debug("%s: freq[%d] = %u\n", mmc_hostname(host), i, clk_scaling->freq_table[i]); return 0; } /** * mmc_init_devfreq_clk_scaling() - Initialize clock scaling * @host: pointer to mmc host structure * * Initialize clock scaling for supported hosts. It is assumed that the caller * ensure clock is running at maximum possible frequency before calling this * function. Shall use struct devfreq_simple_ondemand_data to configure * governor. */ int mmc_init_clk_scaling(struct mmc_host *host) { int err; if (!host || !host->card) { pr_err("%s: unexpected host/card parameters\n", __func__); return -EINVAL; } if (!mmc_can_scale_clk(host) || !host->bus_ops->change_bus_speed) { pr_debug("%s: clock scaling is not supported\n", mmc_hostname(host)); return 0; } pr_debug("registering %s dev (%p) to devfreq", mmc_hostname(host), mmc_classdev(host)); if (host->clk_scaling.devfreq) { pr_err("%s: dev is already registered for dev %p\n", mmc_hostname(host), mmc_dev(host)); return -EPERM; } spin_lock_init(&host->clk_scaling.lock); atomic_set(&host->clk_scaling.devfreq_abort, 0); host->clk_scaling.curr_freq = host->ios.clock; host->clk_scaling.clk_scaling_in_progress = false; host->clk_scaling.need_freq_change = false; host->clk_scaling.is_busy_started = false; host->clk_scaling.devfreq_profile.polling_ms = host->clk_scaling.polling_delay_ms; host->clk_scaling.devfreq_profile.get_dev_status = mmc_devfreq_get_dev_status; host->clk_scaling.devfreq_profile.target = mmc_devfreq_set_target; host->clk_scaling.devfreq_profile.initial_freq = host->ios.clock; host->clk_scaling.ondemand_gov_data.simple_scaling = true; host->clk_scaling.ondemand_gov_data.upthreshold = host->clk_scaling.upthreshold; host->clk_scaling.ondemand_gov_data.downdifferential = host->clk_scaling.upthreshold - host->clk_scaling.downthreshold; err = mmc_devfreq_create_freq_table(host); if (err) { pr_err("%s: fail to create devfreq frequency table\n", mmc_hostname(host)); return err; } pr_debug("%s: adding devfreq with: upthreshold=%u downthreshold=%u polling=%u\n", mmc_hostname(host), host->clk_scaling.ondemand_gov_data.upthreshold, host->clk_scaling.ondemand_gov_data.downdifferential, host->clk_scaling.devfreq_profile.polling_ms); host->clk_scaling.devfreq = devfreq_add_device( mmc_classdev(host), &host->clk_scaling.devfreq_profile, "simple_ondemand", &host->clk_scaling.ondemand_gov_data); if (!host->clk_scaling.devfreq) { pr_err("%s: unable to register with devfreq\n", mmc_hostname(host)); return -EPERM; } pr_debug("%s: clk scaling is enabled for device %s (%p) with devfreq %p (clock = %uHz)\n", mmc_hostname(host), dev_name(mmc_classdev(host)), mmc_classdev(host), host->clk_scaling.devfreq, host->ios.clock); host->clk_scaling.enable = true; return err; } EXPORT_SYMBOL(mmc_init_clk_scaling); /** * mmc_suspend_clk_scaling() - suspend clock scaling * @host: pointer to mmc host structure * * This API will suspend devfreq feature for the specific host. * The statistics collected by mmc will be cleared. * This function is intended to be called by the pm callbacks * (e.g. runtime_suspend, suspend) of the mmc device */ int mmc_suspend_clk_scaling(struct mmc_host *host) { int err; if (!host) { WARN(1, "bad host parameter\n"); return -EINVAL; } if (!mmc_can_scale_clk(host) || !host->clk_scaling.enable) return 0; if (!host->clk_scaling.devfreq) { pr_err("%s: %s: no devfreq is assosiated with this device\n", mmc_hostname(host), __func__); return -EPERM; } atomic_inc(&host->clk_scaling.devfreq_abort); wake_up(&host->wq); err = devfreq_suspend_device(host->clk_scaling.devfreq); if (err) { pr_err("%s: %s: failed to suspend devfreq\n", mmc_hostname(host), __func__); return err; } host->clk_scaling.enable = false; host->clk_scaling.total_busy_time_us = 0; pr_debug("%s: devfreq suspended\n", mmc_hostname(host)); return 0; } EXPORT_SYMBOL(mmc_suspend_clk_scaling); /** * mmc_resume_clk_scaling() - resume clock scaling * @host: pointer to mmc host structure * * This API will resume devfreq feature for the specific host. * This API is intended to be called by the pm callbacks * (e.g. runtime_suspend, suspend) of the mmc device */ int mmc_resume_clk_scaling(struct mmc_host *host) { int err = 0; u32 max_clk_idx = 0; u32 devfreq_max_clk = 0; u32 devfreq_min_clk = 0; if (!host) { WARN(1, "bad host parameter\n"); return -EINVAL; } if (!mmc_can_scale_clk(host)) return 0; if (!host->clk_scaling.devfreq) { pr_err("%s: %s: no devfreq is assosiated with this device\n", mmc_hostname(host), __func__); return -EPERM; } atomic_set(&host->clk_scaling.devfreq_abort, 0); max_clk_idx = host->clk_scaling.freq_table_sz - 1; devfreq_max_clk = host->clk_scaling.freq_table[max_clk_idx]; devfreq_min_clk = host->clk_scaling.freq_table[0]; host->clk_scaling.curr_freq = devfreq_max_clk; if (host->ios.clock < host->card->clk_scaling_highest) host->clk_scaling.curr_freq = devfreq_min_clk; host->clk_scaling.clk_scaling_in_progress = false; host->clk_scaling.need_freq_change = false; err = devfreq_resume_device(host->clk_scaling.devfreq); if (err) { pr_err("%s: %s: failed to resume devfreq (%d)\n", mmc_hostname(host), __func__, err); } else { host->clk_scaling.enable = true; pr_debug("%s: devfreq resumed\n", mmc_hostname(host)); } return err; } EXPORT_SYMBOL(mmc_resume_clk_scaling); /** * mmc_exit_devfreq_clk_scaling() - Disable clock scaling * @host: pointer to mmc host structure * * Disable clock scaling permanently. */ int mmc_exit_clk_scaling(struct mmc_host *host) { int err; if (!host) { pr_err("%s: bad host parameter\n", __func__); WARN_ON(1); return -EINVAL; } if (!mmc_can_scale_clk(host)) return 0; if (!host->clk_scaling.devfreq) { pr_err("%s: %s: no devfreq is assosiated with this device\n", mmc_hostname(host), __func__); return -EPERM; } err = mmc_suspend_clk_scaling(host); if (err) { pr_err("%s: %s: fail to suspend clock scaling (%d)\n", mmc_hostname(host), __func__, err); return err; } err = devfreq_remove_device(host->clk_scaling.devfreq); if (err) { pr_err("%s: remove devfreq failed (%d)\n", mmc_hostname(host), err); return err; } host->clk_scaling.devfreq = NULL; atomic_set(&host->clk_scaling.devfreq_abort, 1); pr_debug("%s: devfreq was removed\n", mmc_hostname(host)); return 0; } EXPORT_SYMBOL(mmc_exit_clk_scaling); /** * mmc_request_done - finish processing an MMC request * @host: MMC host which completed request * @mrq: MMC request which request * * MMC drivers should call this function when they have completed * their processing of a request. */ void mmc_request_done(struct mmc_host *host, struct mmc_request *mrq) { struct mmc_command *cmd = mrq->cmd; int err = cmd->error; #ifdef CONFIG_MMC_PERF_PROFILING ktime_t diff; #endif if (host->clk_scaling.is_busy_started) mmc_clk_scaling_stop_busy(host, true); if (err && cmd->retries && mmc_host_is_spi(host)) { if (cmd->resp[0] & R1_SPI_ILLEGAL_COMMAND) cmd->retries = 0; } if (err && cmd->retries && !mmc_card_removed(host->card)) { /* * Request starter must handle retries - see * mmc_wait_for_req_done(). */ if (mrq->done) mrq->done(mrq); } else { mmc_should_fail_request(host, mrq); led_trigger_event(host->led, LED_OFF); pr_debug("%s: req done (CMD%u): %d: %08x %08x %08x %08x\n", mmc_hostname(host), cmd->opcode, err, cmd->resp[0], cmd->resp[1], cmd->resp[2], cmd->resp[3]); if (mrq->data) { #ifdef CONFIG_MMC_PERF_PROFILING if (host->perf_enable) { diff = ktime_sub(ktime_get(), host->perf.start); if (mrq->data->flags == MMC_DATA_READ) { host->perf.rbytes_drv += mrq->data->bytes_xfered; host->perf.rtime_drv = ktime_add(host->perf.rtime_drv, diff); } else { host->perf.wbytes_drv += mrq->data->bytes_xfered; host->perf.wtime_drv = ktime_add(host->perf.wtime_drv, diff); } } #endif pr_debug("%s: %d bytes transferred: %d\n", mmc_hostname(host), mrq->data->bytes_xfered, mrq->data->error); trace_mmc_blk_rw_end(cmd->opcode, cmd->arg, mrq->data); } if (mrq->stop) { pr_debug("%s: (CMD%u): %d: %08x %08x %08x %08x\n", mmc_hostname(host), mrq->stop->opcode, mrq->stop->error, mrq->stop->resp[0], mrq->stop->resp[1], mrq->stop->resp[2], mrq->stop->resp[3]); } if (mrq->done) mrq->done(mrq); mmc_host_clk_release(host); } } EXPORT_SYMBOL(mmc_request_done); static void mmc_start_request(struct mmc_host *host, struct mmc_request *mrq) { #ifdef CONFIG_MMC_DEBUG unsigned int i, sz; struct scatterlist *sg; #endif if (mrq->sbc) { pr_debug("<%s: starting CMD%u arg %08x flags %08x>\n", mmc_hostname(host), mrq->sbc->opcode, mrq->sbc->arg, mrq->sbc->flags); } pr_debug("%s: starting CMD%u arg %08x flags %08x\n", mmc_hostname(host), mrq->cmd->opcode, mrq->cmd->arg, mrq->cmd->flags); if (mrq->data) { pr_debug("%s: blksz %d blocks %d flags %08x " "tsac %d ms nsac %d\n", mmc_hostname(host), mrq->data->blksz, mrq->data->blocks, mrq->data->flags, mrq->data->timeout_ns / 1000000, mrq->data->timeout_clks); } if (mrq->stop) { pr_debug("%s: CMD%u arg %08x flags %08x\n", mmc_hostname(host), mrq->stop->opcode, mrq->stop->arg, mrq->stop->flags); } WARN_ON(!host->claimed); mrq->cmd->error = 0; mrq->cmd->mrq = mrq; if (mrq->data) { BUG_ON(mrq->data->blksz > host->max_blk_size); BUG_ON(mrq->data->blocks > host->max_blk_count); BUG_ON(mrq->data->blocks * mrq->data->blksz > host->max_req_size); #ifdef CONFIG_MMC_DEBUG sz = 0; for_each_sg(mrq->data->sg, sg, mrq->data->sg_len, i) sz += sg->length; BUG_ON(sz != mrq->data->blocks * mrq->data->blksz); #endif mrq->cmd->data = mrq->data; mrq->data->error = 0; mrq->data->mrq = mrq; if (mrq->stop) { mrq->data->stop = mrq->stop; mrq->stop->error = 0; mrq->stop->mrq = mrq; } #ifdef CONFIG_MMC_PERF_PROFILING if (host->perf_enable) host->perf.start = ktime_get(); #endif } mmc_host_clk_hold(host); led_trigger_event(host->led, LED_FULL); if (mmc_is_data_request(mrq)) { mmc_deferred_scaling(host); mmc_clk_scaling_start_busy(host, true); } host->ops->request(host, mrq); } static void mmc_start_cmdq_request(struct mmc_host *host, struct mmc_request *mrq) { if (mrq->data) { pr_debug("%s: blksz %d blocks %d flags %08x tsac %lu ms nsac %d\n", mmc_hostname(host), mrq->data->blksz, mrq->data->blocks, mrq->data->flags, mrq->data->timeout_ns / NSEC_PER_MSEC, mrq->data->timeout_clks); BUG_ON(mrq->data->blksz > host->max_blk_size); BUG_ON(mrq->data->blocks > host->max_blk_count); BUG_ON(mrq->data->blocks * mrq->data->blksz > host->max_req_size); mrq->data->error = 0; mrq->data->mrq = mrq; } if (mrq->cmd) { mrq->cmd->error = 0; mrq->cmd->mrq = mrq; } mmc_host_clk_hold(host); if (likely(host->cmdq_ops->request)) host->cmdq_ops->request(host, mrq); else pr_err("%s: %s: issue request failed\n", mmc_hostname(host), __func__); } /** * mmc_blk_init_bkops_statistics - initialize bkops statistics * @card: MMC card to start BKOPS * * Initialize and enable the bkops statistics */ void mmc_blk_init_bkops_statistics(struct mmc_card *card) { int i; struct mmc_bkops_stats *stats; if (!card) return; stats = &card->bkops.stats; spin_lock(&stats->lock); stats->manual_start = 0; stats->hpi = 0; stats->auto_start = 0; stats->auto_stop = 0; for (i = 0 ; i < MMC_BKOPS_NUM_SEVERITY_LEVELS ; i++) stats->level[i] = 0; stats->enabled = true; spin_unlock(&stats->lock); } EXPORT_SYMBOL(mmc_blk_init_bkops_statistics); static void mmc_update_bkops_hpi(struct mmc_bkops_stats *stats) { spin_lock_irq(&stats->lock); if (stats->enabled) stats->hpi++; spin_unlock_irq(&stats->lock); } static void mmc_update_bkops_start(struct mmc_bkops_stats *stats) { spin_lock_irq(&stats->lock); if (stats->enabled) stats->manual_start++; spin_unlock_irq(&stats->lock); } static void mmc_update_bkops_auto_on(struct mmc_bkops_stats *stats) { spin_lock_irq(&stats->lock); if (stats->enabled) stats->auto_start++; spin_unlock_irq(&stats->lock); } static void mmc_update_bkops_auto_off(struct mmc_bkops_stats *stats) { spin_lock_irq(&stats->lock); if (stats->enabled) stats->auto_stop++; spin_unlock_irq(&stats->lock); } static void mmc_update_bkops_level(struct mmc_bkops_stats *stats, unsigned level) { BUG_ON(level >= MMC_BKOPS_NUM_SEVERITY_LEVELS); spin_lock_irq(&stats->lock); if (stats->enabled) stats->level[level]++; spin_unlock_irq(&stats->lock); } /** * mmc_set_auto_bkops - set auto BKOPS for supported cards * @card: MMC card to start BKOPS * @enable: enable/disable flag * * Configure the card to run automatic BKOPS. * * Should be called when host is claimed. */ int mmc_set_auto_bkops(struct mmc_card *card, bool enable) { int ret = 0; u8 bkops_en; BUG_ON(!card); enable = !!enable; if (unlikely(!mmc_card_support_auto_bkops(card))) { pr_err("%s: %s: card doesn't support auto bkops\n", mmc_hostname(card->host), __func__); return -EPERM; } if (enable) { if (mmc_card_doing_auto_bkops(card)) goto out; bkops_en = card->ext_csd.bkops_en | EXT_CSD_BKOPS_AUTO_EN; } else { if (!mmc_card_doing_auto_bkops(card)) goto out; bkops_en = card->ext_csd.bkops_en & ~EXT_CSD_BKOPS_AUTO_EN; } ret = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL, EXT_CSD_BKOPS_EN, bkops_en, 0); if (ret) { pr_err("%s: %s: error in setting auto bkops to %d (%d)\n", mmc_hostname(card->host), __func__, enable, ret); } else { if (enable) { mmc_card_set_auto_bkops(card); mmc_update_bkops_auto_on(&card->bkops.stats); } else { mmc_card_clr_auto_bkops(card); mmc_update_bkops_auto_off(&card->bkops.stats); } card->ext_csd.bkops_en = bkops_en; pr_debug("%s: %s: bkops state %x\n", mmc_hostname(card->host), __func__, bkops_en); } out: return ret; } EXPORT_SYMBOL(mmc_set_auto_bkops); /** * mmc_check_bkops - check BKOPS for supported cards * @card: MMC card to check BKOPS * * Read the BKOPS status in order to determine whether the * card requires bkops to be started. */ void mmc_check_bkops(struct mmc_card *card) { int err; BUG_ON(!card); if (mmc_card_doing_bkops(card)) return; err = mmc_read_bkops_status(card); if (err) { pr_err("%s: Failed to read bkops status: %d\n", mmc_hostname(card->host), err); return; } card->bkops.needs_check = false; mmc_update_bkops_level(&card->bkops.stats, card->ext_csd.raw_bkops_status); card->bkops.needs_bkops = card->ext_csd.raw_bkops_status > 0; } EXPORT_SYMBOL(mmc_check_bkops); /** * mmc_start_manual_bkops - start BKOPS for supported cards * @card: MMC card to start BKOPS * * Send START_BKOPS to the card. * The function should be called with claimed host. */ void mmc_start_manual_bkops(struct mmc_card *card) { int err; BUG_ON(!card); if (unlikely(!mmc_card_configured_manual_bkops(card))) return; if (mmc_card_doing_bkops(card)) return; err = __mmc_switch(card, EXT_CSD_CMD_SET_NORMAL, EXT_CSD_BKOPS_START, 1, 0, false, true, false); if (err) { pr_err("%s: Error %d starting manual bkops\n", mmc_hostname(card->host), err); } else { mmc_card_set_doing_bkops(card); mmc_update_bkops_start(&card->bkops.stats); card->bkops.needs_bkops = false; } } EXPORT_SYMBOL(mmc_start_manual_bkops); /* * mmc_wait_data_done() - done callback for data request * @mrq: done data request * * Wakes up mmc context, passed as a callback to host controller driver */ static void mmc_wait_data_done(struct mmc_request *mrq) { unsigned long flags; struct mmc_context_info *context_info = &mrq->host->context_info; spin_lock_irqsave(&context_info->lock, flags); context_info->is_done_rcv = true; wake_up_interruptible(&context_info->wait); spin_unlock_irqrestore(&context_info->lock, flags); } static void mmc_wait_done(struct mmc_request *mrq) { complete(&mrq->completion); } /* *__mmc_start_data_req() - starts data request * @host: MMC host to start the request * @mrq: data request to start * * Sets the done callback to be called when request is completed by the card. * Starts data mmc request execution */ static int __mmc_start_data_req(struct mmc_host *host, struct mmc_request *mrq) { mrq->done = mmc_wait_data_done; mrq->host = host; if (mmc_card_removed(host->card)) { mrq->cmd->error = -ENOMEDIUM; mmc_wait_data_done(mrq); return -ENOMEDIUM; } mmc_start_request(host, mrq); return 0; } static int __mmc_start_req(struct mmc_host *host, struct mmc_request *mrq) { init_completion(&mrq->completion); mrq->done = mmc_wait_done; if (mmc_card_removed(host->card)) { mrq->cmd->error = -ENOMEDIUM; complete(&mrq->completion); return -ENOMEDIUM; } mmc_start_request(host, mrq); return 0; } /* * mmc_wait_for_data_req_done() - wait for request completed * @host: MMC host to prepare the command. * @mrq: MMC request to wait for * * Blocks MMC context till host controller will ack end of data request * execution or new request notification arrives from the block layer. * Handles command retries. * * Returns enum mmc_blk_status after checking errors. */ static int mmc_wait_for_data_req_done(struct mmc_host *host, struct mmc_request *mrq, struct mmc_async_req *next_req) { struct mmc_command *cmd; struct mmc_context_info *context_info = &host->context_info; int err; bool is_done_rcv = false; unsigned long flags; while (1) { wait_event_interruptible(context_info->wait, (context_info->is_done_rcv || context_info->is_new_req)); spin_lock_irqsave(&context_info->lock, flags); is_done_rcv = context_info->is_done_rcv; context_info->is_waiting_last_req = false; spin_unlock_irqrestore(&context_info->lock, flags); if (is_done_rcv) { context_info->is_done_rcv = false; context_info->is_new_req = false; cmd = mrq->cmd; if (!cmd->error || !cmd->retries || mmc_card_removed(host->card)) { err = host->areq->err_check(host->card, host->areq); break; /* return err */ } else { pr_info("%s: req failed (CMD%u): %d, retrying...\n", mmc_hostname(host), cmd->opcode, cmd->error); cmd->retries--; cmd->error = 0; host->ops->request(host, mrq); continue; /* wait for done/new event again */ } } else if (context_info->is_new_req) { context_info->is_new_req = false; if (!next_req) { err = MMC_BLK_NEW_REQUEST; break; /* return err */ } } } return err; } static void mmc_wait_for_req_done(struct mmc_host *host, struct mmc_request *mrq) { struct mmc_command *cmd; while (1) { wait_for_completion_io(&mrq->completion); cmd = mrq->cmd; /* * If host has timed out waiting for the sanitize/bkops * to complete, card might be still in programming state * so let's try to bring the card out of programming * state. */ if ((cmd->bkops_busy || cmd->sanitize_busy) && cmd->error == -ETIMEDOUT) { if (!mmc_interrupt_hpi(host->card)) { pr_warn("%s: %s: Interrupted sanitize/bkops\n", mmc_hostname(host), __func__); cmd->error = 0; break; } else { pr_err("%s: %s: Failed to interrupt sanitize\n", mmc_hostname(host), __func__); } } if (!cmd->error || !cmd->retries || mmc_card_removed(host->card)) break; pr_debug("%s: req failed (CMD%u): %d, retrying...\n", mmc_hostname(host), cmd->opcode, cmd->error); cmd->retries--; cmd->error = 0; host->ops->request(host, mrq); } } /** * mmc_pre_req - Prepare for a new request * @host: MMC host to prepare command * @mrq: MMC request to prepare for * @is_first_req: true if there is no previous started request * that may run in parellel to this call, otherwise false * * mmc_pre_req() is called in prior to mmc_start_req() to let * host prepare for the new request. Preparation of a request may be * performed while another request is running on the host. */ static void mmc_pre_req(struct mmc_host *host, struct mmc_request *mrq, bool is_first_req) { if (host->ops->pre_req) { mmc_host_clk_hold(host); host->ops->pre_req(host, mrq, is_first_req); mmc_host_clk_release(host); } } /** * mmc_post_req - Post process a completed request * @host: MMC host to post process command * @mrq: MMC request to post process for * @err: Error, if non zero, clean up any resources made in pre_req * * Let the host post process a completed request. Post processing of * a request may be performed while another reuqest is running. */ static void mmc_post_req(struct mmc_host *host, struct mmc_request *mrq, int err) { if (host->ops->post_req) { mmc_host_clk_hold(host); host->ops->post_req(host, mrq, err); mmc_host_clk_release(host); } } /** * mmc_cmdq_discard_card_queue - discard the task[s] in the device * @host: host instance * @tasks: mask of tasks to be knocked off * 0: remove all queued tasks */ int mmc_cmdq_discard_queue(struct mmc_host *host, u32 tasks) { return mmc_discard_queue(host, tasks); } EXPORT_SYMBOL(mmc_cmdq_discard_queue); /** * mmc_cmdq_post_req - post process of a completed request * @host: host instance * @tag: the request tag. * @err: non-zero is error, success otherwise */ void mmc_cmdq_post_req(struct mmc_host *host, int tag, int err) { if (likely(host->cmdq_ops->post_req)) host->cmdq_ops->post_req(host, tag, err); } EXPORT_SYMBOL(mmc_cmdq_post_req); /** * mmc_cmdq_halt - halt/un-halt the command queue engine * @host: host instance * @halt: true - halt, un-halt otherwise * * Host halts the command queue engine. It should complete * the ongoing transfer and release the bus. * All legacy commands can be sent upon successful * completion of this function. * Returns 0 on success, negative otherwise */ int mmc_cmdq_halt(struct mmc_host *host, bool halt) { int err = 0; if ((halt && mmc_host_halt(host)) || (!halt && !mmc_host_halt(host))) { pr_debug("%s: %s: CQE is already %s\n", mmc_hostname(host), __func__, halt ? "halted" : "un-halted"); return 0; } mmc_host_clk_hold(host); if (host->cmdq_ops->halt) { err = host->cmdq_ops->halt(host, halt); if (!err && host->ops->notify_halt) host->ops->notify_halt(host, halt); if (!err && halt) mmc_host_set_halt(host); else if (!err && !halt) { mmc_host_clr_halt(host); wake_up(&host->cmdq_ctx.wait); } } else { err = -ENOSYS; } mmc_host_clk_release(host); return err; } EXPORT_SYMBOL(mmc_cmdq_halt); int mmc_cmdq_start_req(struct mmc_host *host, struct mmc_cmdq_req *cmdq_req) { struct mmc_request *mrq = &cmdq_req->mrq; mrq->host = host; if (mmc_card_removed(host->card)) { mrq->cmd->error = -ENOMEDIUM; return -ENOMEDIUM; } mmc_start_cmdq_request(host, mrq); return 0; } EXPORT_SYMBOL(mmc_cmdq_start_req); static void mmc_cmdq_dcmd_req_done(struct mmc_request *mrq) { mmc_host_clk_release(mrq->host); complete(&mrq->completion); } int mmc_cmdq_wait_for_dcmd(struct mmc_host *host, struct mmc_cmdq_req *cmdq_req) { struct mmc_request *mrq = &cmdq_req->mrq; struct mmc_command *cmd = mrq->cmd; int err = 0; init_completion(&mrq->completion); mrq->done = mmc_cmdq_dcmd_req_done; err = mmc_cmdq_start_req(host, cmdq_req); if (err) return err; wait_for_completion_io(&mrq->completion); if (cmd->error) { pr_err("%s: DCMD %d failed with err %d\n", mmc_hostname(host), cmd->opcode, cmd->error); err = cmd->error; mmc_host_clk_hold(host); host->cmdq_ops->dumpstate(host); mmc_host_clk_release(host); } return err; } EXPORT_SYMBOL(mmc_cmdq_wait_for_dcmd); int mmc_cmdq_prepare_flush(struct mmc_command *cmd) { return __mmc_switch_cmdq_mode(cmd, EXT_CSD_CMD_SET_NORMAL, EXT_CSD_FLUSH_CACHE, 1, 0, true, true); } EXPORT_SYMBOL(mmc_cmdq_prepare_flush); /** * mmc_start_req - start a non-blocking request * @host: MMC host to start command * @areq: async request to start * @error: out parameter returns 0 for success, otherwise non zero * * Start a new MMC custom command request for a host. * If there is on ongoing async request wait for completion * of that request and start the new one and return. * Does not wait for the new request to complete. * * Returns the completed request, NULL in case of none completed. * Wait for the an ongoing request (previoulsy started) to complete and * return the completed request. If there is no ongoing request, NULL * is returned without waiting. NULL is not an error condition. */ struct mmc_async_req *mmc_start_req(struct mmc_host *host, struct mmc_async_req *areq, int *error) { int err = 0; int start_err = 0; struct mmc_async_req *data = host->areq; /* Prepare a new request */ if (areq) mmc_pre_req(host, areq->mrq, !host->areq); if (host->areq) { err = mmc_wait_for_data_req_done(host, host->areq->mrq, areq); if (err == MMC_BLK_NEW_REQUEST) { if (error) *error = err; /* * The previous request was not completed, * nothing to return */ return NULL; } /* * Check BKOPS urgency for each R1 response */ if (host->card && mmc_card_mmc(host->card) && ((mmc_resp_type(host->areq->mrq->cmd) == MMC_RSP_R1) || (mmc_resp_type(host->areq->mrq->cmd) == MMC_RSP_R1B)) && (host->areq->mrq->cmd->resp[0] & R1_EXCEPTION_EVENT)) mmc_check_bkops(host->card); } if (!err && areq) { trace_mmc_blk_rw_start(areq->mrq->cmd->opcode, areq->mrq->cmd->arg, areq->mrq->data); start_err = __mmc_start_data_req(host, areq->mrq); } if (host->areq) mmc_post_req(host, host->areq->mrq, 0); if (err && areq) mmc_post_req(host, areq->mrq, -EINVAL); if (err) host->areq = NULL; else host->areq = areq; if (error) *error = err; return data; } EXPORT_SYMBOL(mmc_start_req); /** * mmc_wait_for_req - start a request and wait for completion * @host: MMC host to start command * @mrq: MMC request to start * * Start a new MMC custom command request for a host, and wait * for the command to complete. Does not attempt to parse the * response. */ void mmc_wait_for_req(struct mmc_host *host, struct mmc_request *mrq) { __mmc_start_req(host, mrq); mmc_wait_for_req_done(host, mrq); } EXPORT_SYMBOL(mmc_wait_for_req); /** * mmc_interrupt_hpi - Issue for High priority Interrupt * @card: the MMC card associated with the HPI transfer * * Issued High Priority Interrupt, and check for card status * until out-of prg-state. */ int mmc_interrupt_hpi(struct mmc_card *card) { int err; u32 status; unsigned long prg_wait; BUG_ON(!card); if (!card->ext_csd.hpi_en) { pr_info("%s: HPI enable bit unset\n", mmc_hostname(card->host)); return 1; } mmc_claim_host(card->host); err = mmc_send_status(card, &status); if (err) { pr_err("%s: Get card status fail\n", mmc_hostname(card->host)); goto out; } switch (R1_CURRENT_STATE(status)) { case R1_STATE_IDLE: case R1_STATE_READY: case R1_STATE_STBY: case R1_STATE_TRAN: /* * In idle and transfer states, HPI is not needed and the caller * can issue the next intended command immediately */ goto out; case R1_STATE_PRG: break; default: /* In all other states, it's illegal to issue HPI */ pr_debug("%s: HPI cannot be sent. Card state=%d\n", mmc_hostname(card->host), R1_CURRENT_STATE(status)); err = -EINVAL; goto out; } err = mmc_send_hpi_cmd(card, &status); prg_wait = jiffies + msecs_to_jiffies(card->ext_csd.out_of_int_time); do { err = mmc_send_status(card, &status); if (!err && R1_CURRENT_STATE(status) == R1_STATE_TRAN) break; if (time_after(jiffies, prg_wait)) { err = mmc_send_status(card, &status); if (!err && R1_CURRENT_STATE(status) != R1_STATE_TRAN) err = -ETIMEDOUT; else break; } } while (!err); out: mmc_release_host(card->host); return err; } EXPORT_SYMBOL(mmc_interrupt_hpi); /** * mmc_wait_for_cmd - start a command and wait for completion * @host: MMC host to start command * @cmd: MMC command to start * @retries: maximum number of retries * * Start a new MMC command for a host, and wait for the command * to complete. Return any error that occurred while the command * was executing. Do not attempt to parse the response. */ int mmc_wait_for_cmd(struct mmc_host *host, struct mmc_command *cmd, int retries) { struct mmc_request mrq = {NULL}; WARN_ON(!host->claimed); memset(cmd->resp, 0, sizeof(cmd->resp)); cmd->retries = retries; mrq.cmd = cmd; cmd->data = NULL; mmc_wait_for_req(host, &mrq); return cmd->error; } EXPORT_SYMBOL(mmc_wait_for_cmd); /** * mmc_stop_bkops - stop ongoing BKOPS * @card: MMC card to check BKOPS * * Send HPI command to stop ongoing background operations to * allow rapid servicing of foreground operations, e.g. read/ * writes. Wait until the card comes out of the programming state * to avoid errors in servicing read/write requests. */ int mmc_stop_bkops(struct mmc_card *card) { int err = 0; BUG_ON(!card); if (unlikely(!mmc_card_configured_manual_bkops(card))) goto out; if (!mmc_card_doing_bkops(card)) goto out; err = mmc_interrupt_hpi(card); /* * If err is EINVAL, we can't issue an HPI. * It should complete the BKOPS. */ if (!err || (err == -EINVAL)) { mmc_card_clr_doing_bkops(card); mmc_update_bkops_hpi(&card->bkops.stats); err = 0; } out: return err; } EXPORT_SYMBOL(mmc_stop_bkops); int mmc_read_bkops_status(struct mmc_card *card) { int err; u8 *ext_csd; /* * In future work, we should consider storing the entire ext_csd. */ ext_csd = kmalloc(512, GFP_KERNEL); if (!ext_csd) { pr_err("%s: could not allocate buffer to receive the ext_csd.\n", mmc_hostname(card->host)); return -ENOMEM; } mmc_claim_host(card->host); err = mmc_send_ext_csd(card, ext_csd); mmc_release_host(card->host); if (err) goto out; card->ext_csd.raw_bkops_status = ext_csd[EXT_CSD_BKOPS_STATUS] & MMC_BKOPS_URGENCY_MASK; card->ext_csd.raw_exception_status = ext_csd[EXT_CSD_EXP_EVENTS_STATUS] & (EXT_CSD_URGENT_BKOPS | EXT_CSD_DYNCAP_NEEDED | EXT_CSD_SYSPOOL_EXHAUSTED | EXT_CSD_PACKED_FAILURE); out: kfree(ext_csd); return err; } EXPORT_SYMBOL(mmc_read_bkops_status); /** * mmc_set_data_timeout - set the timeout for a data command * @data: data phase for command * @card: the MMC card associated with the data transfer * * Computes the data timeout parameters according to the * correct algorithm given the card type. */ void mmc_set_data_timeout(struct mmc_data *data, const struct mmc_card *card) { unsigned int mult; if (!card) { WARN_ON(1); return; } /* * SDIO cards only define an upper 1 s limit on access. */ if (mmc_card_sdio(card)) { data->timeout_ns = 1000000000; data->timeout_clks = 0; return; } /* * SD cards use a 100 multiplier rather than 10 */ mult = mmc_card_sd(card) ? 100 : 10; /* * Scale up the multiplier (and therefore the timeout) by * the r2w factor for writes. */ if (data->flags & MMC_DATA_WRITE) mult <<= card->csd.r2w_factor; data->timeout_ns = card->csd.tacc_ns * mult; data->timeout_clks = card->csd.tacc_clks * mult; /* * SD cards also have an upper limit on the timeout. */ if (mmc_card_sd(card)) { unsigned int timeout_us, limit_us; timeout_us = data->timeout_ns / 1000; if (mmc_host_clk_rate(card->host)) timeout_us += data->timeout_clks * 1000 / (mmc_host_clk_rate(card->host) / 1000); if (data->flags & MMC_DATA_WRITE) /* * The MMC spec "It is strongly recommended * for hosts to implement more than 500ms * timeout value even if the card indicates * the 250ms maximum busy length." Even the * previous value of 300ms is known to be * insufficient for some cards. */ limit_us = 3000000; else limit_us = 100000; /* * SDHC cards always use these fixed values. */ if (timeout_us > limit_us || mmc_card_blockaddr(card)) { data->timeout_ns = limit_us * 1000; data->timeout_clks = 0; } /* assign limit value if invalid */ if (timeout_us == 0) data->timeout_ns = limit_us * 1000; } /* * Some cards require longer data read timeout than indicated in CSD. * Address this by setting the read timeout to a "reasonably high" * value. For the cards tested, 600ms has proven enough. If necessary, * this value can be increased if other problematic cards require this. */ if (mmc_card_long_read_time(card) && data->flags & MMC_DATA_READ) { data->timeout_ns = 600000000; data->timeout_clks = 0; } /* * Some cards need very high timeouts if driven in SPI mode. * The worst observed timeout was 900ms after writing a * continuous stream of data until the internal logic * overflowed. */ if (mmc_host_is_spi(card->host)) { if (data->flags & MMC_DATA_WRITE) { if (data->timeout_ns < 1000000000) data->timeout_ns = 1000000000; /* 1s */ } else { if (data->timeout_ns < 100000000) data->timeout_ns = 100000000; /* 100ms */ } } /* Increase the timeout values for some bad INAND MCP devices */ if (card->quirks & MMC_QUIRK_INAND_DATA_TIMEOUT) { data->timeout_ns = 4000000000u; /* 4s */ data->timeout_clks = 0; } } EXPORT_SYMBOL(mmc_set_data_timeout); /** * mmc_align_data_size - pads a transfer size to a more optimal value * @card: the MMC card associated with the data transfer * @sz: original transfer size * * Pads the original data size with a number of extra bytes in * order to avoid controller bugs and/or performance hits * (e.g. some controllers revert to PIO for certain sizes). * * Returns the improved size, which might be unmodified. * * Note that this function is only relevant when issuing a * single scatter gather entry. */ unsigned int mmc_align_data_size(struct mmc_card *card, unsigned int sz) { /* * FIXME: We don't have a system for the controller to tell * the core about its problems yet, so for now we just 32-bit * align the size. */ sz = ((sz + 3) / 4) * 4; return sz; } EXPORT_SYMBOL(mmc_align_data_size); /** * __mmc_claim_host - exclusively claim a host * @host: mmc host to claim * @abort: whether or not the operation should be aborted * * Claim a host for a set of operations. If @abort is non null and * dereference a non-zero value then this will return prematurely with * that non-zero value without acquiring the lock. Returns zero * with the lock held otherwise. */ int __mmc_claim_host(struct mmc_host *host, atomic_t *abort) { DECLARE_WAITQUEUE(wait, current); unsigned long flags; int stop; might_sleep(); add_wait_queue(&host->wq, &wait); spin_lock_irqsave(&host->lock, flags); while (1) { set_current_state(TASK_UNINTERRUPTIBLE); stop = abort ? atomic_read(abort) : 0; if (stop || !host->claimed || host->claimer == current) break; spin_unlock_irqrestore(&host->lock, flags); schedule(); spin_lock_irqsave(&host->lock, flags); } set_current_state(TASK_RUNNING); if (!stop) { host->claimed = 1; host->claimer = current; host->claim_cnt += 1; } else wake_up(&host->wq); spin_unlock_irqrestore(&host->lock, flags); remove_wait_queue(&host->wq, &wait); if (host->ops->enable && !stop && host->claim_cnt == 1) host->ops->enable(host); return stop; } EXPORT_SYMBOL(__mmc_claim_host); /** * mmc_release_host - release a host * @host: mmc host to release * * Release a MMC host, allowing others to claim the host * for their operations. */ void mmc_release_host(struct mmc_host *host) { unsigned long flags; WARN_ON(!host->claimed); if (host->ops->disable && host->claim_cnt == 1) host->ops->disable(host); spin_lock_irqsave(&host->lock, flags); if (--host->claim_cnt) { /* Release for nested claim */ spin_unlock_irqrestore(&host->lock, flags); } else { host->claimed = 0; host->claimer = NULL; spin_unlock_irqrestore(&host->lock, flags); wake_up(&host->wq); } } EXPORT_SYMBOL(mmc_release_host); /* * This is a helper function, which fetches a runtime pm reference for the * card device and also claims the host. */ void mmc_get_card(struct mmc_card *card) { pm_runtime_get_sync(&card->dev); mmc_claim_host(card->host); } EXPORT_SYMBOL(mmc_get_card); /* * This is a helper function, which releases the host and drops the runtime * pm reference for the card device. */ void mmc_put_card(struct mmc_card *card) { mmc_release_host(card->host); pm_runtime_mark_last_busy(&card->dev); pm_runtime_put_autosuspend(&card->dev); } EXPORT_SYMBOL(mmc_put_card); /* * Internal function that does the actual ios call to the host driver, * optionally printing some debug output. */ void mmc_set_ios(struct mmc_host *host) { struct mmc_ios *ios = &host->ios; pr_debug("%s: clock %uHz busmode %u powermode %u cs %u Vdd %u " "width %u timing %u\n", mmc_hostname(host), ios->clock, ios->bus_mode, ios->power_mode, ios->chip_select, ios->vdd, ios->bus_width, ios->timing); if (ios->clock > 0) mmc_set_ungated(host); host->ops->set_ios(host, ios); if (ios->old_rate != ios->clock) { if (likely(ios->clk_ts)) { char trace_info[80]; snprintf(trace_info, 80, "%s: freq_KHz %d --> %d | t = %d", mmc_hostname(host), ios->old_rate / 1000, ios->clock / 1000, jiffies_to_msecs( (long)jiffies - (long)ios->clk_ts)); trace_mmc_clk(trace_info); } ios->old_rate = ios->clock; ios->clk_ts = jiffies; } } EXPORT_SYMBOL(mmc_set_ios); /* * Control chip select pin on a host. */ void mmc_set_chip_select(struct mmc_host *host, int mode) { mmc_host_clk_hold(host); host->ios.chip_select = mode; mmc_set_ios(host); mmc_host_clk_release(host); } /* * Sets the host clock to the highest possible frequency that * is below "hz". */ static void __mmc_set_clock(struct mmc_host *host, unsigned int hz) { WARN_ON(hz && hz < host->f_min); if (hz > host->f_max) hz = host->f_max; host->ios.clock = hz; mmc_set_ios(host); } void mmc_set_clock(struct mmc_host *host, unsigned int hz) { mmc_host_clk_hold(host); __mmc_set_clock(host, hz); mmc_host_clk_release(host); } #ifdef CONFIG_MMC_CLKGATE /* * This gates the clock by setting it to 0 Hz. */ void mmc_gate_clock(struct mmc_host *host) { unsigned long flags; WARN_ON(!host->ios.clock); spin_lock_irqsave(&host->clk_lock, flags); host->clk_old = host->ios.clock; host->ios.clock = 0; host->clk_gated = true; spin_unlock_irqrestore(&host->clk_lock, flags); mmc_set_ios(host); } /* * This restores the clock from gating by using the cached * clock value. */ void mmc_ungate_clock(struct mmc_host *host) { /* * We should previously have gated the clock, so the clock shall * be 0 here! The clock may however be 0 during initialization, * when some request operations are performed before setting * the frequency. When ungate is requested in that situation * we just ignore the call. */ if (host->clk_old) { WARN_ON(host->ios.clock); /* This call will also set host->clk_gated to false */ __mmc_set_clock(host, host->clk_old); } } void mmc_set_ungated(struct mmc_host *host) { unsigned long flags; /* * We've been given a new frequency while the clock is gated, * so make sure we regard this as ungating it. */ spin_lock_irqsave(&host->clk_lock, flags); host->clk_gated = false; spin_unlock_irqrestore(&host->clk_lock, flags); } #else void mmc_set_ungated(struct mmc_host *host) { } #endif int mmc_execute_tuning(struct mmc_card *card) { struct mmc_host *host = card->host; u32 opcode; int err; if (!host->ops->execute_tuning) return 0; if (mmc_card_mmc(card)) opcode = MMC_SEND_TUNING_BLOCK_HS200; else opcode = MMC_SEND_TUNING_BLOCK; mmc_host_clk_hold(host); err = host->ops->execute_tuning(host, opcode); mmc_host_clk_release(host); if (err) pr_err("%s: tuning execution failed\n", mmc_hostname(host)); return err; } /* * Change the bus mode (open drain/push-pull) of a host. */ void mmc_set_bus_mode(struct mmc_host *host, unsigned int mode) { mmc_host_clk_hold(host); host->ios.bus_mode = mode; mmc_set_ios(host); mmc_host_clk_release(host); } /* * Change data bus width of a host. */ void mmc_set_bus_width(struct mmc_host *host, unsigned int width) { mmc_host_clk_hold(host); host->ios.bus_width = width; mmc_set_ios(host); mmc_host_clk_release(host); } /** * mmc_vdd_to_ocrbitnum - Convert a voltage to the OCR bit number * @vdd: voltage (mV) * @low_bits: prefer low bits in boundary cases * * This function returns the OCR bit number according to the provided @vdd * value. If conversion is not possible a negative errno value returned. * * Depending on the @low_bits flag the function prefers low or high OCR bits * on boundary voltages. For example, * with @low_bits = true, 3300 mV translates to ilog2(MMC_VDD_32_33); * with @low_bits = false, 3300 mV translates to ilog2(MMC_VDD_33_34); * * Any value in the [1951:1999] range translates to the ilog2(MMC_VDD_20_21). */ static int mmc_vdd_to_ocrbitnum(int vdd, bool low_bits) { const int max_bit = ilog2(MMC_VDD_35_36); int bit; if (vdd < 1650 || vdd > 3600) return -EINVAL; if (vdd >= 1650 && vdd <= 1950) return ilog2(MMC_VDD_165_195); if (low_bits) vdd -= 1; /* Base 2000 mV, step 100 mV, bit's base 8. */ bit = (vdd - 2000) / 100 + 8; if (bit > max_bit) return max_bit; return bit; } /** * mmc_vddrange_to_ocrmask - Convert a voltage range to the OCR mask * @vdd_min: minimum voltage value (mV) * @vdd_max: maximum voltage value (mV) * * This function returns the OCR mask bits according to the provided @vdd_min * and @vdd_max values. If conversion is not possible the function returns 0. * * Notes wrt boundary cases: * This function sets the OCR bits for all boundary voltages, for example * [3300:3400] range is translated to MMC_VDD_32_33 | MMC_VDD_33_34 | * MMC_VDD_34_35 mask. */ u32 mmc_vddrange_to_ocrmask(int vdd_min, int vdd_max) { u32 mask = 0; if (vdd_max < vdd_min) return 0; /* Prefer high bits for the boundary vdd_max values. */ vdd_max = mmc_vdd_to_ocrbitnum(vdd_max, false); if (vdd_max < 0) return 0; /* Prefer low bits for the boundary vdd_min values. */ vdd_min = mmc_vdd_to_ocrbitnum(vdd_min, true); if (vdd_min < 0) return 0; /* Fill the mask, from max bit to min bit. */ while (vdd_max >= vdd_min) mask |= 1 << vdd_max--; return mask; } EXPORT_SYMBOL(mmc_vddrange_to_ocrmask); #ifdef CONFIG_OF /** * mmc_of_parse_voltage - return mask of supported voltages * @np: The device node need to be parsed. * @mask: mask of voltages available for MMC/SD/SDIO * * 1. Return zero on success. * 2. Return negative errno: voltage-range is invalid. */ int mmc_of_parse_voltage(struct device_node *np, u32 *mask) { const u32 *voltage_ranges; int num_ranges, i; voltage_ranges = of_get_property(np, "voltage-ranges", &num_ranges); num_ranges = num_ranges / sizeof(*voltage_ranges) / 2; if (!voltage_ranges || !num_ranges) { pr_info("%s: voltage-ranges unspecified\n", np->full_name); return -EINVAL; } for (i = 0; i < num_ranges; i++) { const int j = i * 2; u32 ocr_mask; ocr_mask = mmc_vddrange_to_ocrmask( be32_to_cpu(voltage_ranges[j]), be32_to_cpu(voltage_ranges[j + 1])); if (!ocr_mask) { pr_err("%s: voltage-range #%d is invalid\n", np->full_name, i); return -EINVAL; } *mask |= ocr_mask; } return 0; } EXPORT_SYMBOL(mmc_of_parse_voltage); #endif /* CONFIG_OF */ #ifdef CONFIG_REGULATOR /** * mmc_regulator_get_ocrmask - return mask of supported voltages * @supply: regulator to use * * This returns either a negative errno, or a mask of voltages that * can be provided to MMC/SD/SDIO devices using the specified voltage * regulator. This would normally be called before registering the * MMC host adapter. */ int mmc_regulator_get_ocrmask(struct regulator *supply) { int result = 0; int count; int i; int vdd_uV; int vdd_mV; count = regulator_count_voltages(supply); if (count < 0) return count; for (i = 0; i < count; i++) { vdd_uV = regulator_list_voltage(supply, i); if (vdd_uV <= 0) continue; vdd_mV = vdd_uV / 1000; result |= mmc_vddrange_to_ocrmask(vdd_mV, vdd_mV); } if (!result) { vdd_uV = regulator_get_voltage(supply); if (vdd_uV <= 0) return vdd_uV; vdd_mV = vdd_uV / 1000; result = mmc_vddrange_to_ocrmask(vdd_mV, vdd_mV); } return result; } EXPORT_SYMBOL_GPL(mmc_regulator_get_ocrmask); /** * mmc_regulator_set_ocr - set regulator to match host->ios voltage * @mmc: the host to regulate * @supply: regulator to use * @vdd_bit: zero for power off, else a bit number (host->ios.vdd) * * Returns zero on success, else negative errno. * * MMC host drivers may use this to enable or disable a regulator using * a particular supply voltage. This would normally be called from the * set_ios() method. */ int mmc_regulator_set_ocr(struct mmc_host *mmc, struct regulator *supply, unsigned short vdd_bit) { int result = 0; int min_uV, max_uV; if (vdd_bit) { int tmp; /* * REVISIT mmc_vddrange_to_ocrmask() may have set some * bits this regulator doesn't quite support ... don't * be too picky, most cards and regulators are OK with * a 0.1V range goof (it's a small error percentage). */ tmp = vdd_bit - ilog2(MMC_VDD_165_195); if (tmp == 0) { min_uV = 1650 * 1000; max_uV = 1950 * 1000; } else { min_uV = 1900 * 1000 + tmp * 100 * 1000; max_uV = min_uV + 100 * 1000; } result = regulator_set_voltage(supply, min_uV, max_uV); if (result == 0 && !mmc->regulator_enabled) { result = regulator_enable(supply); if (!result) mmc->regulator_enabled = true; } } else if (mmc->regulator_enabled) { result = regulator_disable(supply); if (result == 0) mmc->regulator_enabled = false; } if (result) dev_err(mmc_dev(mmc), "could not set regulator OCR (%d)\n", result); return result; } EXPORT_SYMBOL_GPL(mmc_regulator_set_ocr); #endif /* CONFIG_REGULATOR */ int mmc_regulator_get_supply(struct mmc_host *mmc) { struct device *dev = mmc_dev(mmc); int ret; mmc->supply.vmmc = devm_regulator_get_optional(dev, "vmmc"); mmc->supply.vqmmc = devm_regulator_get_optional(dev, "vqmmc"); if (IS_ERR(mmc->supply.vmmc)) { if (PTR_ERR(mmc->supply.vmmc) == -EPROBE_DEFER) return -EPROBE_DEFER; dev_info(dev, "No vmmc regulator found\n"); } else { ret = mmc_regulator_get_ocrmask(mmc->supply.vmmc); if (ret > 0) mmc->ocr_avail = ret; else dev_warn(dev, "Failed getting OCR mask: %d\n", ret); } if (IS_ERR(mmc->supply.vqmmc)) { if (PTR_ERR(mmc->supply.vqmmc) == -EPROBE_DEFER) return -EPROBE_DEFER; dev_info(dev, "No vqmmc regulator found\n"); } return 0; } EXPORT_SYMBOL_GPL(mmc_regulator_get_supply); /* * Mask off any voltages we don't support and select * the lowest voltage */ u32 mmc_select_voltage(struct mmc_host *host, u32 ocr) { int bit; /* * Sanity check the voltages that the card claims to * support. */ if (ocr & 0x7F) { dev_warn(mmc_dev(host), "card claims to support voltages below defined range\n"); ocr &= ~0x7F; } ocr &= host->ocr_avail; if (!ocr) { dev_warn(mmc_dev(host), "no support for card's volts\n"); return 0; } if (host->caps2 & MMC_CAP2_FULL_PWR_CYCLE) { bit = ffs(ocr) - 1; ocr &= 3 << bit; mmc_power_cycle(host, ocr); } else { bit = fls(ocr) - 1; ocr &= 3 << bit; if (bit != host->ios.vdd) dev_warn(mmc_dev(host), "exceeding card's volts\n"); } return ocr; } int __mmc_set_signal_voltage(struct mmc_host *host, int signal_voltage) { int err = 0; int old_signal_voltage = host->ios.signal_voltage; host->ios.signal_voltage = signal_voltage; if (host->ops->start_signal_voltage_switch) { mmc_host_clk_hold(host); err = host->ops->start_signal_voltage_switch(host, &host->ios); mmc_host_clk_release(host); } if (err) host->ios.signal_voltage = old_signal_voltage; return err; } int mmc_set_signal_voltage(struct mmc_host *host, int signal_voltage, u32 ocr) { struct mmc_command cmd = {0}; int err = 0; u32 clock; BUG_ON(!host); /* * Send CMD11 only if the request is to switch the card to * 1.8V signalling. */ if (signal_voltage == MMC_SIGNAL_VOLTAGE_330) return __mmc_set_signal_voltage(host, signal_voltage); /* * If we cannot switch voltages, return failure so the caller * can continue without UHS mode */ if (!host->ops->start_signal_voltage_switch) return -EPERM; if (!host->ops->card_busy) pr_warn("%s: cannot verify signal voltage switch\n", mmc_hostname(host)); cmd.opcode = SD_SWITCH_VOLTAGE; cmd.arg = 0; cmd.flags = MMC_RSP_R1 | MMC_CMD_AC; /* * Hold the clock reference so clock doesn't get auto gated during this * voltage switch sequence. */ mmc_host_clk_hold(host); err = mmc_wait_for_cmd(host, &cmd, 0); if (err) goto exit; if (!mmc_host_is_spi(host) && (cmd.resp[0] & R1_ERROR)) { err = -EIO; goto exit; } /* * The card should drive cmd and dat[0:3] low immediately * after the response of cmd11, but wait 1 ms to be sure */ mmc_delay(1); if (host->ops->card_busy && !host->ops->card_busy(host)) { err = -EAGAIN; goto power_cycle; } /* * During a signal voltage level switch, the clock must be gated * for 5 ms according to the SD spec */ host->card_clock_off = true; clock = host->ios.clock; host->ios.clock = 0; mmc_set_ios(host); if (__mmc_set_signal_voltage(host, signal_voltage)) { /* * Voltages may not have been switched, but we've already * sent CMD11, so a power cycle is required anyway */ err = -EAGAIN; host->ios.clock = clock; mmc_set_ios(host); host->card_clock_off = false; goto power_cycle; } /* Keep clock gated for at least 5 ms */ mmc_delay(5); host->ios.clock = clock; mmc_set_ios(host); host->card_clock_off = false; /* Wait for at least 1 ms according to spec */ mmc_delay(1); /* * Failure to switch is indicated by the card holding * dat[0:3] low */ if (host->ops->card_busy && host->ops->card_busy(host)) err = -EAGAIN; power_cycle: if (err) { pr_debug("%s: Signal voltage switch failed, " "power cycling card\n", mmc_hostname(host)); mmc_power_cycle(host, ocr); } exit: mmc_host_clk_release(host); return err; } /* * Select timing parameters for host. */ void mmc_set_timing(struct mmc_host *host, unsigned int timing) { mmc_host_clk_hold(host); host->ios.timing = timing; mmc_set_ios(host); mmc_host_clk_release(host); } /* * Select appropriate driver type for host. */ void mmc_set_driver_type(struct mmc_host *host, unsigned int drv_type) { mmc_host_clk_hold(host); host->ios.drv_type = drv_type; mmc_set_ios(host); mmc_host_clk_release(host); } /* * Apply power to the MMC stack. This is a two-stage process. * First, we enable power to the card without the clock running. * We then wait a bit for the power to stabilise. Finally, * enable the bus drivers and clock to the card. * * We must _NOT_ enable the clock prior to power stablising. * * If a host does all the power sequencing itself, ignore the * initial MMC_POWER_UP stage. */ void mmc_power_up(struct mmc_host *host, u32 ocr) { if (host->ios.power_mode == MMC_POWER_ON) return; mmc_host_clk_hold(host); host->ios.vdd = fls(ocr) - 1; if (mmc_host_is_spi(host)) host->ios.chip_select = MMC_CS_HIGH; else { host->ios.chip_select = MMC_CS_DONTCARE; host->ios.bus_mode = MMC_BUSMODE_OPENDRAIN; } host->ios.power_mode = MMC_POWER_UP; host->ios.bus_width = MMC_BUS_WIDTH_1; host->ios.timing = MMC_TIMING_LEGACY; mmc_set_ios(host); /* Try to set signal voltage to 3.3V but fall back to 1.8v or 1.2v */ if (__mmc_set_signal_voltage(host, MMC_SIGNAL_VOLTAGE_330) == 0) dev_dbg(mmc_dev(host), "Initial signal voltage of 3.3v\n"); else if (__mmc_set_signal_voltage(host, MMC_SIGNAL_VOLTAGE_180) == 0) dev_dbg(mmc_dev(host), "Initial signal voltage of 1.8v\n"); else if (__mmc_set_signal_voltage(host, MMC_SIGNAL_VOLTAGE_120) == 0) dev_dbg(mmc_dev(host), "Initial signal voltage of 1.2v\n"); /* * This delay should be sufficient to allow the power supply * to reach the minimum voltage. */ mmc_delay(10); host->ios.clock = host->f_init; host->ios.power_mode = MMC_POWER_ON; mmc_set_ios(host); /* * This delay must be at least 74 clock sizes, or 1 ms, or the * time required to reach a stable voltage. */ mmc_delay(10); mmc_host_clk_release(host); } void mmc_power_off(struct mmc_host *host) { if (host->ios.power_mode == MMC_POWER_OFF) return; mmc_host_clk_hold(host); host->ios.clock = 0; host->ios.vdd = 0; if (!mmc_host_is_spi(host)) { host->ios.bus_mode = MMC_BUSMODE_OPENDRAIN; host->ios.chip_select = MMC_CS_DONTCARE; } host->ios.power_mode = MMC_POWER_OFF; host->ios.bus_width = MMC_BUS_WIDTH_1; host->ios.timing = MMC_TIMING_LEGACY; mmc_set_ios(host); /* * Some configurations, such as the 802.11 SDIO card in the OLPC * XO-1.5, require a short delay after poweroff before the card * can be successfully turned on again. */ mmc_delay(1); mmc_host_clk_release(host); } void mmc_power_cycle(struct mmc_host *host, u32 ocr) { mmc_power_off(host); /* Wait at least 1 ms according to SD spec */ mmc_delay(1); mmc_power_up(host, ocr); } /* * Cleanup when the last reference to the bus operator is dropped. */ static void __mmc_release_bus(struct mmc_host *host) { BUG_ON(!host); BUG_ON(host->bus_refs); BUG_ON(!host->bus_dead); host->bus_ops = NULL; } /* * Increase reference count of bus operator */ static inline void mmc_bus_get(struct mmc_host *host) { unsigned long flags; spin_lock_irqsave(&host->lock, flags); host->bus_refs++; spin_unlock_irqrestore(&host->lock, flags); } /* * Decrease reference count of bus operator and free it if * it is the last reference. */ static inline void mmc_bus_put(struct mmc_host *host) { unsigned long flags; spin_lock_irqsave(&host->lock, flags); host->bus_refs--; if ((host->bus_refs == 0) && host->bus_ops) __mmc_release_bus(host); spin_unlock_irqrestore(&host->lock, flags); } /* * Assign a mmc bus handler to a host. Only one bus handler may control a * host at any given time. */ void mmc_attach_bus(struct mmc_host *host, const struct mmc_bus_ops *ops) { unsigned long flags; BUG_ON(!host); BUG_ON(!ops); WARN_ON(!host->claimed); spin_lock_irqsave(&host->lock, flags); BUG_ON(host->bus_ops); BUG_ON(host->bus_refs); host->bus_ops = ops; host->bus_refs = 1; host->bus_dead = 0; spin_unlock_irqrestore(&host->lock, flags); } /* * Remove the current bus handler from a host. */ void mmc_detach_bus(struct mmc_host *host) { unsigned long flags; BUG_ON(!host); WARN_ON(!host->claimed); WARN_ON(!host->bus_ops); spin_lock_irqsave(&host->lock, flags); host->bus_dead = 1; spin_unlock_irqrestore(&host->lock, flags); mmc_bus_put(host); } static void _mmc_detect_change(struct mmc_host *host, unsigned long delay, bool cd_irq) { #ifdef CONFIG_MMC_DEBUG unsigned long flags; spin_lock_irqsave(&host->lock, flags); WARN_ON(host->removed); spin_unlock_irqrestore(&host->lock, flags); #endif /* * If the device is configured as wakeup, we prevent a new sleep for * 5 s to give provision for user space to consume the event. */ if (cd_irq && !(host->caps & MMC_CAP_NEEDS_POLL) && device_can_wakeup(mmc_dev(host))) pm_wakeup_event(mmc_dev(host), 5000); host->detect_change = 1; mmc_schedule_delayed_work(&host->detect, delay); } /** * mmc_detect_change - process change of state on a MMC socket * @host: host which changed state. * @delay: optional delay to wait before detection (jiffies) * * MMC drivers should call this when they detect a card has been * inserted or removed. The MMC layer will confirm that any * present card is still functional, and initialize any newly * inserted. */ void mmc_detect_change(struct mmc_host *host, unsigned long delay) { _mmc_detect_change(host, delay, true); } EXPORT_SYMBOL(mmc_detect_change); void mmc_init_erase(struct mmc_card *card) { unsigned int sz; if (is_power_of_2(card->erase_size)) card->erase_shift = ffs(card->erase_size) - 1; else card->erase_shift = 0; /* * It is possible to erase an arbitrarily large area of an SD or MMC * card. That is not desirable because it can take a long time * (minutes) potentially delaying more important I/O, and also the * timeout calculations become increasingly hugely over-estimated. * Consequently, 'pref_erase' is defined as a guide to limit erases * to that size and alignment. * * For SD cards that define Allocation Unit size, limit erases to one * Allocation Unit at a time. For MMC cards that define High Capacity * Erase Size, whether it is switched on or not, limit to that size. * Otherwise just have a stab at a good value. For modern cards it * will end up being 4MiB. Note that if the value is too small, it * can end up taking longer to erase. */ if (mmc_card_sd(card) && card->ssr.au) { card->pref_erase = card->ssr.au; card->erase_shift = ffs(card->ssr.au) - 1; } else if (card->ext_csd.hc_erase_size) { card->pref_erase = card->ext_csd.hc_erase_size; } else if (card->erase_size) { sz = (card->csd.capacity << (card->csd.read_blkbits - 9)) >> 11; if (sz < 128) card->pref_erase = 512 * 1024 / 512; else if (sz < 512) card->pref_erase = 1024 * 1024 / 512; else if (sz < 1024) card->pref_erase = 2 * 1024 * 1024 / 512; else card->pref_erase = 4 * 1024 * 1024 / 512; if (card->pref_erase < card->erase_size) card->pref_erase = card->erase_size; else { sz = card->pref_erase % card->erase_size; if (sz) card->pref_erase += card->erase_size - sz; } } else card->pref_erase = 0; } static unsigned int mmc_mmc_erase_timeout(struct mmc_card *card, unsigned int arg, unsigned int qty) { unsigned int erase_timeout; if (arg == MMC_DISCARD_ARG || (arg == MMC_TRIM_ARG && card->ext_csd.rev >= 6)) { erase_timeout = card->ext_csd.trim_timeout; } else if (card->ext_csd.erase_group_def & 1) { /* High Capacity Erase Group Size uses HC timeouts */ if (arg == MMC_TRIM_ARG) erase_timeout = card->ext_csd.trim_timeout; else erase_timeout = card->ext_csd.hc_erase_timeout; } else { /* CSD Erase Group Size uses write timeout */ unsigned int mult = (10 << card->csd.r2w_factor); unsigned int timeout_clks = card->csd.tacc_clks * mult; unsigned int timeout_us; /* Avoid overflow: e.g. tacc_ns=80000000 mult=1280 */ if (card->csd.tacc_ns < 1000000) timeout_us = (card->csd.tacc_ns * mult) / 1000; else timeout_us = (card->csd.tacc_ns / 1000) * mult; /* * ios.clock is only a target. The real clock rate might be * less but not that much less, so fudge it by multiplying by 2. */ timeout_clks <<= 1; timeout_us += (timeout_clks * 1000) / (mmc_host_clk_rate(card->host) / 1000); erase_timeout = timeout_us / 1000; /* * Theoretically, the calculation could underflow so round up * to 1ms in that case. */ if (!erase_timeout) erase_timeout = 1; } /* Multiplier for secure operations */ if (arg & MMC_SECURE_ARGS) { if (arg == MMC_SECURE_ERASE_ARG) erase_timeout *= card->ext_csd.sec_erase_mult; else erase_timeout *= card->ext_csd.sec_trim_mult; } erase_timeout *= qty; /* * Ensure at least a 1 second timeout for SPI as per * 'mmc_set_data_timeout()' */ if (mmc_host_is_spi(card->host) && erase_timeout < 1000) erase_timeout = 1000; return erase_timeout; } static unsigned int mmc_sd_erase_timeout(struct mmc_card *card, unsigned int arg, unsigned int qty) { unsigned int erase_timeout; if (card->ssr.erase_timeout) { /* Erase timeout specified in SD Status Register (SSR) */ erase_timeout = card->ssr.erase_timeout * qty + card->ssr.erase_offset; } else { /* * Erase timeout not specified in SD Status Register (SSR) so * use 250ms per write block. */ erase_timeout = 250 * qty; } /* Must not be less than 1 second */ if (erase_timeout < 1000) erase_timeout = 1000; return erase_timeout; } static unsigned int mmc_erase_timeout(struct mmc_card *card, unsigned int arg, unsigned int qty) { if (mmc_card_sd(card)) return mmc_sd_erase_timeout(card, arg, qty); else return mmc_mmc_erase_timeout(card, arg, qty); } static u32 mmc_get_erase_qty(struct mmc_card *card, u32 from, u32 to) { u32 qty = 0; /* * qty is used to calculate the erase timeout which depends on how many * erase groups (or allocation units in SD terminology) are affected. * We count erasing part of an erase group as one erase group. * For SD, the allocation units are always a power of 2. For MMC, the * erase group size is almost certainly also power of 2, but it does not * seem to insist on that in the JEDEC standard, so we fall back to * division in that case. SD may not specify an allocation unit size, * in which case the timeout is based on the number of write blocks. * * Note that the timeout for secure trim 2 will only be correct if the * number of erase groups specified is the same as the total of all * preceding secure trim 1 commands. Since the power may have been * lost since the secure trim 1 commands occurred, it is generally * impossible to calculate the secure trim 2 timeout correctly. */ if (card->erase_shift) qty += ((to >> card->erase_shift) - (from >> card->erase_shift)) + 1; else if (mmc_card_sd(card)) qty += to - from + 1; else qty += ((to / card->erase_size) - (from / card->erase_size)) + 1; return qty; } static int mmc_cmdq_send_erase_cmd(struct mmc_cmdq_req *cmdq_req, struct mmc_card *card, u32 opcode, u32 arg, u32 qty) { struct mmc_command *cmd = cmdq_req->mrq.cmd; int err; memset(cmd, 0, sizeof(struct mmc_command)); cmd->opcode = opcode; cmd->arg = arg; if (cmd->opcode == MMC_ERASE) { cmd->flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC; cmd->busy_timeout = mmc_erase_timeout(card, arg, qty); } else { cmd->flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC; } err = mmc_cmdq_wait_for_dcmd(card->host, cmdq_req); if (err) { pr_err("mmc_erase: group start error %d, status %#x\n", err, cmd->resp[0]); return -EIO; } return 0; } static int mmc_cmdq_do_erase(struct mmc_cmdq_req *cmdq_req, struct mmc_card *card, unsigned int from, unsigned int to, unsigned int arg) { struct mmc_command *cmd = cmdq_req->mrq.cmd; unsigned int qty = 0; unsigned long timeout; unsigned int fr, nr; int err; fr = from; nr = to - from + 1; trace_mmc_blk_erase_start(arg, fr, nr); qty = mmc_get_erase_qty(card, from, to); if (!mmc_card_blockaddr(card)) { from <<= 9; to <<= 9; } err = mmc_cmdq_send_erase_cmd(cmdq_req, card, MMC_ERASE_GROUP_START, from, qty); if (err) goto out; err = mmc_cmdq_send_erase_cmd(cmdq_req, card, MMC_ERASE_GROUP_END, to, qty); if (err) goto out; err = mmc_cmdq_send_erase_cmd(cmdq_req, card, MMC_ERASE, arg, qty); if (err) goto out; timeout = jiffies + msecs_to_jiffies(MMC_CORE_TIMEOUT_MS); do { memset(cmd, 0, sizeof(struct mmc_command)); cmd->opcode = MMC_SEND_STATUS; cmd->arg = card->rca << 16; cmd->flags = MMC_RSP_R1 | MMC_CMD_AC; /* Do not retry else we can't see errors */ err = mmc_cmdq_wait_for_dcmd(card->host, cmdq_req); if (err || (cmd->resp[0] & 0xFDF92000)) { pr_err("error %d requesting status %#x\n", err, cmd->resp[0]); err = -EIO; goto out; } /* Timeout if the device never becomes ready for data and * never leaves the program state. */ if (time_after(jiffies, timeout)) { pr_err("%s: Card stuck in programming state! %s\n", mmc_hostname(card->host), __func__); err = -EIO; goto out; } } while (!(cmd->resp[0] & R1_READY_FOR_DATA) || (R1_CURRENT_STATE(cmd->resp[0]) == R1_STATE_PRG)); out: trace_mmc_blk_erase_end(arg, fr, nr); return err; } static int mmc_do_erase(struct mmc_card *card, unsigned int from, unsigned int to, unsigned int arg) { struct mmc_command cmd = {0}; unsigned int qty = 0; unsigned long timeout; unsigned int fr, nr; int err; fr = from; nr = to - from + 1; trace_mmc_blk_erase_start(arg, fr, nr); qty = mmc_get_erase_qty(card, from, to); if (!mmc_card_blockaddr(card)) { from <<= 9; to <<= 9; } if (mmc_card_sd(card)) cmd.opcode = SD_ERASE_WR_BLK_START; else cmd.opcode = MMC_ERASE_GROUP_START; cmd.arg = from; cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC; err = mmc_wait_for_cmd(card->host, &cmd, 0); if (err) { pr_err("mmc_erase: group start error %d, " "status %#x\n", err, cmd.resp[0]); err = -EIO; goto out; } memset(&cmd, 0, sizeof(struct mmc_command)); if (mmc_card_sd(card)) cmd.opcode = SD_ERASE_WR_BLK_END; else cmd.opcode = MMC_ERASE_GROUP_END; cmd.arg = to; cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC; err = mmc_wait_for_cmd(card->host, &cmd, 0); if (err) { pr_err("mmc_erase: group end error %d, status %#x\n", err, cmd.resp[0]); err = -EIO; goto out; } memset(&cmd, 0, sizeof(struct mmc_command)); cmd.opcode = MMC_ERASE; cmd.arg = arg; cmd.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC; cmd.busy_timeout = mmc_erase_timeout(card, arg, qty); err = mmc_wait_for_cmd(card->host, &cmd, 0); if (err) { pr_err("mmc_erase: erase error %d, status %#x\n", err, cmd.resp[0]); err = -EIO; goto out; } if (mmc_host_is_spi(card->host)) goto out; timeout = jiffies + msecs_to_jiffies(MMC_CORE_TIMEOUT_MS); do { memset(&cmd, 0, sizeof(struct mmc_command)); cmd.opcode = MMC_SEND_STATUS; cmd.arg = card->rca << 16; cmd.flags = MMC_RSP_R1 | MMC_CMD_AC; /* Do not retry else we can't see errors */ err = mmc_wait_for_cmd(card->host, &cmd, 0); if (err || (cmd.resp[0] & 0xFDF92000)) { pr_err("error %d requesting status %#x\n", err, cmd.resp[0]); err = -EIO; goto out; } /* Timeout if the device never becomes ready for data and * never leaves the program state. */ if (time_after(jiffies, timeout)) { pr_err("%s: Card stuck in programming state! %s\n", mmc_hostname(card->host), __func__); err = -EIO; goto out; } } while (!(cmd.resp[0] & R1_READY_FOR_DATA) || (R1_CURRENT_STATE(cmd.resp[0]) == R1_STATE_PRG)); out: trace_mmc_blk_erase_end(arg, fr, nr); return err; } int mmc_erase_sanity_check(struct mmc_card *card, unsigned int from, unsigned int nr, unsigned int arg) { if (!(card->host->caps & MMC_CAP_ERASE) || !(card->csd.cmdclass & CCC_ERASE)) return -EOPNOTSUPP; if (!card->erase_size) return -EOPNOTSUPP; if (mmc_card_sd(card) && arg != MMC_ERASE_ARG) return -EOPNOTSUPP; if ((arg & MMC_SECURE_ARGS) && !(card->ext_csd.sec_feature_support & EXT_CSD_SEC_ER_EN)) return -EOPNOTSUPP; if ((arg & MMC_TRIM_ARGS) && !(card->ext_csd.sec_feature_support & EXT_CSD_SEC_GB_CL_EN)) return -EOPNOTSUPP; if (arg == MMC_SECURE_ERASE_ARG) { if (from % card->erase_size || nr % card->erase_size) return -EINVAL; } return 0; } int mmc_cmdq_erase(struct mmc_cmdq_req *cmdq_req, struct mmc_card *card, unsigned int from, unsigned int nr, unsigned int arg) { unsigned int rem, to = from + nr; int ret; ret = mmc_erase_sanity_check(card, from, nr, arg); if (ret) return ret; if (arg == MMC_ERASE_ARG) { rem = from % card->erase_size; if (rem) { rem = card->erase_size - rem; from += rem; if (nr > rem) nr -= rem; else return 0; } rem = nr % card->erase_size; if (rem) nr -= rem; } if (nr == 0) return 0; to = from + nr; if (to <= from) return -EINVAL; /* 'from' and 'to' are inclusive */ to -= 1; return mmc_cmdq_do_erase(cmdq_req, card, from, to, arg); } EXPORT_SYMBOL(mmc_cmdq_erase); /** * mmc_erase - erase sectors. * @card: card to erase * @from: first sector to erase * @nr: number of sectors to erase * @arg: erase command argument (SD supports only %MMC_ERASE_ARG) * * Caller must claim host before calling this function. */ int mmc_erase(struct mmc_card *card, unsigned int from, unsigned int nr, unsigned int arg) { unsigned int rem, to = from + nr; int ret; ret = mmc_erase_sanity_check(card, from, nr, arg); if (ret) return ret; if (arg == MMC_ERASE_ARG) { rem = from % card->erase_size; if (rem) { rem = card->erase_size - rem; from += rem; if (nr > rem) nr -= rem; else return 0; } rem = nr % card->erase_size; if (rem) nr -= rem; } if (nr == 0) return 0; to = from + nr; if (to <= from) return -EINVAL; /* 'from' and 'to' are inclusive */ to -= 1; return mmc_do_erase(card, from, to, arg); } EXPORT_SYMBOL(mmc_erase); int mmc_can_erase(struct mmc_card *card) { if ((card->host->caps & MMC_CAP_ERASE) && (card->csd.cmdclass & CCC_ERASE) && card->erase_size) return 1; return 0; } EXPORT_SYMBOL(mmc_can_erase); int mmc_can_trim(struct mmc_card *card) { if (card->ext_csd.sec_feature_support & EXT_CSD_SEC_GB_CL_EN) return 1; return 0; } EXPORT_SYMBOL(mmc_can_trim); int mmc_can_discard(struct mmc_card *card) { /* * As there's no way to detect the discard support bit at v4.5 * use the s/w feature support filed. */ if (card->ext_csd.feature_support & MMC_DISCARD_FEATURE) return 1; return 0; } EXPORT_SYMBOL(mmc_can_discard); int mmc_can_sanitize(struct mmc_card *card) { if (!mmc_can_trim(card) && !mmc_can_erase(card)) return 0; if (card->ext_csd.sec_feature_support & EXT_CSD_SEC_SANITIZE) return 1; return 0; } EXPORT_SYMBOL(mmc_can_sanitize); int mmc_can_secure_erase_trim(struct mmc_card *card) { if ((card->ext_csd.sec_feature_support & EXT_CSD_SEC_ER_EN) && !(card->quirks & MMC_QUIRK_SEC_ERASE_TRIM_BROKEN)) return 1; return 0; } EXPORT_SYMBOL(mmc_can_secure_erase_trim); int mmc_erase_group_aligned(struct mmc_card *card, unsigned int from, unsigned int nr) { if (!card->erase_size) return 0; if (from % card->erase_size || nr % card->erase_size) return 0; return 1; } EXPORT_SYMBOL(mmc_erase_group_aligned); static unsigned int mmc_do_calc_max_discard(struct mmc_card *card, unsigned int arg) { struct mmc_host *host = card->host; unsigned int max_discard, x, y, qty = 0, max_qty, timeout; unsigned int last_timeout = 0; if (card->erase_shift) max_qty = UINT_MAX >> card->erase_shift; else if (mmc_card_sd(card)) max_qty = UINT_MAX; else max_qty = UINT_MAX / card->erase_size; /* Find the largest qty with an OK timeout */ do { y = 0; for (x = 1; x && x <= max_qty && max_qty - x >= qty; x <<= 1) { timeout = mmc_erase_timeout(card, arg, qty + x); if (timeout > host->max_busy_timeout) break; if (timeout < last_timeout) break; last_timeout = timeout; y = x; } qty += y; } while (y); if (!qty) return 0; if (qty == 1) return 1; /* Convert qty to sectors */ if (card->erase_shift) max_discard = --qty << card->erase_shift; else if (mmc_card_sd(card)) max_discard = qty; else max_discard = --qty * card->erase_size; return max_discard; } unsigned int mmc_calc_max_discard(struct mmc_card *card) { struct mmc_host *host = card->host; unsigned int max_discard, max_trim; if (!host->max_busy_timeout || (host->caps2 & MMC_CAP2_MAX_DISCARD_SIZE)) return UINT_MAX; /* * Without erase_group_def set, MMC erase timeout depends on clock * frequence which can change. In that case, the best choice is * just the preferred erase size. */ if (mmc_card_mmc(card) && !(card->ext_csd.erase_group_def & 1)) return card->pref_erase; max_discard = mmc_do_calc_max_discard(card, MMC_ERASE_ARG); if (mmc_can_trim(card)) { max_trim = mmc_do_calc_max_discard(card, MMC_TRIM_ARG); if (max_trim < max_discard) max_discard = max_trim; } else if (max_discard < card->erase_size) { max_discard = 0; } pr_debug("%s: calculated max. discard sectors %u for timeout %u ms\n", mmc_hostname(host), max_discard, host->max_busy_timeout); return max_discard; } EXPORT_SYMBOL(mmc_calc_max_discard); int mmc_set_blocklen(struct mmc_card *card, unsigned int blocklen) { struct mmc_command cmd = {0}; if (mmc_card_blockaddr(card) || mmc_card_ddr52(card)) return 0; cmd.opcode = MMC_SET_BLOCKLEN; cmd.arg = blocklen; cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC; return mmc_wait_for_cmd(card->host, &cmd, 5); } EXPORT_SYMBOL(mmc_set_blocklen); int mmc_set_blockcount(struct mmc_card *card, unsigned int blockcount, bool is_rel_write) { struct mmc_command cmd = {0}; cmd.opcode = MMC_SET_BLOCK_COUNT; cmd.arg = blockcount & 0x0000FFFF; if (is_rel_write) cmd.arg |= 1 << 31; cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC; return mmc_wait_for_cmd(card->host, &cmd, 5); } EXPORT_SYMBOL(mmc_set_blockcount); static void mmc_hw_reset_for_init(struct mmc_host *host) { if (!(host->caps & MMC_CAP_HW_RESET) || !host->ops->hw_reset) return; mmc_host_clk_hold(host); host->ops->hw_reset(host); mmc_host_clk_release(host); } int mmc_can_reset(struct mmc_card *card) { u8 rst_n_function; if (mmc_card_sdio(card)) return 0; if (mmc_card_mmc(card) && (card->host->caps & MMC_CAP_HW_RESET)) { rst_n_function = card->ext_csd.rst_n_function; if ((rst_n_function & EXT_CSD_RST_N_EN_MASK) != EXT_CSD_RST_N_ENABLED) return 0; } return 1; } EXPORT_SYMBOL(mmc_can_reset); static int mmc_do_hw_reset(struct mmc_host *host, int check) { struct mmc_card *card = host->card; int ret; if (!host->bus_ops->power_restore) return -EOPNOTSUPP; if (!card) return -EINVAL; if (!mmc_can_reset(card)) return -EOPNOTSUPP; mmc_host_clk_hold(host); mmc_set_clock(host, host->f_init); if (mmc_card_mmc(card) && host->ops->hw_reset) host->ops->hw_reset(host); else mmc_power_cycle(host, host->ocr_avail); /* If the reset has happened, then a status command will fail */ if (check) { struct mmc_command cmd = {0}; int err; cmd.opcode = MMC_SEND_STATUS; if (!mmc_host_is_spi(card->host)) cmd.arg = card->rca << 16; cmd.flags = MMC_RSP_SPI_R2 | MMC_RSP_R1 | MMC_CMD_AC; err = mmc_wait_for_cmd(card->host, &cmd, 0); if (!err) { mmc_host_clk_release(host); return -ENOSYS; } } if (mmc_host_is_spi(host)) { host->ios.chip_select = MMC_CS_HIGH; host->ios.bus_mode = MMC_BUSMODE_PUSHPULL; } else { host->ios.chip_select = MMC_CS_DONTCARE; host->ios.bus_mode = MMC_BUSMODE_OPENDRAIN; } host->ios.bus_width = MMC_BUS_WIDTH_1; host->ios.timing = MMC_TIMING_LEGACY; mmc_set_ios(host); mmc_host_clk_release(host); mmc_claim_host(host); ret = host->bus_ops->power_restore(host); mmc_release_host(host); return ret; } /* * mmc_cmdq_hw_reset: Helper API for doing * reset_all of host and reinitializing card. * This must be called with mmc_claim_host * acquired by the caller. */ int mmc_cmdq_hw_reset(struct mmc_host *host) { if (!host->bus_ops->power_restore) return -EOPNOTSUPP; mmc_power_cycle(host, host->ocr_avail); mmc_select_voltage(host, host->card->ocr); return host->bus_ops->power_restore(host); } EXPORT_SYMBOL(mmc_cmdq_hw_reset); int mmc_hw_reset(struct mmc_host *host) { return mmc_do_hw_reset(host, 0); } EXPORT_SYMBOL(mmc_hw_reset); int mmc_hw_reset_check(struct mmc_host *host) { return mmc_do_hw_reset(host, 1); } EXPORT_SYMBOL(mmc_hw_reset_check); static int mmc_rescan_try_freq(struct mmc_host *host, unsigned freq) { host->f_init = freq; #ifdef CONFIG_MMC_DEBUG pr_info("%s: %s: trying to init card at %u Hz\n", mmc_hostname(host), __func__, host->f_init); #endif mmc_power_up(host, host->ocr_avail); /* * Some eMMCs (with VCCQ always on) may not be reset after power up, so * do a hardware reset if possible. */ mmc_hw_reset_for_init(host); /* * sdio_reset sends CMD52 to reset card. Since we do not know * if the card is being re-initialized, just send it. CMD52 * should be ignored by SD/eMMC cards. */ sdio_reset(host); mmc_go_idle(host); mmc_send_if_cond(host, host->ocr_avail); /* Order's important: probe SDIO, then SD, then MMC */ if (!mmc_attach_sdio(host)) return 0; if (!mmc_attach_sd(host)) return 0; if (!mmc_attach_mmc(host)) return 0; mmc_power_off(host); return -EIO; } int _mmc_detect_card_removed(struct mmc_host *host) { int ret; if (host->caps & MMC_CAP_NONREMOVABLE) return 0; if (!host->card || mmc_card_removed(host->card)) return 1; ret = host->bus_ops->alive(host); /* * Card detect status and alive check may be out of sync if card is * removed slowly, when card detect switch changes while card/slot * pads are still contacted in hardware (refer to "SD Card Mechanical * Addendum, Appendix C: Card Detection Switch"). So reschedule a * detect work 200ms later for this case. */ if (!ret && host->ops->get_cd && !host->ops->get_cd(host)) { mmc_detect_change(host, msecs_to_jiffies(200)); pr_debug("%s: card removed too slowly\n", mmc_hostname(host)); } if (ret) { mmc_card_set_removed(host->card); pr_debug("%s: card remove detected\n", mmc_hostname(host)); } return ret; } int mmc_detect_card_removed(struct mmc_host *host) { struct mmc_card *card = host->card; int ret; WARN_ON(!host->claimed); if (!card) return 1; ret = mmc_card_removed(card); /* * The card will be considered unchanged unless we have been asked to * detect a change or host requires polling to provide card detection. */ if (!host->detect_change && !(host->caps & MMC_CAP_NEEDS_POLL)) return ret; host->detect_change = 0; if (!ret) { ret = _mmc_detect_card_removed(host); if (ret && (host->caps & MMC_CAP_NEEDS_POLL)) { /* * Schedule a detect work as soon as possible to let a * rescan handle the card removal. */ cancel_delayed_work(&host->detect); _mmc_detect_change(host, 0, false); } } return ret; } EXPORT_SYMBOL(mmc_detect_card_removed); void mmc_rescan(struct work_struct *work) { struct mmc_host *host = container_of(work, struct mmc_host, detect.work); if (host->trigger_card_event && host->ops->card_event) { host->ops->card_event(host); host->trigger_card_event = false; } if (host->rescan_disable) return; /* If there is a non-removable card registered, only scan once */ if ((host->caps & MMC_CAP_NONREMOVABLE) && host->rescan_entered) return; host->rescan_entered = 1; mmc_bus_get(host); /* * if there is a _removable_ card registered, check whether it is * still present */ if (host->bus_ops && !host->bus_dead && !(host->caps & MMC_CAP_NONREMOVABLE)) host->bus_ops->detect(host); host->detect_change = 0; /* * Let mmc_bus_put() free the bus/bus_ops if we've found that * the card is no longer present. */ mmc_bus_put(host); mmc_bus_get(host); /* if there still is a card present, stop here */ if (host->bus_ops != NULL) { mmc_bus_put(host); goto out; } /* * Only we can add a new handler, so it's safe to * release the lock here. */ mmc_bus_put(host); if (!(host->caps & MMC_CAP_NONREMOVABLE) && host->ops->get_cd && host->ops->get_cd(host) == 0) { mmc_claim_host(host); mmc_power_off(host); mmc_release_host(host); goto out; } mmc_claim_host(host); (void) mmc_rescan_try_freq(host, host->f_min); mmc_release_host(host); out: if (host->caps & MMC_CAP_NEEDS_POLL) mmc_schedule_delayed_work(&host->detect, HZ); } void mmc_start_host(struct mmc_host *host) { mmc_claim_host(host); host->f_init = max(freqs[0], host->f_min); host->rescan_disable = 0; host->ios.power_mode = MMC_POWER_UNDEFINED; if (host->caps2 & MMC_CAP2_NO_PRESCAN_POWERUP) mmc_power_off(host); else mmc_power_up(host, host->ocr_avail); mmc_gpiod_request_cd_irq(host); mmc_release_host(host); _mmc_detect_change(host, 0, false); } void mmc_stop_host(struct mmc_host *host) { #ifdef CONFIG_MMC_DEBUG unsigned long flags; spin_lock_irqsave(&host->lock, flags); host->removed = 1; spin_unlock_irqrestore(&host->lock, flags); #endif if (host->slot.cd_irq >= 0) disable_irq(host->slot.cd_irq); host->rescan_disable = 1; cancel_delayed_work_sync(&host->detect); mmc_flush_scheduled_work(); /* clear pm flags now and let card drivers set them as needed */ host->pm_flags = 0; mmc_bus_get(host); if (host->bus_ops && !host->bus_dead) { /* Calling bus_ops->remove() with a claimed host can deadlock */ host->bus_ops->remove(host); mmc_claim_host(host); mmc_detach_bus(host); mmc_power_off(host); mmc_release_host(host); mmc_bus_put(host); return; } mmc_bus_put(host); BUG_ON(host->card); mmc_power_off(host); } int mmc_power_save_host(struct mmc_host *host) { int ret = 0; #ifdef CONFIG_MMC_DEBUG pr_info("%s: %s: powering down\n", mmc_hostname(host), __func__); #endif mmc_bus_get(host); if (!host->bus_ops || host->bus_dead) { mmc_bus_put(host); return -EINVAL; } if (host->bus_ops->power_save) ret = host->bus_ops->power_save(host); mmc_bus_put(host); mmc_power_off(host); return ret; } EXPORT_SYMBOL(mmc_power_save_host); int mmc_power_restore_host(struct mmc_host *host) { int ret; #ifdef CONFIG_MMC_DEBUG pr_info("%s: %s: powering up\n", mmc_hostname(host), __func__); #endif mmc_bus_get(host); if (!host->bus_ops || host->bus_dead) { mmc_bus_put(host); return -EINVAL; } mmc_power_up(host, host->card->ocr); mmc_claim_host(host); ret = host->bus_ops->power_restore(host); mmc_release_host(host); mmc_bus_put(host); return ret; } EXPORT_SYMBOL(mmc_power_restore_host); /* * Add barrier request to the requests in cache */ int mmc_cache_barrier(struct mmc_card *card) { struct mmc_host *host = card->host; int err = 0; if (!card->ext_csd.cache_ctrl || (card->quirks & MMC_QUIRK_CACHE_DISABLE)) goto out; if (!mmc_card_mmc(card)) goto out; if (!card->ext_csd.barrier_en) return -ENOTSUPP; /* * If a device receives maximum supported barrier * requests, a barrier command is treated as a * flush command. Hence, it is betetr to use * flush timeout instead a generic CMD6 timeout */ err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL, EXT_CSD_FLUSH_CACHE, 0x2, 0); if (err) pr_err("%s: cache barrier error %d\n", mmc_hostname(host), err); out: return err; } EXPORT_SYMBOL(mmc_cache_barrier); /* * Flush the cache to the non-volatile storage. */ int mmc_flush_cache(struct mmc_card *card) { int err = 0; if (mmc_card_mmc(card) && (card->ext_csd.cache_size > 0) && (card->ext_csd.cache_ctrl & 1) && (!(card->quirks & MMC_QUIRK_CACHE_DISABLE))) { err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL, EXT_CSD_FLUSH_CACHE, 1, 0); if (err == -ETIMEDOUT) { pr_err("%s: cache flush timeout\n", mmc_hostname(card->host)); err = mmc_interrupt_hpi(card); if (err) { pr_err("%s: mmc_interrupt_hpi() failed (%d)\n", mmc_hostname(card->host), err); err = -ENODEV; } } else if (err) { pr_err("%s: cache flush error %d\n", mmc_hostname(card->host), err); } } return err; } EXPORT_SYMBOL(mmc_flush_cache); #ifdef CONFIG_PM /* Do the card removal on suspend if card is assumed removeable * Do that in pm notifier while userspace isn't yet frozen, so we will be able to sync the card. */ int mmc_pm_notify(struct notifier_block *notify_block, unsigned long mode, void *unused) { struct mmc_host *host = container_of( notify_block, struct mmc_host, pm_notify); unsigned long flags; int err = 0; switch (mode) { case PM_HIBERNATION_PREPARE: case PM_SUSPEND_PREPARE: case PM_RESTORE_PREPARE: spin_lock_irqsave(&host->lock, flags); host->rescan_disable = 1; spin_unlock_irqrestore(&host->lock, flags); cancel_delayed_work_sync(&host->detect); if (!host->bus_ops) break; /* Validate prerequisites for suspend */ if (host->bus_ops->pre_suspend) err = host->bus_ops->pre_suspend(host); if (!err) break; /* Calling bus_ops->remove() with a claimed host can deadlock */ host->bus_ops->remove(host); mmc_claim_host(host); mmc_detach_bus(host); mmc_power_off(host); mmc_release_host(host); host->pm_flags = 0; break; case PM_POST_SUSPEND: case PM_POST_HIBERNATION: case PM_POST_RESTORE: spin_lock_irqsave(&host->lock, flags); host->rescan_disable = 0; spin_unlock_irqrestore(&host->lock, flags); _mmc_detect_change(host, 0, false); } return 0; } #endif /** * mmc_init_context_info() - init synchronization context * @host: mmc host * * Init struct context_info needed to implement asynchronous * request mechanism, used by mmc core, host driver and mmc requests * supplier. */ void mmc_init_context_info(struct mmc_host *host) { spin_lock_init(&host->context_info.lock); host->context_info.is_new_req = false; host->context_info.is_done_rcv = false; host->context_info.is_waiting_last_req = false; init_waitqueue_head(&host->context_info.wait); } #ifdef CONFIG_MMC_EMBEDDED_SDIO void mmc_set_embedded_sdio_data(struct mmc_host *host, struct sdio_cis *cis, struct sdio_cccr *cccr, struct sdio_embedded_func *funcs, int num_funcs) { host->embedded_sdio_data.cis = cis; host->embedded_sdio_data.cccr = cccr; host->embedded_sdio_data.funcs = funcs; host->embedded_sdio_data.num_funcs = num_funcs; } EXPORT_SYMBOL(mmc_set_embedded_sdio_data); #endif static int __init mmc_init(void) { int ret; workqueue = alloc_ordered_workqueue("kmmcd", 0); if (!workqueue) return -ENOMEM; ret = mmc_register_bus(); if (ret) goto destroy_workqueue; ret = mmc_register_host_class(); if (ret) goto unregister_bus; ret = sdio_register_bus(); if (ret) goto unregister_host_class; return 0; unregister_host_class: mmc_unregister_host_class(); unregister_bus: mmc_unregister_bus(); destroy_workqueue: destroy_workqueue(workqueue); return ret; } static void __exit mmc_exit(void) { sdio_unregister_bus(); mmc_unregister_host_class(); mmc_unregister_bus(); destroy_workqueue(workqueue); } subsys_initcall(mmc_init); module_exit(mmc_exit); MODULE_LICENSE("GPL");
fedosis/android_kernel_xiaomi_msm8937
drivers/mmc/core/core.c
C
gpl-2.0
102,367
<?php /** * Created by PhpStorm. * User: Anh Tuan * Date: 7/24/14 * Time: 3:45 PM */ global $theme_options_data; $logo_id = $theme_options_data['thim_logo']; // The value may be a URL to the image (for the default parameter) // or an attachment ID to the selected image. $logo_src = $logo_id; // For the default value if ( is_numeric( $logo_id ) ) { $imageAttachment = wp_get_attachment_image_src( $logo_id, 'full' ); $logo_src = $imageAttachment[0]; } $sticky_logo_id = $theme_options_data['thim_sticky_logo']; // The value may be a URL to the image (for the default parameter) // or an attachment ID to the selected image. $sticky_logo_src = $sticky_logo_id; // For the default value if ( is_numeric( $sticky_logo_id ) ) { $imageAttachment = wp_get_attachment_image_src( $sticky_logo_id, 'full' ); $sticky_logo_src = $imageAttachment[0]; } ?> <?php if ( isset( $theme_options_data['thim_header_position'] ) && $theme_options_data['thim_header_position'] == 'header_after_slider' && is_active_sidebar( 'banner_header' ) ) { dynamic_sidebar( 'banner_header' ); } ?> <header id="masthead" class="site-header <?php if ( isset( $theme_options_data['thim_header_position'] ) && $theme_options_data['thim_header_position'] <> '' ) { echo $theme_options_data['thim_header_position']; } if ( isset( $theme_options_data['thim_config_height_sticky'] ) && $theme_options_data['thim_config_height_sticky'] <> '' ) { echo ' ' . $theme_options_data['thim_config_height_sticky']; } if ( isset( $theme_options_data['thim_config_att_sticky'] ) && $theme_options_data['thim_config_att_sticky'] <> '' ) { echo ' ' . $theme_options_data['thim_config_att_sticky']; } ?>" role="banner"> <?php if ( isset( $theme_options_data['thim_header_layout'] ) && $theme_options_data['thim_header_layout'] == 'boxed' ) { echo "<div class=\"container header_boxed\">"; } ?> <?php $width_topsidebar_left = 5; if ( isset( $theme_options_data['width_left_top_sidebar'] ) ) { $width_topsidebar_left = $theme_options_data['width_left_top_sidebar']; } $width_topsidebar_right = 12 - $width_topsidebar_left; if ( isset( $theme_options_data['thim_topbar_show'] ) && $theme_options_data['thim_topbar_show'] == '1' ) { ?> <?php if ( ( is_active_sidebar( 'top_right_sidebar' ) ) || ( is_active_sidebar( 'top_left_sidebar' ) ) ) : ?> <div class="top-header"> <?php if ( isset( $theme_options_data['thim_header_layout'] ) && $theme_options_data['thim_header_layout'] == 'wide' ) { echo "<div class=\"container\"><div class=\"row\">"; } ?> <?php if ( is_active_sidebar( 'top_left_sidebar' ) ) : ?> <div class="col-sm-<?php echo $width_topsidebar_left; ?> top_left"> <ul class="top-left-menu"> <?php dynamic_sidebar( 'top_left_sidebar' ); ?> </ul> </div><!-- col-sm-6 --> <?php endif; ?> <?php if ( is_active_sidebar( 'top_right_sidebar' ) ) : ?> <div class="col-sm-<?php echo $width_topsidebar_right; ?> top_right"> <ul class="top-right-menu"> <?php dynamic_sidebar( 'top_right_sidebar' ); ?> </ul> </div><!-- col-sm-6 --> <?php endif; ?> <?php if ( isset( $theme_options_data['thim_header_layout'] ) && $theme_options_data['thim_header_layout'] == 'wide' ) { echo "</div></div>"; } ?> </div><!--End/div.top--> <?php endif; } ?> <?php $width_logo = 3; if ( isset( $theme_options_data['thim_column_logo'] ) ) { $width_logo = $theme_options_data['thim_column_logo']; } $width_menu = 12 - $width_logo; ?> <div class="wapper_logo"> <div class="container tm-table"> <?php if ( is_active_sidebar( 'header_left' ) ) : ?> <div class="table_cell"> <div class="header_left"> <?php dynamic_sidebar( 'header_left' ); ?> </div> </div><!-- col-sm-6 --> <?php endif; ?> <div class="menu-mobile-effect navbar-toggle" data-effect="mobile-effect"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </div> <div class="table_cell table_cell-center sm-logo"> <?php if ( is_single() ) { echo '<h2 class="header_logo">'; } else { echo '<h1 class="header_logo">'; } ?> <a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?> - <?php bloginfo( 'description' ); ?>" rel="home"> <?php if ( isset( $logo_src ) && $logo_src ) { $aloxo_logo_size = @getimagesize( $logo_src ); $width = $aloxo_logo_size[0]; $height = $aloxo_logo_size[1]; $site_title = esc_attr( get_bloginfo( 'name', 'display' ) ); echo '<img src="' . $logo_src . '" alt="' . $site_title . '" width="' . $width . '" height="' . $height . '" />'; } else { bloginfo( 'name' ); } ?> </a> <?php if ( is_single() ) { echo '</h2>'; } else { echo '</h1>'; } ?> </div> <?php if ( is_active_sidebar( 'header_right' ) ) : ?> <div class="table_cell right_header"> <div class="header_right"> <?php dynamic_sidebar( 'header_right' ); ?> </div> </div><!-- col-sm-6 --> <?php endif; ?> <div id="header-search-form-input" class="main-header-search-form-input"> <form role="search" method="get" action="<?php echo get_site_url(); ?>"> <input type="text" value="" name="s" id="s" placeholder="<?php echo __( 'Search the site or press ESC to cancel.', 'aloxo' ); ?>" class="form-control ob-search-input" autocomplete="off" /> <span class="header-search-close"><i class="fa fa-times"></i></span> </form> <ul class="ob_list_search"> </ul> </div> </div> <!--end container tm-table--> </div> <!--end wapper-logo--> <div class="navigation affix-top" <?php if ( isset( $theme_options_data['thim_header_sticky'] ) && $theme_options_data['thim_header_sticky'] == 1 ) { echo 'data-spy="affix" data-offset-top="' . $theme_options_data['thim_header_height_sticky'] . '" '; } ?>> <!-- <div class="main-menu"> --> <div class="container tm-table"> <div class="col-sm-<?php echo $width_logo ?> table_cell sm-logo-affix"> <?php echo '<h2 class="header_logo">'; ?> <a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?> - <?php bloginfo( 'description' ); ?>" rel="home"> <?php if ( isset( $sticky_logo_src ) ) { if ( $sticky_logo_src ) { $aloxo_logo_size = @getimagesize( $sticky_logo_src ); $width = $aloxo_logo_size[0]; $height = $aloxo_logo_size[1]; $site_title = esc_attr( get_bloginfo( 'name', 'display' ) ); echo '<img src="' . $sticky_logo_src . '" alt="' . $site_title . '" width="' . $width . '" height="' . $height . '" />'; } else { $aloxo_logo_size = @getimagesize( $logo_src ); $width = $aloxo_logo_size[0]; $height = $aloxo_logo_size[1]; $site_title = esc_attr( get_bloginfo( 'name', 'display' ) ); echo '<img src="' . $logo_src . '" alt="' . $site_title . '" width="' . $width . '" height="' . $height . '" />'; } } ?> </a> <?php echo '</h2>'; ?> </div> <nav class="col-sm-<?php echo $width_menu ?> table_cell" role="navigation"> <?php get_template_part( 'inc/header/main_menu' ); ?> </nav> </div> <!-- </div> --> </div> <?php if ( isset( $theme_options_data['thim_header_layout'] ) && $theme_options_data['thim_header_layout'] == 'boxed' ) { echo "</div>"; } ?> </header>
yogaValdlabs/shopingchart
wp-content/themes/aloxo/inc/header/header_3.php
PHP
gpl-2.0
7,564
# attack_csrf.rb # model of a cross-site request forgery attack require 'sdsl/view.rb' u = mod :User do stores set(:intentsA, :URI) invokes(:visitA, # user only types dest address that he/she intends to visit :when => [:intentsA.contains(o.destA)]) end goodServer = mod :TrustedServer do stores :cookies, :Op, :Cookie stores :addrA, :Hostname stores set(:protected, :Op) creates :DOM creates :Cookie exports(:httpReqA, :args => [item(:cookie, :Cookie), item(:addrA, :URI)], # if op is protected, only accept when it provides a valid cookie :when => [implies(:protected.contains(o), o.cookie.eq(:cookies[o]))]) invokes(:httpRespA, :when => [triggeredBy :httpReqA]) end badServer = mod :MaliciousServer do stores :addrA, :Hostname creates :DOM exports(:httpReqA2, :args => [item(:cookie, :Cookie), item(:addrA, :URI)]) invokes(:httpRespA, :when => [triggeredBy :httpReqA2]) end goodClient = mod :Client do stores :cookies, :URI, :Cookie exports(:visitA, :args => [item(:destA, :URI)]) exports(:httpRespA, :args => [item(:dom, :DOM), item(:addrA, :URI)]) invokes([:httpReqA, :httpReqA2], :when => [ # req always contains any associated cookie implies(some(:cookies[o.addrA]), o.cookie.eq(:cookies[o.addrA])), disj( # sends a http request only when # the user initiates a connection conj(triggeredBy(:visitA), o.addrA.eq(trig.destA)), # or in response to a src tag conjs([triggeredBy(:httpRespA), trig.dom.tags.src.contains(o.addrA)] )) ]) end dom = datatype :DOM do field set(:tags, :HTMLTag) extends :Payload end addr = datatype :Addr do end uri = datatype :URI do field item(:addr, :Addr) field set(:vals, :Payload) end imgTag = datatype :ImgTag do field item(:src, :URI) extends :HTMLTag end tag = datatype :HTMLTag do setAbstract end cookie = datatype :Cookie do extends :Payload end otherPayload = datatype :OtherPayload do extends :Payload end payload = datatype :Payload do setAbstract end VIEW_CSRF = view :AttackCSRF do modules u, goodServer, badServer, goodClient trusted goodServer, goodClient, u data uri, :Hostname, cookie, otherPayload, payload, dom, tag, imgTag, addr end drawView VIEW_CSRF, "csrf.dot" dumpAlloy VIEW_CSRF, "csrf.als" # puts goodServer # puts badServer # puts goodClient # writeDot mods
kyessenov/poirot
lib/sdsl/case_studies/attack_csrf.rb
Ruby
gpl-2.0
2,814
/* * HTTP protocol analyzer * * Copyright 2000-2011 Willy Tarreau <[email protected]> * * 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. * */ #include <ctype.h> #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <syslog.h> #include <time.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/types.h> #include <netinet/tcp.h> #include <common/appsession.h> #include <common/base64.h> #include <common/chunk.h> #include <common/compat.h> #include <common/config.h> #include <common/debug.h> #include <common/memory.h> #include <common/mini-clist.h> #include <common/standard.h> #include <common/ticks.h> #include <common/time.h> #include <common/uri_auth.h> #include <common/version.h> #include <types/capture.h> #include <types/global.h> #include <proto/acl.h> #include <proto/arg.h> #include <proto/auth.h> #include <proto/backend.h> #include <proto/channel.h> #include <proto/checks.h> #include <proto/compression.h> #include <proto/dumpstats.h> #include <proto/fd.h> #include <proto/frontend.h> #include <proto/log.h> #include <proto/hdr_idx.h> #include <proto/pattern.h> #include <proto/proto_tcp.h> #include <proto/proto_http.h> #include <proto/proxy.h> #include <proto/queue.h> #include <proto/sample.h> #include <proto/server.h> #include <proto/session.h> #include <proto/stream_interface.h> #include <proto/task.h> #include <proto/pattern.h> const char HTTP_100[] = "HTTP/1.1 100 Continue\r\n\r\n"; const struct chunk http_100_chunk = { .str = (char *)&HTTP_100, .len = sizeof(HTTP_100)-1 }; /* Warning: no "connection" header is provided with the 3xx messages below */ const char *HTTP_301 = "HTTP/1.1 301 Moved Permanently\r\n" "Content-length: 0\r\n" "Location: "; /* not terminated since it will be concatenated with the URL */ const char *HTTP_302 = "HTTP/1.1 302 Found\r\n" "Cache-Control: no-cache\r\n" "Content-length: 0\r\n" "Location: "; /* not terminated since it will be concatenated with the URL */ /* same as 302 except that the browser MUST retry with the GET method */ const char *HTTP_303 = "HTTP/1.1 303 See Other\r\n" "Cache-Control: no-cache\r\n" "Content-length: 0\r\n" "Location: "; /* not terminated since it will be concatenated with the URL */ /* same as 302 except that the browser MUST retry with the same method */ const char *HTTP_307 = "HTTP/1.1 307 Temporary Redirect\r\n" "Cache-Control: no-cache\r\n" "Content-length: 0\r\n" "Location: "; /* not terminated since it will be concatenated with the URL */ /* same as 301 except that the browser MUST retry with the same method */ const char *HTTP_308 = "HTTP/1.1 308 Permanent Redirect\r\n" "Content-length: 0\r\n" "Location: "; /* not terminated since it will be concatenated with the URL */ /* Warning: this one is an sprintf() fmt string, with <realm> as its only argument */ const char *HTTP_401_fmt = "HTTP/1.0 401 Unauthorized\r\n" "Cache-Control: no-cache\r\n" "Connection: close\r\n" "Content-Type: text/html\r\n" "WWW-Authenticate: Basic realm=\"%s\"\r\n" "\r\n" "<html><body><h1>401 Unauthorized</h1>\nYou need a valid user and password to access this content.\n</body></html>\n"; const char *HTTP_407_fmt = "HTTP/1.0 407 Unauthorized\r\n" "Cache-Control: no-cache\r\n" "Connection: close\r\n" "Content-Type: text/html\r\n" "Proxy-Authenticate: Basic realm=\"%s\"\r\n" "\r\n" "<html><body><h1>401 Unauthorized</h1>\nYou need a valid user and password to access this content.\n</body></html>\n"; const int http_err_codes[HTTP_ERR_SIZE] = { [HTTP_ERR_200] = 200, /* used by "monitor-uri" */ [HTTP_ERR_400] = 400, [HTTP_ERR_403] = 403, [HTTP_ERR_408] = 408, [HTTP_ERR_500] = 500, [HTTP_ERR_502] = 502, [HTTP_ERR_503] = 503, [HTTP_ERR_504] = 504, }; static const char *http_err_msgs[HTTP_ERR_SIZE] = { [HTTP_ERR_200] = "HTTP/1.0 200 OK\r\n" "Cache-Control: no-cache\r\n" "Connection: close\r\n" "Content-Type: text/html\r\n" "\r\n" "<html><body><h1>200 OK</h1>\nService ready.\n</body></html>\n", [HTTP_ERR_400] = "HTTP/1.0 400 Bad request\r\n" "Cache-Control: no-cache\r\n" "Connection: close\r\n" "Content-Type: text/html\r\n" "\r\n" "<html><body><h1>400 Bad request</h1>\nYour browser sent an invalid request.\n</body></html>\n", [HTTP_ERR_403] = "HTTP/1.0 403 Forbidden\r\n" "Cache-Control: no-cache\r\n" "Connection: close\r\n" "Content-Type: text/html\r\n" "\r\n" "<html><body><h1>403 Forbidden</h1>\nRequest forbidden by administrative rules.\n</body></html>\n", [HTTP_ERR_408] = "HTTP/1.0 408 Request Time-out\r\n" "Cache-Control: no-cache\r\n" "Connection: close\r\n" "Content-Type: text/html\r\n" "\r\n" "<html><body><h1>408 Request Time-out</h1>\nYour browser didn't send a complete request in time.\n</body></html>\n", [HTTP_ERR_500] = "HTTP/1.0 500 Server Error\r\n" "Cache-Control: no-cache\r\n" "Connection: close\r\n" "Content-Type: text/html\r\n" "\r\n" "<html><body><h1>500 Server Error</h1>\nAn internal server error occured.\n</body></html>\n", [HTTP_ERR_502] = "HTTP/1.0 502 Bad Gateway\r\n" "Cache-Control: no-cache\r\n" "Connection: close\r\n" "Content-Type: text/html\r\n" "\r\n" "<html><body><h1>502 Bad Gateway</h1>\nThe server returned an invalid or incomplete response.\n</body></html>\n", [HTTP_ERR_503] = "HTTP/1.0 503 Service Unavailable\r\n" "Cache-Control: no-cache\r\n" "Connection: close\r\n" "Content-Type: text/html\r\n" "\r\n" "<html><body><h1>503 Service Unavailable</h1>\nNo server is available to handle this request.\n</body></html>\n", [HTTP_ERR_504] = "HTTP/1.0 504 Gateway Time-out\r\n" "Cache-Control: no-cache\r\n" "Connection: close\r\n" "Content-Type: text/html\r\n" "\r\n" "<html><body><h1>504 Gateway Time-out</h1>\nThe server didn't respond in time.\n</body></html>\n", }; /* status codes available for the stats admin page (strictly 4 chars length) */ const char *stat_status_codes[STAT_STATUS_SIZE] = { [STAT_STATUS_DENY] = "DENY", [STAT_STATUS_DONE] = "DONE", [STAT_STATUS_ERRP] = "ERRP", [STAT_STATUS_EXCD] = "EXCD", [STAT_STATUS_NONE] = "NONE", [STAT_STATUS_PART] = "PART", [STAT_STATUS_UNKN] = "UNKN", }; /* List head of all known action keywords for "http-request" */ struct http_req_action_kw_list http_req_keywords = { .list = LIST_HEAD_INIT(http_req_keywords.list) }; /* List head of all known action keywords for "http-response" */ struct http_res_action_kw_list http_res_keywords = { .list = LIST_HEAD_INIT(http_res_keywords.list) }; /* We must put the messages here since GCC cannot initialize consts depending * on strlen(). */ struct chunk http_err_chunks[HTTP_ERR_SIZE]; /* this struct is used between calls to smp_fetch_hdr() or smp_fetch_cookie() */ static struct hdr_ctx static_hdr_ctx; #define FD_SETS_ARE_BITFIELDS #ifdef FD_SETS_ARE_BITFIELDS /* * This map is used with all the FD_* macros to check whether a particular bit * is set or not. Each bit represents an ACSII code. FD_SET() sets those bytes * which should be encoded. When FD_ISSET() returns non-zero, it means that the * byte should be encoded. Be careful to always pass bytes from 0 to 255 * exclusively to the macros. */ fd_set hdr_encode_map[(sizeof(fd_set) > (256/8)) ? 1 : ((256/8) / sizeof(fd_set))]; fd_set url_encode_map[(sizeof(fd_set) > (256/8)) ? 1 : ((256/8) / sizeof(fd_set))]; fd_set http_encode_map[(sizeof(fd_set) > (256/8)) ? 1 : ((256/8) / sizeof(fd_set))]; #else #error "Check if your OS uses bitfields for fd_sets" #endif static int http_apply_redirect_rule(struct redirect_rule *rule, struct session *s, struct http_txn *txn); void init_proto_http() { int i; char *tmp; int msg; for (msg = 0; msg < HTTP_ERR_SIZE; msg++) { if (!http_err_msgs[msg]) { Alert("Internal error: no message defined for HTTP return code %d. Aborting.\n", msg); abort(); } http_err_chunks[msg].str = (char *)http_err_msgs[msg]; http_err_chunks[msg].len = strlen(http_err_msgs[msg]); } /* initialize the log header encoding map : '{|}"#' should be encoded with * '#' as prefix, as well as non-printable characters ( <32 or >= 127 ). * URL encoding only requires '"', '#' to be encoded as well as non- * printable characters above. */ memset(hdr_encode_map, 0, sizeof(hdr_encode_map)); memset(url_encode_map, 0, sizeof(url_encode_map)); memset(http_encode_map, 0, sizeof(url_encode_map)); for (i = 0; i < 32; i++) { FD_SET(i, hdr_encode_map); FD_SET(i, url_encode_map); } for (i = 127; i < 256; i++) { FD_SET(i, hdr_encode_map); FD_SET(i, url_encode_map); } tmp = "\"#{|}"; while (*tmp) { FD_SET(*tmp, hdr_encode_map); tmp++; } tmp = "\"#"; while (*tmp) { FD_SET(*tmp, url_encode_map); tmp++; } /* initialize the http header encoding map. The draft httpbis define the * header content as: * * HTTP-message = start-line * *( header-field CRLF ) * CRLF * [ message-body ] * header-field = field-name ":" OWS field-value OWS * field-value = *( field-content / obs-fold ) * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] * obs-fold = CRLF 1*( SP / HTAB ) * field-vchar = VCHAR / obs-text * VCHAR = %x21-7E * obs-text = %x80-FF * * All the chars are encoded except "VCHAR", "obs-text", SP and HTAB. * The encoded chars are form 0x00 to 0x08, 0x0a to 0x1f and 0x7f. The * "obs-fold" is volontary forgotten because haproxy remove this. */ memset(http_encode_map, 0, sizeof(http_encode_map)); for (i = 0x00; i <= 0x08; i++) FD_SET(i, http_encode_map); for (i = 0x0a; i <= 0x1f; i++) FD_SET(i, http_encode_map); FD_SET(0x7f, http_encode_map); /* memory allocations */ pool2_requri = create_pool("requri", REQURI_LEN, MEM_F_SHARED); pool2_uniqueid = create_pool("uniqueid", UNIQUEID_LEN, MEM_F_SHARED); } /* * We have 26 list of methods (1 per first letter), each of which can have * up to 3 entries (2 valid, 1 null). */ struct http_method_desc { enum http_meth_t meth; int len; const char text[8]; }; const struct http_method_desc http_methods[26][3] = { ['C' - 'A'] = { [0] = { .meth = HTTP_METH_CONNECT , .len=7, .text="CONNECT" }, }, ['D' - 'A'] = { [0] = { .meth = HTTP_METH_DELETE , .len=6, .text="DELETE" }, }, ['G' - 'A'] = { [0] = { .meth = HTTP_METH_GET , .len=3, .text="GET" }, }, ['H' - 'A'] = { [0] = { .meth = HTTP_METH_HEAD , .len=4, .text="HEAD" }, }, ['P' - 'A'] = { [0] = { .meth = HTTP_METH_POST , .len=4, .text="POST" }, [1] = { .meth = HTTP_METH_PUT , .len=3, .text="PUT" }, }, ['T' - 'A'] = { [0] = { .meth = HTTP_METH_TRACE , .len=5, .text="TRACE" }, }, /* rest is empty like this : * [1] = { .meth = HTTP_METH_NONE , .len=0, .text="" }, */ }; const struct http_method_name http_known_methods[HTTP_METH_OTHER] = { [HTTP_METH_NONE] = { "", 0 }, [HTTP_METH_OPTIONS] = { "OPTIONS", 7 }, [HTTP_METH_GET] = { "GET", 3 }, [HTTP_METH_HEAD] = { "HEAD", 4 }, [HTTP_METH_POST] = { "POST", 4 }, [HTTP_METH_PUT] = { "PUT", 3 }, [HTTP_METH_DELETE] = { "DELETE", 6 }, [HTTP_METH_TRACE] = { "TRACE", 5 }, [HTTP_METH_CONNECT] = { "CONNECT", 7 }, }; /* It is about twice as fast on recent architectures to lookup a byte in a * table than to perform a boolean AND or OR between two tests. Refer to * RFC2616 for those chars. */ const char http_is_spht[256] = { [' '] = 1, ['\t'] = 1, }; const char http_is_crlf[256] = { ['\r'] = 1, ['\n'] = 1, }; const char http_is_lws[256] = { [' '] = 1, ['\t'] = 1, ['\r'] = 1, ['\n'] = 1, }; const char http_is_sep[256] = { ['('] = 1, [')'] = 1, ['<'] = 1, ['>'] = 1, ['@'] = 1, [','] = 1, [';'] = 1, [':'] = 1, ['"'] = 1, ['/'] = 1, ['['] = 1, [']'] = 1, ['{'] = 1, ['}'] = 1, ['?'] = 1, ['='] = 1, [' '] = 1, ['\t'] = 1, ['\\'] = 1, }; const char http_is_ctl[256] = { [0 ... 31] = 1, [127] = 1, }; /* * A token is any ASCII char that is neither a separator nor a CTL char. * Do not overwrite values in assignment since gcc-2.95 will not handle * them correctly. Instead, define every non-CTL char's status. */ const char http_is_token[256] = { [' '] = 0, ['!'] = 1, ['"'] = 0, ['#'] = 1, ['$'] = 1, ['%'] = 1, ['&'] = 1, ['\''] = 1, ['('] = 0, [')'] = 0, ['*'] = 1, ['+'] = 1, [','] = 0, ['-'] = 1, ['.'] = 1, ['/'] = 0, ['0'] = 1, ['1'] = 1, ['2'] = 1, ['3'] = 1, ['4'] = 1, ['5'] = 1, ['6'] = 1, ['7'] = 1, ['8'] = 1, ['9'] = 1, [':'] = 0, [';'] = 0, ['<'] = 0, ['='] = 0, ['>'] = 0, ['?'] = 0, ['@'] = 0, ['A'] = 1, ['B'] = 1, ['C'] = 1, ['D'] = 1, ['E'] = 1, ['F'] = 1, ['G'] = 1, ['H'] = 1, ['I'] = 1, ['J'] = 1, ['K'] = 1, ['L'] = 1, ['M'] = 1, ['N'] = 1, ['O'] = 1, ['P'] = 1, ['Q'] = 1, ['R'] = 1, ['S'] = 1, ['T'] = 1, ['U'] = 1, ['V'] = 1, ['W'] = 1, ['X'] = 1, ['Y'] = 1, ['Z'] = 1, ['['] = 0, ['\\'] = 0, [']'] = 0, ['^'] = 1, ['_'] = 1, ['`'] = 1, ['a'] = 1, ['b'] = 1, ['c'] = 1, ['d'] = 1, ['e'] = 1, ['f'] = 1, ['g'] = 1, ['h'] = 1, ['i'] = 1, ['j'] = 1, ['k'] = 1, ['l'] = 1, ['m'] = 1, ['n'] = 1, ['o'] = 1, ['p'] = 1, ['q'] = 1, ['r'] = 1, ['s'] = 1, ['t'] = 1, ['u'] = 1, ['v'] = 1, ['w'] = 1, ['x'] = 1, ['y'] = 1, ['z'] = 1, ['{'] = 0, ['|'] = 1, ['}'] = 0, ['~'] = 1, }; /* * An http ver_token is any ASCII which can be found in an HTTP version, * which includes 'H', 'T', 'P', '/', '.' and any digit. */ const char http_is_ver_token[256] = { ['.'] = 1, ['/'] = 1, ['0'] = 1, ['1'] = 1, ['2'] = 1, ['3'] = 1, ['4'] = 1, ['5'] = 1, ['6'] = 1, ['7'] = 1, ['8'] = 1, ['9'] = 1, ['H'] = 1, ['P'] = 1, ['T'] = 1, }; /* * Adds a header and its CRLF at the tail of the message's buffer, just before * the last CRLF. Text length is measured first, so it cannot be NULL. * The header is also automatically added to the index <hdr_idx>, and the end * of headers is automatically adjusted. The number of bytes added is returned * on success, otherwise <0 is returned indicating an error. */ int http_header_add_tail(struct http_msg *msg, struct hdr_idx *hdr_idx, const char *text) { int bytes, len; len = strlen(text); bytes = buffer_insert_line2(msg->chn->buf, msg->chn->buf->p + msg->eoh, text, len); if (!bytes) return -1; http_msg_move_end(msg, bytes); return hdr_idx_add(len, 1, hdr_idx, hdr_idx->tail); } /* * Adds a header and its CRLF at the tail of the message's buffer, just before * the last CRLF. <len> bytes are copied, not counting the CRLF. If <text> is NULL, then * the buffer is only opened and the space reserved, but nothing is copied. * The header is also automatically added to the index <hdr_idx>, and the end * of headers is automatically adjusted. The number of bytes added is returned * on success, otherwise <0 is returned indicating an error. */ int http_header_add_tail2(struct http_msg *msg, struct hdr_idx *hdr_idx, const char *text, int len) { int bytes; bytes = buffer_insert_line2(msg->chn->buf, msg->chn->buf->p + msg->eoh, text, len); if (!bytes) return -1; http_msg_move_end(msg, bytes); return hdr_idx_add(len, 1, hdr_idx, hdr_idx->tail); } /* * Checks if <hdr> is exactly <name> for <len> chars, and ends with a colon. * If so, returns the position of the first non-space character relative to * <hdr>, or <end>-<hdr> if not found before. If no value is found, it tries * to return a pointer to the place after the first space. Returns 0 if the * header name does not match. Checks are case-insensitive. */ int http_header_match2(const char *hdr, const char *end, const char *name, int len) { const char *val; if (hdr + len >= end) return 0; if (hdr[len] != ':') return 0; if (strncasecmp(hdr, name, len) != 0) return 0; val = hdr + len + 1; while (val < end && HTTP_IS_SPHT(*val)) val++; if ((val >= end) && (len + 2 <= end - hdr)) return len + 2; /* we may replace starting from second space */ return val - hdr; } /* Find the first or next occurrence of header <name> in message buffer <sol> * using headers index <idx>, and return it in the <ctx> structure. This * structure holds everything necessary to use the header and find next * occurrence. If its <idx> member is 0, the header is searched from the * beginning. Otherwise, the next occurrence is returned. The function returns * 1 when it finds a value, and 0 when there is no more. It is very similar to * http_find_header2() except that it is designed to work with full-line headers * whose comma is not a delimiter but is part of the syntax. As a special case, * if ctx->val is NULL when searching for a new values of a header, the current * header is rescanned. This allows rescanning after a header deletion. */ int http_find_full_header2(const char *name, int len, char *sol, struct hdr_idx *idx, struct hdr_ctx *ctx) { char *eol, *sov; int cur_idx, old_idx; cur_idx = ctx->idx; if (cur_idx) { /* We have previously returned a header, let's search another one */ sol = ctx->line; eol = sol + idx->v[cur_idx].len; goto next_hdr; } /* first request for this header */ sol += hdr_idx_first_pos(idx); old_idx = 0; cur_idx = hdr_idx_first_idx(idx); while (cur_idx) { eol = sol + idx->v[cur_idx].len; if (len == 0) { /* No argument was passed, we want any header. * To achieve this, we simply build a fake request. */ while (sol + len < eol && sol[len] != ':') len++; name = sol; } if ((len < eol - sol) && (sol[len] == ':') && (strncasecmp(sol, name, len) == 0)) { ctx->del = len; sov = sol + len + 1; while (sov < eol && http_is_lws[(unsigned char)*sov]) sov++; ctx->line = sol; ctx->prev = old_idx; ctx->idx = cur_idx; ctx->val = sov - sol; ctx->tws = 0; while (eol > sov && http_is_lws[(unsigned char)*(eol - 1)]) { eol--; ctx->tws++; } ctx->vlen = eol - sov; return 1; } next_hdr: sol = eol + idx->v[cur_idx].cr + 1; old_idx = cur_idx; cur_idx = idx->v[cur_idx].next; } return 0; } /* Find the end of the header value contained between <s> and <e>. See RFC2616, * par 2.2 for more information. Note that it requires a valid header to return * a valid result. This works for headers defined as comma-separated lists. */ char *find_hdr_value_end(char *s, const char *e) { int quoted, qdpair; quoted = qdpair = 0; for (; s < e; s++) { if (qdpair) qdpair = 0; else if (quoted) { if (*s == '\\') qdpair = 1; else if (*s == '"') quoted = 0; } else if (*s == '"') quoted = 1; else if (*s == ',') return s; } return s; } /* Find the first or next occurrence of header <name> in message buffer <sol> * using headers index <idx>, and return it in the <ctx> structure. This * structure holds everything necessary to use the header and find next * occurrence. If its <idx> member is 0, the header is searched from the * beginning. Otherwise, the next occurrence is returned. The function returns * 1 when it finds a value, and 0 when there is no more. It is designed to work * with headers defined as comma-separated lists. As a special case, if ctx->val * is NULL when searching for a new values of a header, the current header is * rescanned. This allows rescanning after a header deletion. */ int http_find_header2(const char *name, int len, char *sol, struct hdr_idx *idx, struct hdr_ctx *ctx) { char *eol, *sov; int cur_idx, old_idx; cur_idx = ctx->idx; if (cur_idx) { /* We have previously returned a value, let's search * another one on the same line. */ sol = ctx->line; ctx->del = ctx->val + ctx->vlen + ctx->tws; sov = sol + ctx->del; eol = sol + idx->v[cur_idx].len; if (sov >= eol) /* no more values in this header */ goto next_hdr; /* values remaining for this header, skip the comma but save it * for later use (eg: for header deletion). */ sov++; while (sov < eol && http_is_lws[(unsigned char)*sov]) sov++; goto return_hdr; } /* first request for this header */ sol += hdr_idx_first_pos(idx); old_idx = 0; cur_idx = hdr_idx_first_idx(idx); while (cur_idx) { eol = sol + idx->v[cur_idx].len; if (len == 0) { /* No argument was passed, we want any header. * To achieve this, we simply build a fake request. */ while (sol + len < eol && sol[len] != ':') len++; name = sol; } if ((len < eol - sol) && (sol[len] == ':') && (strncasecmp(sol, name, len) == 0)) { ctx->del = len; sov = sol + len + 1; while (sov < eol && http_is_lws[(unsigned char)*sov]) sov++; ctx->line = sol; ctx->prev = old_idx; return_hdr: ctx->idx = cur_idx; ctx->val = sov - sol; eol = find_hdr_value_end(sov, eol); ctx->tws = 0; while (eol > sov && http_is_lws[(unsigned char)*(eol - 1)]) { eol--; ctx->tws++; } ctx->vlen = eol - sov; return 1; } next_hdr: sol = eol + idx->v[cur_idx].cr + 1; old_idx = cur_idx; cur_idx = idx->v[cur_idx].next; } return 0; } int http_find_header(const char *name, char *sol, struct hdr_idx *idx, struct hdr_ctx *ctx) { return http_find_header2(name, strlen(name), sol, idx, ctx); } /* Remove one value of a header. This only works on a <ctx> returned by one of * the http_find_header functions. The value is removed, as well as surrounding * commas if any. If the removed value was alone, the whole header is removed. * The ctx is always updated accordingly, as well as the buffer and HTTP * message <msg>. The new index is returned. If it is zero, it means there is * no more header, so any processing may stop. The ctx is always left in a form * that can be handled by http_find_header2() to find next occurrence. */ int http_remove_header2(struct http_msg *msg, struct hdr_idx *idx, struct hdr_ctx *ctx) { int cur_idx = ctx->idx; char *sol = ctx->line; struct hdr_idx_elem *hdr; int delta, skip_comma; if (!cur_idx) return 0; hdr = &idx->v[cur_idx]; if (sol[ctx->del] == ':' && ctx->val + ctx->vlen + ctx->tws == hdr->len) { /* This was the only value of the header, we must now remove it entirely. */ delta = buffer_replace2(msg->chn->buf, sol, sol + hdr->len + hdr->cr + 1, NULL, 0); http_msg_move_end(msg, delta); idx->used--; hdr->len = 0; /* unused entry */ idx->v[ctx->prev].next = idx->v[ctx->idx].next; if (idx->tail == ctx->idx) idx->tail = ctx->prev; ctx->idx = ctx->prev; /* walk back to the end of previous header */ ctx->line -= idx->v[ctx->idx].len + idx->v[cur_idx].cr + 1; ctx->val = idx->v[ctx->idx].len; /* point to end of previous header */ ctx->tws = ctx->vlen = 0; return ctx->idx; } /* This was not the only value of this header. We have to remove between * ctx->del+1 and ctx->val+ctx->vlen+ctx->tws+1 included. If it is the * last entry of the list, we remove the last separator. */ skip_comma = (ctx->val + ctx->vlen + ctx->tws == hdr->len) ? 0 : 1; delta = buffer_replace2(msg->chn->buf, sol + ctx->del + skip_comma, sol + ctx->val + ctx->vlen + ctx->tws + skip_comma, NULL, 0); hdr->len += delta; http_msg_move_end(msg, delta); ctx->val = ctx->del; ctx->tws = ctx->vlen = 0; return ctx->idx; } /* This function handles a server error at the stream interface level. The * stream interface is assumed to be already in a closed state. An optional * message is copied into the input buffer, and an HTTP status code stored. * The error flags are set to the values in arguments. Any pending request * in this buffer will be lost. */ static void http_server_error(struct session *s, struct stream_interface *si, int err, int finst, int status, const struct chunk *msg) { channel_auto_read(si->ob); channel_abort(si->ob); channel_auto_close(si->ob); channel_erase(si->ob); channel_auto_close(si->ib); channel_auto_read(si->ib); if (status > 0 && msg) { s->txn.status = status; bo_inject(si->ib, msg->str, msg->len); } if (!(s->flags & SN_ERR_MASK)) s->flags |= err; if (!(s->flags & SN_FINST_MASK)) s->flags |= finst; } /* This function returns the appropriate error location for the given session * and message. */ struct chunk *http_error_message(struct session *s, int msgnum) { if (s->be->errmsg[msgnum].str) return &s->be->errmsg[msgnum]; else if (s->fe->errmsg[msgnum].str) return &s->fe->errmsg[msgnum]; else return &http_err_chunks[msgnum]; } /* * returns HTTP_METH_NONE if there is nothing valid to read (empty or non-text * string), HTTP_METH_OTHER for unknown methods, or the identified method. */ enum http_meth_t find_http_meth(const char *str, const int len) { unsigned char m; const struct http_method_desc *h; m = ((unsigned)*str - 'A'); if (m < 26) { for (h = http_methods[m]; h->len > 0; h++) { if (unlikely(h->len != len)) continue; if (likely(memcmp(str, h->text, h->len) == 0)) return h->meth; }; return HTTP_METH_OTHER; } return HTTP_METH_NONE; } /* Parse the URI from the given transaction (which is assumed to be in request * phase) and look for the "/" beginning the PATH. If not found, return NULL. * It is returned otherwise. */ static char * http_get_path(struct http_txn *txn) { char *ptr, *end; ptr = txn->req.chn->buf->p + txn->req.sl.rq.u; end = ptr + txn->req.sl.rq.u_l; if (ptr >= end) return NULL; /* RFC2616, par. 5.1.2 : * Request-URI = "*" | absuri | abspath | authority */ if (*ptr == '*') return NULL; if (isalpha((unsigned char)*ptr)) { /* this is a scheme as described by RFC3986, par. 3.1 */ ptr++; while (ptr < end && (isalnum((unsigned char)*ptr) || *ptr == '+' || *ptr == '-' || *ptr == '.')) ptr++; /* skip '://' */ if (ptr == end || *ptr++ != ':') return NULL; if (ptr == end || *ptr++ != '/') return NULL; if (ptr == end || *ptr++ != '/') return NULL; } /* skip [user[:passwd]@]host[:[port]] */ while (ptr < end && *ptr != '/') ptr++; if (ptr == end) return NULL; /* OK, we got the '/' ! */ return ptr; } /* Parse the URI from the given string and look for the "/" beginning the PATH. * If not found, return NULL. It is returned otherwise. */ static char * http_get_path_from_string(char *str) { char *ptr = str; /* RFC2616, par. 5.1.2 : * Request-URI = "*" | absuri | abspath | authority */ if (*ptr == '*') return NULL; if (isalpha((unsigned char)*ptr)) { /* this is a scheme as described by RFC3986, par. 3.1 */ ptr++; while (isalnum((unsigned char)*ptr) || *ptr == '+' || *ptr == '-' || *ptr == '.') ptr++; /* skip '://' */ if (*ptr == '\0' || *ptr++ != ':') return NULL; if (*ptr == '\0' || *ptr++ != '/') return NULL; if (*ptr == '\0' || *ptr++ != '/') return NULL; } /* skip [user[:passwd]@]host[:[port]] */ while (*ptr != '\0' && *ptr != ' ' && *ptr != '/') ptr++; if (*ptr == '\0' || *ptr == ' ') return NULL; /* OK, we got the '/' ! */ return ptr; } /* Returns a 302 for a redirectable request that reaches a server working in * in redirect mode. This may only be called just after the stream interface * has moved to SI_ST_ASS. Unprocessable requests are left unchanged and will * follow normal proxy processing. NOTE: this function is designed to support * being called once data are scheduled for forwarding. */ void http_perform_server_redirect(struct session *s, struct stream_interface *si) { struct http_txn *txn; struct server *srv; char *path; int len, rewind; /* 1: create the response header */ trash.len = strlen(HTTP_302); memcpy(trash.str, HTTP_302, trash.len); srv = objt_server(s->target); /* 2: add the server's prefix */ if (trash.len + srv->rdr_len > trash.size) return; /* special prefix "/" means don't change URL */ if (srv->rdr_len != 1 || *srv->rdr_pfx != '/') { memcpy(trash.str + trash.len, srv->rdr_pfx, srv->rdr_len); trash.len += srv->rdr_len; } /* 3: add the request URI. Since it was already forwarded, we need * to temporarily rewind the buffer. */ txn = &s->txn; b_rew(s->req->buf, rewind = http_hdr_rewind(&txn->req)); path = http_get_path(txn); len = buffer_count(s->req->buf, path, b_ptr(s->req->buf, txn->req.sl.rq.u + txn->req.sl.rq.u_l)); b_adv(s->req->buf, rewind); if (!path) return; if (trash.len + len > trash.size - 4) /* 4 for CRLF-CRLF */ return; memcpy(trash.str + trash.len, path, len); trash.len += len; if (unlikely(txn->flags & TX_USE_PX_CONN)) { memcpy(trash.str + trash.len, "\r\nProxy-Connection: close\r\n\r\n", 29); trash.len += 29; } else { memcpy(trash.str + trash.len, "\r\nConnection: close\r\n\r\n", 23); trash.len += 23; } /* prepare to return without error. */ si_shutr(si); si_shutw(si); si->err_type = SI_ET_NONE; si->state = SI_ST_CLO; /* send the message */ http_server_error(s, si, SN_ERR_LOCAL, SN_FINST_C, 302, &trash); /* FIXME: we should increase a counter of redirects per server and per backend. */ srv_inc_sess_ctr(srv); srv_set_sess_last(srv); } /* Return the error message corresponding to si->err_type. It is assumed * that the server side is closed. Note that err_type is actually a * bitmask, where almost only aborts may be cumulated with other * values. We consider that aborted operations are more important * than timeouts or errors due to the fact that nobody else in the * logs might explain incomplete retries. All others should avoid * being cumulated. It should normally not be possible to have multiple * aborts at once, but just in case, the first one in sequence is reported. * Note that connection errors appearing on the second request of a keep-alive * connection are not reported since this allows the client to retry. */ void http_return_srv_error(struct session *s, struct stream_interface *si) { int err_type = si->err_type; if (err_type & SI_ET_QUEUE_ABRT) http_server_error(s, si, SN_ERR_CLICL, SN_FINST_Q, 503, http_error_message(s, HTTP_ERR_503)); else if (err_type & SI_ET_CONN_ABRT) http_server_error(s, si, SN_ERR_CLICL, SN_FINST_C, 503, (s->txn.flags & TX_NOT_FIRST) ? NULL : http_error_message(s, HTTP_ERR_503)); else if (err_type & SI_ET_QUEUE_TO) http_server_error(s, si, SN_ERR_SRVTO, SN_FINST_Q, 503, http_error_message(s, HTTP_ERR_503)); else if (err_type & SI_ET_QUEUE_ERR) http_server_error(s, si, SN_ERR_SRVCL, SN_FINST_Q, 503, http_error_message(s, HTTP_ERR_503)); else if (err_type & SI_ET_CONN_TO) http_server_error(s, si, SN_ERR_SRVTO, SN_FINST_C, 503, (s->txn.flags & TX_NOT_FIRST) ? NULL : http_error_message(s, HTTP_ERR_503)); else if (err_type & SI_ET_CONN_ERR) http_server_error(s, si, SN_ERR_SRVCL, SN_FINST_C, 503, (s->flags & SN_SRV_REUSED) ? NULL : http_error_message(s, HTTP_ERR_503)); else if (err_type & SI_ET_CONN_RES) http_server_error(s, si, SN_ERR_RESOURCE, SN_FINST_C, 503, (s->txn.flags & TX_NOT_FIRST) ? NULL : http_error_message(s, HTTP_ERR_503)); else /* SI_ET_CONN_OTHER and others */ http_server_error(s, si, SN_ERR_INTERNAL, SN_FINST_C, 500, http_error_message(s, HTTP_ERR_500)); } extern const char sess_term_cond[8]; extern const char sess_fin_state[8]; extern const char *monthname[12]; struct pool_head *pool2_requri; struct pool_head *pool2_capture = NULL; struct pool_head *pool2_uniqueid; /* * Capture headers from message starting at <som> according to header list * <cap_hdr>, and fill the <cap> pointers appropriately. */ void capture_headers(char *som, struct hdr_idx *idx, char **cap, struct cap_hdr *cap_hdr) { char *eol, *sol, *col, *sov; int cur_idx; struct cap_hdr *h; int len; sol = som + hdr_idx_first_pos(idx); cur_idx = hdr_idx_first_idx(idx); while (cur_idx) { eol = sol + idx->v[cur_idx].len; col = sol; while (col < eol && *col != ':') col++; sov = col + 1; while (sov < eol && http_is_lws[(unsigned char)*sov]) sov++; for (h = cap_hdr; h; h = h->next) { if (h->namelen && (h->namelen == col - sol) && (strncasecmp(sol, h->name, h->namelen) == 0)) { if (cap[h->index] == NULL) cap[h->index] = pool_alloc2(h->pool); if (cap[h->index] == NULL) { Alert("HTTP capture : out of memory.\n"); continue; } len = eol - sov; if (len > h->len) len = h->len; memcpy(cap[h->index], sov, len); cap[h->index][len]=0; } } sol = eol + idx->v[cur_idx].cr + 1; cur_idx = idx->v[cur_idx].next; } } /* either we find an LF at <ptr> or we jump to <bad>. */ #define EXPECT_LF_HERE(ptr, bad) do { if (unlikely(*(ptr) != '\n')) goto bad; } while (0) /* plays with variables <ptr>, <end> and <state>. Jumps to <good> if OK, * otherwise to <http_msg_ood> with <state> set to <st>. */ #define EAT_AND_JUMP_OR_RETURN(good, st) do { \ ptr++; \ if (likely(ptr < end)) \ goto good; \ else { \ state = (st); \ goto http_msg_ood; \ } \ } while (0) /* * This function parses a status line between <ptr> and <end>, starting with * parser state <state>. Only states HTTP_MSG_RPVER, HTTP_MSG_RPVER_SP, * HTTP_MSG_RPCODE, HTTP_MSG_RPCODE_SP and HTTP_MSG_RPREASON are handled. Others * will give undefined results. * Note that it is upon the caller's responsibility to ensure that ptr < end, * and that msg->sol points to the beginning of the response. * If a complete line is found (which implies that at least one CR or LF is * found before <end>, the updated <ptr> is returned, otherwise NULL is * returned indicating an incomplete line (which does not mean that parts have * not been updated). In the incomplete case, if <ret_ptr> or <ret_state> are * non-NULL, they are fed with the new <ptr> and <state> values to be passed * upon next call. * * This function was intentionally designed to be called from * http_msg_analyzer() with the lowest overhead. It should integrate perfectly * within its state machine and use the same macros, hence the need for same * labels and variable names. Note that msg->sol is left unchanged. */ const char *http_parse_stsline(struct http_msg *msg, enum ht_state state, const char *ptr, const char *end, unsigned int *ret_ptr, enum ht_state *ret_state) { const char *msg_start = msg->chn->buf->p; switch (state) { case HTTP_MSG_RPVER: http_msg_rpver: if (likely(HTTP_IS_VER_TOKEN(*ptr))) EAT_AND_JUMP_OR_RETURN(http_msg_rpver, HTTP_MSG_RPVER); if (likely(HTTP_IS_SPHT(*ptr))) { msg->sl.st.v_l = ptr - msg_start; EAT_AND_JUMP_OR_RETURN(http_msg_rpver_sp, HTTP_MSG_RPVER_SP); } state = HTTP_MSG_ERROR; break; case HTTP_MSG_RPVER_SP: http_msg_rpver_sp: if (likely(!HTTP_IS_LWS(*ptr))) { msg->sl.st.c = ptr - msg_start; goto http_msg_rpcode; } if (likely(HTTP_IS_SPHT(*ptr))) EAT_AND_JUMP_OR_RETURN(http_msg_rpver_sp, HTTP_MSG_RPVER_SP); /* so it's a CR/LF, this is invalid */ state = HTTP_MSG_ERROR; break; case HTTP_MSG_RPCODE: http_msg_rpcode: if (likely(!HTTP_IS_LWS(*ptr))) EAT_AND_JUMP_OR_RETURN(http_msg_rpcode, HTTP_MSG_RPCODE); if (likely(HTTP_IS_SPHT(*ptr))) { msg->sl.st.c_l = ptr - msg_start - msg->sl.st.c; EAT_AND_JUMP_OR_RETURN(http_msg_rpcode_sp, HTTP_MSG_RPCODE_SP); } /* so it's a CR/LF, so there is no reason phrase */ msg->sl.st.c_l = ptr - msg_start - msg->sl.st.c; http_msg_rsp_reason: /* FIXME: should we support HTTP responses without any reason phrase ? */ msg->sl.st.r = ptr - msg_start; msg->sl.st.r_l = 0; goto http_msg_rpline_eol; case HTTP_MSG_RPCODE_SP: http_msg_rpcode_sp: if (likely(!HTTP_IS_LWS(*ptr))) { msg->sl.st.r = ptr - msg_start; goto http_msg_rpreason; } if (likely(HTTP_IS_SPHT(*ptr))) EAT_AND_JUMP_OR_RETURN(http_msg_rpcode_sp, HTTP_MSG_RPCODE_SP); /* so it's a CR/LF, so there is no reason phrase */ goto http_msg_rsp_reason; case HTTP_MSG_RPREASON: http_msg_rpreason: if (likely(!HTTP_IS_CRLF(*ptr))) EAT_AND_JUMP_OR_RETURN(http_msg_rpreason, HTTP_MSG_RPREASON); msg->sl.st.r_l = ptr - msg_start - msg->sl.st.r; http_msg_rpline_eol: /* We have seen the end of line. Note that we do not * necessarily have the \n yet, but at least we know that we * have EITHER \r OR \n, otherwise the response would not be * complete. We can then record the response length and return * to the caller which will be able to register it. */ msg->sl.st.l = ptr - msg_start - msg->sol; return ptr; default: #ifdef DEBUG_FULL fprintf(stderr, "FIXME !!!! impossible state at %s:%d = %d\n", __FILE__, __LINE__, state); exit(1); #endif ; } http_msg_ood: /* out of valid data */ if (ret_state) *ret_state = state; if (ret_ptr) *ret_ptr = ptr - msg_start; return NULL; } /* * This function parses a request line between <ptr> and <end>, starting with * parser state <state>. Only states HTTP_MSG_RQMETH, HTTP_MSG_RQMETH_SP, * HTTP_MSG_RQURI, HTTP_MSG_RQURI_SP and HTTP_MSG_RQVER are handled. Others * will give undefined results. * Note that it is upon the caller's responsibility to ensure that ptr < end, * and that msg->sol points to the beginning of the request. * If a complete line is found (which implies that at least one CR or LF is * found before <end>, the updated <ptr> is returned, otherwise NULL is * returned indicating an incomplete line (which does not mean that parts have * not been updated). In the incomplete case, if <ret_ptr> or <ret_state> are * non-NULL, they are fed with the new <ptr> and <state> values to be passed * upon next call. * * This function was intentionally designed to be called from * http_msg_analyzer() with the lowest overhead. It should integrate perfectly * within its state machine and use the same macros, hence the need for same * labels and variable names. Note that msg->sol is left unchanged. */ const char *http_parse_reqline(struct http_msg *msg, enum ht_state state, const char *ptr, const char *end, unsigned int *ret_ptr, enum ht_state *ret_state) { const char *msg_start = msg->chn->buf->p; switch (state) { case HTTP_MSG_RQMETH: http_msg_rqmeth: if (likely(HTTP_IS_TOKEN(*ptr))) EAT_AND_JUMP_OR_RETURN(http_msg_rqmeth, HTTP_MSG_RQMETH); if (likely(HTTP_IS_SPHT(*ptr))) { msg->sl.rq.m_l = ptr - msg_start; EAT_AND_JUMP_OR_RETURN(http_msg_rqmeth_sp, HTTP_MSG_RQMETH_SP); } if (likely(HTTP_IS_CRLF(*ptr))) { /* HTTP 0.9 request */ msg->sl.rq.m_l = ptr - msg_start; http_msg_req09_uri: msg->sl.rq.u = ptr - msg_start; http_msg_req09_uri_e: msg->sl.rq.u_l = ptr - msg_start - msg->sl.rq.u; http_msg_req09_ver: msg->sl.rq.v = ptr - msg_start; msg->sl.rq.v_l = 0; goto http_msg_rqline_eol; } state = HTTP_MSG_ERROR; break; case HTTP_MSG_RQMETH_SP: http_msg_rqmeth_sp: if (likely(!HTTP_IS_LWS(*ptr))) { msg->sl.rq.u = ptr - msg_start; goto http_msg_rquri; } if (likely(HTTP_IS_SPHT(*ptr))) EAT_AND_JUMP_OR_RETURN(http_msg_rqmeth_sp, HTTP_MSG_RQMETH_SP); /* so it's a CR/LF, meaning an HTTP 0.9 request */ goto http_msg_req09_uri; case HTTP_MSG_RQURI: http_msg_rquri: if (likely((unsigned char)(*ptr - 33) <= 93)) /* 33 to 126 included */ EAT_AND_JUMP_OR_RETURN(http_msg_rquri, HTTP_MSG_RQURI); if (likely(HTTP_IS_SPHT(*ptr))) { msg->sl.rq.u_l = ptr - msg_start - msg->sl.rq.u; EAT_AND_JUMP_OR_RETURN(http_msg_rquri_sp, HTTP_MSG_RQURI_SP); } if (likely((unsigned char)*ptr >= 128)) { /* non-ASCII chars are forbidden unless option * accept-invalid-http-request is enabled in the frontend. * In any case, we capture the faulty char. */ if (msg->err_pos < -1) goto invalid_char; if (msg->err_pos == -1) msg->err_pos = ptr - msg_start; EAT_AND_JUMP_OR_RETURN(http_msg_rquri, HTTP_MSG_RQURI); } if (likely(HTTP_IS_CRLF(*ptr))) { /* so it's a CR/LF, meaning an HTTP 0.9 request */ goto http_msg_req09_uri_e; } /* OK forbidden chars, 0..31 or 127 */ invalid_char: msg->err_pos = ptr - msg_start; state = HTTP_MSG_ERROR; break; case HTTP_MSG_RQURI_SP: http_msg_rquri_sp: if (likely(!HTTP_IS_LWS(*ptr))) { msg->sl.rq.v = ptr - msg_start; goto http_msg_rqver; } if (likely(HTTP_IS_SPHT(*ptr))) EAT_AND_JUMP_OR_RETURN(http_msg_rquri_sp, HTTP_MSG_RQURI_SP); /* so it's a CR/LF, meaning an HTTP 0.9 request */ goto http_msg_req09_ver; case HTTP_MSG_RQVER: http_msg_rqver: if (likely(HTTP_IS_VER_TOKEN(*ptr))) EAT_AND_JUMP_OR_RETURN(http_msg_rqver, HTTP_MSG_RQVER); if (likely(HTTP_IS_CRLF(*ptr))) { msg->sl.rq.v_l = ptr - msg_start - msg->sl.rq.v; http_msg_rqline_eol: /* We have seen the end of line. Note that we do not * necessarily have the \n yet, but at least we know that we * have EITHER \r OR \n, otherwise the request would not be * complete. We can then record the request length and return * to the caller which will be able to register it. */ msg->sl.rq.l = ptr - msg_start - msg->sol; return ptr; } /* neither an HTTP_VER token nor a CRLF */ state = HTTP_MSG_ERROR; break; default: #ifdef DEBUG_FULL fprintf(stderr, "FIXME !!!! impossible state at %s:%d = %d\n", __FILE__, __LINE__, state); exit(1); #endif ; } http_msg_ood: /* out of valid data */ if (ret_state) *ret_state = state; if (ret_ptr) *ret_ptr = ptr - msg_start; return NULL; } /* * Returns the data from Authorization header. Function may be called more * than once so data is stored in txn->auth_data. When no header is found * or auth method is unknown auth_method is set to HTTP_AUTH_WRONG to avoid * searching again for something we are unable to find anyway. However, if * the result if valid, the cache is not reused because we would risk to * have the credentials overwritten by another session in parallel. */ /* This bufffer is initialized in the file 'src/haproxy.c'. This length is * set according to global.tune.bufsize. */ char *get_http_auth_buff; int get_http_auth(struct session *s) { struct http_txn *txn = &s->txn; struct chunk auth_method; struct hdr_ctx ctx; char *h, *p; int len; #ifdef DEBUG_AUTH printf("Auth for session %p: %d\n", s, txn->auth.method); #endif if (txn->auth.method == HTTP_AUTH_WRONG) return 0; txn->auth.method = HTTP_AUTH_WRONG; ctx.idx = 0; if (txn->flags & TX_USE_PX_CONN) { h = "Proxy-Authorization"; len = strlen(h); } else { h = "Authorization"; len = strlen(h); } if (!http_find_header2(h, len, s->req->buf->p, &txn->hdr_idx, &ctx)) return 0; h = ctx.line + ctx.val; p = memchr(h, ' ', ctx.vlen); if (!p || p == h) return 0; chunk_initlen(&auth_method, h, 0, p-h); chunk_initlen(&txn->auth.method_data, p+1, 0, ctx.vlen-(p-h)-1); if (!strncasecmp("Basic", auth_method.str, auth_method.len)) { len = base64dec(txn->auth.method_data.str, txn->auth.method_data.len, get_http_auth_buff, global.tune.bufsize - 1); if (len < 0) return 0; get_http_auth_buff[len] = '\0'; p = strchr(get_http_auth_buff, ':'); if (!p) return 0; txn->auth.user = get_http_auth_buff; *p = '\0'; txn->auth.pass = p+1; txn->auth.method = HTTP_AUTH_BASIC; return 1; } return 0; } /* * This function parses an HTTP message, either a request or a response, * depending on the initial msg->msg_state. The caller is responsible for * ensuring that the message does not wrap. The function can be preempted * everywhere when data are missing and recalled at the exact same location * with no information loss. The message may even be realigned between two * calls. The header index is re-initialized when switching from * MSG_R[PQ]BEFORE to MSG_RPVER|MSG_RQMETH. It modifies msg->sol among other * fields. Note that msg->sol will be initialized after completing the first * state, so that none of the msg pointers has to be initialized prior to the * first call. */ void http_msg_analyzer(struct http_msg *msg, struct hdr_idx *idx) { enum ht_state state; /* updated only when leaving the FSM */ register char *ptr, *end; /* request pointers, to avoid dereferences */ struct buffer *buf; state = msg->msg_state; buf = msg->chn->buf; ptr = buf->p + msg->next; end = buf->p + buf->i; if (unlikely(ptr >= end)) goto http_msg_ood; switch (state) { /* * First, states that are specific to the response only. * We check them first so that request and headers are * closer to each other (accessed more often). */ case HTTP_MSG_RPBEFORE: http_msg_rpbefore: if (likely(HTTP_IS_TOKEN(*ptr))) { /* we have a start of message, but we have to check * first if we need to remove some CRLF. We can only * do this when o=0. */ if (unlikely(ptr != buf->p)) { if (buf->o) goto http_msg_ood; /* Remove empty leading lines, as recommended by RFC2616. */ bi_fast_delete(buf, ptr - buf->p); } msg->sol = 0; msg->sl.st.l = 0; /* used in debug mode */ hdr_idx_init(idx); state = HTTP_MSG_RPVER; goto http_msg_rpver; } if (unlikely(!HTTP_IS_CRLF(*ptr))) goto http_msg_invalid; if (unlikely(*ptr == '\n')) EAT_AND_JUMP_OR_RETURN(http_msg_rpbefore, HTTP_MSG_RPBEFORE); EAT_AND_JUMP_OR_RETURN(http_msg_rpbefore_cr, HTTP_MSG_RPBEFORE_CR); /* stop here */ case HTTP_MSG_RPBEFORE_CR: http_msg_rpbefore_cr: EXPECT_LF_HERE(ptr, http_msg_invalid); EAT_AND_JUMP_OR_RETURN(http_msg_rpbefore, HTTP_MSG_RPBEFORE); /* stop here */ case HTTP_MSG_RPVER: http_msg_rpver: case HTTP_MSG_RPVER_SP: case HTTP_MSG_RPCODE: case HTTP_MSG_RPCODE_SP: case HTTP_MSG_RPREASON: ptr = (char *)http_parse_stsline(msg, state, ptr, end, &msg->next, &msg->msg_state); if (unlikely(!ptr)) return; /* we have a full response and we know that we have either a CR * or an LF at <ptr>. */ hdr_idx_set_start(idx, msg->sl.st.l, *ptr == '\r'); msg->sol = ptr - buf->p; if (likely(*ptr == '\r')) EAT_AND_JUMP_OR_RETURN(http_msg_rpline_end, HTTP_MSG_RPLINE_END); goto http_msg_rpline_end; case HTTP_MSG_RPLINE_END: http_msg_rpline_end: /* msg->sol must point to the first of CR or LF. */ EXPECT_LF_HERE(ptr, http_msg_invalid); EAT_AND_JUMP_OR_RETURN(http_msg_hdr_first, HTTP_MSG_HDR_FIRST); /* stop here */ /* * Second, states that are specific to the request only */ case HTTP_MSG_RQBEFORE: http_msg_rqbefore: if (likely(HTTP_IS_TOKEN(*ptr))) { /* we have a start of message, but we have to check * first if we need to remove some CRLF. We can only * do this when o=0. */ if (likely(ptr != buf->p)) { if (buf->o) goto http_msg_ood; /* Remove empty leading lines, as recommended by RFC2616. */ bi_fast_delete(buf, ptr - buf->p); } msg->sol = 0; msg->sl.rq.l = 0; /* used in debug mode */ state = HTTP_MSG_RQMETH; goto http_msg_rqmeth; } if (unlikely(!HTTP_IS_CRLF(*ptr))) goto http_msg_invalid; if (unlikely(*ptr == '\n')) EAT_AND_JUMP_OR_RETURN(http_msg_rqbefore, HTTP_MSG_RQBEFORE); EAT_AND_JUMP_OR_RETURN(http_msg_rqbefore_cr, HTTP_MSG_RQBEFORE_CR); /* stop here */ case HTTP_MSG_RQBEFORE_CR: http_msg_rqbefore_cr: EXPECT_LF_HERE(ptr, http_msg_invalid); EAT_AND_JUMP_OR_RETURN(http_msg_rqbefore, HTTP_MSG_RQBEFORE); /* stop here */ case HTTP_MSG_RQMETH: http_msg_rqmeth: case HTTP_MSG_RQMETH_SP: case HTTP_MSG_RQURI: case HTTP_MSG_RQURI_SP: case HTTP_MSG_RQVER: ptr = (char *)http_parse_reqline(msg, state, ptr, end, &msg->next, &msg->msg_state); if (unlikely(!ptr)) return; /* we have a full request and we know that we have either a CR * or an LF at <ptr>. */ hdr_idx_set_start(idx, msg->sl.rq.l, *ptr == '\r'); msg->sol = ptr - buf->p; if (likely(*ptr == '\r')) EAT_AND_JUMP_OR_RETURN(http_msg_rqline_end, HTTP_MSG_RQLINE_END); goto http_msg_rqline_end; case HTTP_MSG_RQLINE_END: http_msg_rqline_end: /* check for HTTP/0.9 request : no version information available. * msg->sol must point to the first of CR or LF. */ if (unlikely(msg->sl.rq.v_l == 0)) goto http_msg_last_lf; EXPECT_LF_HERE(ptr, http_msg_invalid); EAT_AND_JUMP_OR_RETURN(http_msg_hdr_first, HTTP_MSG_HDR_FIRST); /* stop here */ /* * Common states below */ case HTTP_MSG_HDR_FIRST: http_msg_hdr_first: msg->sol = ptr - buf->p; if (likely(!HTTP_IS_CRLF(*ptr))) { goto http_msg_hdr_name; } if (likely(*ptr == '\r')) EAT_AND_JUMP_OR_RETURN(http_msg_last_lf, HTTP_MSG_LAST_LF); goto http_msg_last_lf; case HTTP_MSG_HDR_NAME: http_msg_hdr_name: /* assumes msg->sol points to the first char */ if (likely(HTTP_IS_TOKEN(*ptr))) EAT_AND_JUMP_OR_RETURN(http_msg_hdr_name, HTTP_MSG_HDR_NAME); if (likely(*ptr == ':')) EAT_AND_JUMP_OR_RETURN(http_msg_hdr_l1_sp, HTTP_MSG_HDR_L1_SP); if (likely(msg->err_pos < -1) || *ptr == '\n') goto http_msg_invalid; if (msg->err_pos == -1) /* capture error pointer */ msg->err_pos = ptr - buf->p; /* >= 0 now */ /* and we still accept this non-token character */ EAT_AND_JUMP_OR_RETURN(http_msg_hdr_name, HTTP_MSG_HDR_NAME); case HTTP_MSG_HDR_L1_SP: http_msg_hdr_l1_sp: /* assumes msg->sol points to the first char */ if (likely(HTTP_IS_SPHT(*ptr))) EAT_AND_JUMP_OR_RETURN(http_msg_hdr_l1_sp, HTTP_MSG_HDR_L1_SP); /* header value can be basically anything except CR/LF */ msg->sov = ptr - buf->p; if (likely(!HTTP_IS_CRLF(*ptr))) { goto http_msg_hdr_val; } if (likely(*ptr == '\r')) EAT_AND_JUMP_OR_RETURN(http_msg_hdr_l1_lf, HTTP_MSG_HDR_L1_LF); goto http_msg_hdr_l1_lf; case HTTP_MSG_HDR_L1_LF: http_msg_hdr_l1_lf: EXPECT_LF_HERE(ptr, http_msg_invalid); EAT_AND_JUMP_OR_RETURN(http_msg_hdr_l1_lws, HTTP_MSG_HDR_L1_LWS); case HTTP_MSG_HDR_L1_LWS: http_msg_hdr_l1_lws: if (likely(HTTP_IS_SPHT(*ptr))) { /* replace HT,CR,LF with spaces */ for (; buf->p + msg->sov < ptr; msg->sov++) buf->p[msg->sov] = ' '; goto http_msg_hdr_l1_sp; } /* we had a header consisting only in spaces ! */ msg->eol = msg->sov; goto http_msg_complete_header; case HTTP_MSG_HDR_VAL: http_msg_hdr_val: /* assumes msg->sol points to the first char, and msg->sov * points to the first character of the value. */ if (likely(!HTTP_IS_CRLF(*ptr))) EAT_AND_JUMP_OR_RETURN(http_msg_hdr_val, HTTP_MSG_HDR_VAL); msg->eol = ptr - buf->p; /* Note: we could also copy eol into ->eoh so that we have the * real header end in case it ends with lots of LWS, but is this * really needed ? */ if (likely(*ptr == '\r')) EAT_AND_JUMP_OR_RETURN(http_msg_hdr_l2_lf, HTTP_MSG_HDR_L2_LF); goto http_msg_hdr_l2_lf; case HTTP_MSG_HDR_L2_LF: http_msg_hdr_l2_lf: EXPECT_LF_HERE(ptr, http_msg_invalid); EAT_AND_JUMP_OR_RETURN(http_msg_hdr_l2_lws, HTTP_MSG_HDR_L2_LWS); case HTTP_MSG_HDR_L2_LWS: http_msg_hdr_l2_lws: if (unlikely(HTTP_IS_SPHT(*ptr))) { /* LWS: replace HT,CR,LF with spaces */ for (; buf->p + msg->eol < ptr; msg->eol++) buf->p[msg->eol] = ' '; goto http_msg_hdr_val; } http_msg_complete_header: /* * It was a new header, so the last one is finished. * Assumes msg->sol points to the first char, msg->sov points * to the first character of the value and msg->eol to the * first CR or LF so we know how the line ends. We insert last * header into the index. */ if (unlikely(hdr_idx_add(msg->eol - msg->sol, buf->p[msg->eol] == '\r', idx, idx->tail) < 0)) goto http_msg_invalid; msg->sol = ptr - buf->p; if (likely(!HTTP_IS_CRLF(*ptr))) { goto http_msg_hdr_name; } if (likely(*ptr == '\r')) EAT_AND_JUMP_OR_RETURN(http_msg_last_lf, HTTP_MSG_LAST_LF); goto http_msg_last_lf; case HTTP_MSG_LAST_LF: http_msg_last_lf: /* Assumes msg->sol points to the first of either CR or LF. * Sets ->sov and ->next to the total header length, ->eoh to * the last CRLF, and ->eol to the last CRLF length (1 or 2). */ EXPECT_LF_HERE(ptr, http_msg_invalid); ptr++; msg->sov = msg->next = ptr - buf->p; msg->eoh = msg->sol; msg->sol = 0; msg->eol = msg->sov - msg->eoh; msg->msg_state = HTTP_MSG_BODY; return; case HTTP_MSG_ERROR: /* this may only happen if we call http_msg_analyser() twice with an error */ break; default: #ifdef DEBUG_FULL fprintf(stderr, "FIXME !!!! impossible state at %s:%d = %d\n", __FILE__, __LINE__, state); exit(1); #endif ; } http_msg_ood: /* out of data */ msg->msg_state = state; msg->next = ptr - buf->p; return; http_msg_invalid: /* invalid message */ msg->msg_state = HTTP_MSG_ERROR; msg->next = ptr - buf->p; return; } /* convert an HTTP/0.9 request into an HTTP/1.0 request. Returns 1 if the * conversion succeeded, 0 in case of error. If the request was already 1.X, * nothing is done and 1 is returned. */ static int http_upgrade_v09_to_v10(struct http_txn *txn) { int delta; char *cur_end; struct http_msg *msg = &txn->req; if (msg->sl.rq.v_l != 0) return 1; /* RFC 1945 allows only GET for HTTP/0.9 requests */ if (txn->meth != HTTP_METH_GET) return 0; cur_end = msg->chn->buf->p + msg->sl.rq.l; delta = 0; if (msg->sl.rq.u_l == 0) { /* HTTP/0.9 requests *must* have a request URI, per RFC 1945 */ return 0; } /* add HTTP version */ delta = buffer_replace2(msg->chn->buf, cur_end, cur_end, " HTTP/1.0\r\n", 11); http_msg_move_end(msg, delta); cur_end += delta; cur_end = (char *)http_parse_reqline(msg, HTTP_MSG_RQMETH, msg->chn->buf->p, cur_end + 1, NULL, NULL); if (unlikely(!cur_end)) return 0; /* we have a full HTTP/1.0 request now and we know that * we have either a CR or an LF at <ptr>. */ hdr_idx_set_start(&txn->hdr_idx, msg->sl.rq.l, *cur_end == '\r'); return 1; } /* Parse the Connection: header of an HTTP request, looking for both "close" * and "keep-alive" values. If we already know that some headers may safely * be removed, we remove them now. The <to_del> flags are used for that : * - bit 0 means remove "close" headers (in HTTP/1.0 requests/responses) * - bit 1 means remove "keep-alive" headers (in HTTP/1.1 reqs/resp to 1.1). * Presence of the "Upgrade" token is also checked and reported. * The TX_HDR_CONN_* flags are adjusted in txn->flags depending on what was * found, and TX_CON_*_SET is adjusted depending on what is left so only * harmless combinations may be removed. Do not call that after changes have * been processed. */ void http_parse_connection_header(struct http_txn *txn, struct http_msg *msg, int to_del) { struct hdr_ctx ctx; const char *hdr_val = "Connection"; int hdr_len = 10; if (txn->flags & TX_HDR_CONN_PRS) return; if (unlikely(txn->flags & TX_USE_PX_CONN)) { hdr_val = "Proxy-Connection"; hdr_len = 16; } ctx.idx = 0; txn->flags &= ~(TX_CON_KAL_SET|TX_CON_CLO_SET); while (http_find_header2(hdr_val, hdr_len, msg->chn->buf->p, &txn->hdr_idx, &ctx)) { if (ctx.vlen >= 10 && word_match(ctx.line + ctx.val, ctx.vlen, "keep-alive", 10)) { txn->flags |= TX_HDR_CONN_KAL; if (to_del & 2) http_remove_header2(msg, &txn->hdr_idx, &ctx); else txn->flags |= TX_CON_KAL_SET; } else if (ctx.vlen >= 5 && word_match(ctx.line + ctx.val, ctx.vlen, "close", 5)) { txn->flags |= TX_HDR_CONN_CLO; if (to_del & 1) http_remove_header2(msg, &txn->hdr_idx, &ctx); else txn->flags |= TX_CON_CLO_SET; } else if (ctx.vlen >= 7 && word_match(ctx.line + ctx.val, ctx.vlen, "upgrade", 7)) { txn->flags |= TX_HDR_CONN_UPG; } } txn->flags |= TX_HDR_CONN_PRS; return; } /* Apply desired changes on the Connection: header. Values may be removed and/or * added depending on the <wanted> flags, which are exclusively composed of * TX_CON_CLO_SET and TX_CON_KAL_SET, depending on what flags are desired. The * TX_CON_*_SET flags are adjusted in txn->flags depending on what is left. */ void http_change_connection_header(struct http_txn *txn, struct http_msg *msg, int wanted) { struct hdr_ctx ctx; const char *hdr_val = "Connection"; int hdr_len = 10; ctx.idx = 0; if (unlikely(txn->flags & TX_USE_PX_CONN)) { hdr_val = "Proxy-Connection"; hdr_len = 16; } txn->flags &= ~(TX_CON_CLO_SET | TX_CON_KAL_SET); while (http_find_header2(hdr_val, hdr_len, msg->chn->buf->p, &txn->hdr_idx, &ctx)) { if (ctx.vlen >= 10 && word_match(ctx.line + ctx.val, ctx.vlen, "keep-alive", 10)) { if (wanted & TX_CON_KAL_SET) txn->flags |= TX_CON_KAL_SET; else http_remove_header2(msg, &txn->hdr_idx, &ctx); } else if (ctx.vlen >= 5 && word_match(ctx.line + ctx.val, ctx.vlen, "close", 5)) { if (wanted & TX_CON_CLO_SET) txn->flags |= TX_CON_CLO_SET; else http_remove_header2(msg, &txn->hdr_idx, &ctx); } } if (wanted == (txn->flags & (TX_CON_CLO_SET|TX_CON_KAL_SET))) return; if ((wanted & TX_CON_CLO_SET) && !(txn->flags & TX_CON_CLO_SET)) { txn->flags |= TX_CON_CLO_SET; hdr_val = "Connection: close"; hdr_len = 17; if (unlikely(txn->flags & TX_USE_PX_CONN)) { hdr_val = "Proxy-Connection: close"; hdr_len = 23; } http_header_add_tail2(msg, &txn->hdr_idx, hdr_val, hdr_len); } if ((wanted & TX_CON_KAL_SET) && !(txn->flags & TX_CON_KAL_SET)) { txn->flags |= TX_CON_KAL_SET; hdr_val = "Connection: keep-alive"; hdr_len = 22; if (unlikely(txn->flags & TX_USE_PX_CONN)) { hdr_val = "Proxy-Connection: keep-alive"; hdr_len = 28; } http_header_add_tail2(msg, &txn->hdr_idx, hdr_val, hdr_len); } return; } /* Parse the chunk size at msg->next. Once done, it adjusts ->next to point to * the first byte of data after the chunk size, so that we know we can forward * exactly msg->next bytes. msg->sol contains the exact number of bytes forming * the chunk size. That way it is always possible to differentiate between the * start of the body and the start of the data. * Return >0 on success, 0 when some data is missing, <0 on error. * Note: this function is designed to parse wrapped CRLF at the end of the buffer. */ static inline int http_parse_chunk_size(struct http_msg *msg) { const struct buffer *buf = msg->chn->buf; const char *ptr = b_ptr(buf, msg->next); const char *ptr_old = ptr; const char *end = buf->data + buf->size; const char *stop = bi_end(buf); unsigned int chunk = 0; /* The chunk size is in the following form, though we are only * interested in the size and CRLF : * 1*HEXDIGIT *WSP *[ ';' extensions ] CRLF */ while (1) { int c; if (ptr == stop) return 0; c = hex2i(*ptr); if (c < 0) /* not a hex digit anymore */ break; if (unlikely(++ptr >= end)) ptr = buf->data; if (chunk & 0xF8000000) /* integer overflow will occur if result >= 2GB */ goto error; chunk = (chunk << 4) + c; } /* empty size not allowed */ if (unlikely(ptr == ptr_old)) goto error; while (http_is_spht[(unsigned char)*ptr]) { if (++ptr >= end) ptr = buf->data; if (unlikely(ptr == stop)) return 0; } /* Up to there, we know that at least one byte is present at *ptr. Check * for the end of chunk size. */ while (1) { if (likely(HTTP_IS_CRLF(*ptr))) { /* we now have a CR or an LF at ptr */ if (likely(*ptr == '\r')) { if (++ptr >= end) ptr = buf->data; if (ptr == stop) return 0; } if (*ptr != '\n') goto error; if (++ptr >= end) ptr = buf->data; /* done */ break; } else if (*ptr == ';') { /* chunk extension, ends at next CRLF */ if (++ptr >= end) ptr = buf->data; if (ptr == stop) return 0; while (!HTTP_IS_CRLF(*ptr)) { if (++ptr >= end) ptr = buf->data; if (ptr == stop) return 0; } /* we have a CRLF now, loop above */ continue; } else goto error; } /* OK we found our CRLF and now <ptr> points to the next byte, * which may or may not be present. We save that into ->next, * and the number of bytes parsed into msg->sol. */ msg->sol = ptr - ptr_old; if (unlikely(ptr < ptr_old)) msg->sol += buf->size; msg->next = buffer_count(buf, buf->p, ptr); msg->chunk_len = chunk; msg->body_len += chunk; msg->msg_state = chunk ? HTTP_MSG_DATA : HTTP_MSG_TRAILERS; return 1; error: msg->err_pos = buffer_count(buf, buf->p, ptr); return -1; } /* This function skips trailers in the buffer associated with HTTP * message <msg>. The first visited position is msg->next. If the end of * the trailers is found, it is automatically scheduled to be forwarded, * msg->msg_state switches to HTTP_MSG_DONE, and the function returns >0. * If not enough data are available, the function does not change anything * except maybe msg->next if it could parse some lines, and returns zero. * If a parse error is encountered, the function returns < 0 and does not * change anything except maybe msg->next. Note that the message must * already be in HTTP_MSG_TRAILERS state before calling this function, * which implies that all non-trailers data have already been scheduled for * forwarding, and that msg->next exactly matches the length of trailers * already parsed and not forwarded. It is also important to note that this * function is designed to be able to parse wrapped headers at end of buffer. */ static int http_forward_trailers(struct http_msg *msg) { const struct buffer *buf = msg->chn->buf; /* we have msg->next which points to next line. Look for CRLF. */ while (1) { const char *p1 = NULL, *p2 = NULL; const char *ptr = b_ptr(buf, msg->next); const char *stop = bi_end(buf); int bytes; /* scan current line and stop at LF or CRLF */ while (1) { if (ptr == stop) return 0; if (*ptr == '\n') { if (!p1) p1 = ptr; p2 = ptr; break; } if (*ptr == '\r') { if (p1) { msg->err_pos = buffer_count(buf, buf->p, ptr); return -1; } p1 = ptr; } ptr++; if (ptr >= buf->data + buf->size) ptr = buf->data; } /* after LF; point to beginning of next line */ p2++; if (p2 >= buf->data + buf->size) p2 = buf->data; bytes = p2 - b_ptr(buf, msg->next); if (bytes < 0) bytes += buf->size; if (p1 == b_ptr(buf, msg->next)) { /* LF/CRLF at beginning of line => end of trailers at p2. * Everything was scheduled for forwarding, there's nothing * left from this message. */ msg->next = buffer_count(buf, buf->p, p2); msg->msg_state = HTTP_MSG_DONE; return 1; } /* OK, next line then */ msg->next = buffer_count(buf, buf->p, p2); } } /* This function may be called only in HTTP_MSG_CHUNK_CRLF. It reads the CRLF * or a possible LF alone at the end of a chunk. It automatically adjusts * msg->next in order to include this part into the next forwarding phase. * Note that the caller must ensure that ->p points to the first byte to parse. * It also sets msg_state to HTTP_MSG_CHUNK_SIZE and returns >0 on success. If * not enough data are available, the function does not change anything and * returns zero. If a parse error is encountered, the function returns < 0 and * does not change anything. Note: this function is designed to parse wrapped * CRLF at the end of the buffer. */ static inline int http_skip_chunk_crlf(struct http_msg *msg) { const struct buffer *buf = msg->chn->buf; const char *ptr; int bytes; /* NB: we'll check data availabilty at the end. It's not a * problem because whatever we match first will be checked * against the correct length. */ bytes = 1; ptr = b_ptr(buf, msg->next); if (*ptr == '\r') { bytes++; ptr++; if (ptr >= buf->data + buf->size) ptr = buf->data; } if (msg->next + bytes > buf->i) return 0; if (*ptr != '\n') { msg->err_pos = buffer_count(buf, buf->p, ptr); return -1; } ptr++; if (unlikely(ptr >= buf->data + buf->size)) ptr = buf->data; /* Advance ->next to allow the CRLF to be forwarded */ msg->next += bytes; msg->msg_state = HTTP_MSG_CHUNK_SIZE; return 1; } /* Parses a qvalue and returns it multipled by 1000, from 0 to 1000. If the * value is larger than 1000, it is bound to 1000. The parser consumes up to * 1 digit, one dot and 3 digits and stops on the first invalid character. * Unparsable qvalues return 1000 as "q=1.000". */ int parse_qvalue(const char *qvalue, const char **end) { int q = 1000; if (!isdigit((unsigned char)*qvalue)) goto out; q = (*qvalue++ - '0') * 1000; if (*qvalue++ != '.') goto out; if (!isdigit((unsigned char)*qvalue)) goto out; q += (*qvalue++ - '0') * 100; if (!isdigit((unsigned char)*qvalue)) goto out; q += (*qvalue++ - '0') * 10; if (!isdigit((unsigned char)*qvalue)) goto out; q += (*qvalue++ - '0') * 1; out: if (q > 1000) q = 1000; if (end) *end = qvalue; return q; } /* * Selects a compression algorithm depending on the client request. */ int select_compression_request_header(struct session *s, struct buffer *req) { struct http_txn *txn = &s->txn; struct http_msg *msg = &txn->req; struct hdr_ctx ctx; struct comp_algo *comp_algo = NULL; struct comp_algo *comp_algo_back = NULL; /* Disable compression for older user agents announcing themselves as "Mozilla/4" * unless they are known good (MSIE 6 with XP SP2, or MSIE 7 and later). * See http://zoompf.com/2012/02/lose-the-wait-http-compression for more details. */ ctx.idx = 0; if (http_find_header2("User-Agent", 10, req->p, &txn->hdr_idx, &ctx) && ctx.vlen >= 9 && memcmp(ctx.line + ctx.val, "Mozilla/4", 9) == 0 && (ctx.vlen < 31 || memcmp(ctx.line + ctx.val + 25, "MSIE ", 5) != 0 || ctx.line[ctx.val + 30] < '6' || (ctx.line[ctx.val + 30] == '6' && (ctx.vlen < 54 || memcmp(ctx.line + 51, "SV1", 3) != 0)))) { s->comp_algo = NULL; return 0; } /* search for the algo in the backend in priority or the frontend */ if ((s->be->comp && (comp_algo_back = s->be->comp->algos)) || (s->fe->comp && (comp_algo_back = s->fe->comp->algos))) { int best_q = 0; ctx.idx = 0; while (http_find_header2("Accept-Encoding", 15, req->p, &txn->hdr_idx, &ctx)) { const char *qval; int q; int toklen; /* try to isolate the token from the optional q-value */ toklen = 0; while (toklen < ctx.vlen && http_is_token[(unsigned char)*(ctx.line + ctx.val + toklen)]) toklen++; qval = ctx.line + ctx.val + toklen; while (1) { while (qval < ctx.line + ctx.val + ctx.vlen && http_is_lws[(unsigned char)*qval]) qval++; if (qval >= ctx.line + ctx.val + ctx.vlen || *qval != ';') { qval = NULL; break; } qval++; while (qval < ctx.line + ctx.val + ctx.vlen && http_is_lws[(unsigned char)*qval]) qval++; if (qval >= ctx.line + ctx.val + ctx.vlen) { qval = NULL; break; } if (strncmp(qval, "q=", MIN(ctx.line + ctx.val + ctx.vlen - qval, 2)) == 0) break; while (qval < ctx.line + ctx.val + ctx.vlen && *qval != ';') qval++; } /* here we have qval pointing to the first "q=" attribute or NULL if not found */ q = qval ? parse_qvalue(qval + 2, NULL) : 1000; if (q <= best_q) continue; for (comp_algo = comp_algo_back; comp_algo; comp_algo = comp_algo->next) { if (*(ctx.line + ctx.val) == '*' || word_match(ctx.line + ctx.val, toklen, comp_algo->name, comp_algo->name_len)) { s->comp_algo = comp_algo; best_q = q; break; } } } } /* remove all occurrences of the header when "compression offload" is set */ if (s->comp_algo) { if ((s->be->comp && s->be->comp->offload) || (s->fe->comp && s->fe->comp->offload)) { http_remove_header2(msg, &txn->hdr_idx, &ctx); ctx.idx = 0; while (http_find_header2("Accept-Encoding", 15, req->p, &txn->hdr_idx, &ctx)) { http_remove_header2(msg, &txn->hdr_idx, &ctx); } } return 1; } /* identity is implicit does not require headers */ if ((s->be->comp && (comp_algo_back = s->be->comp->algos)) || (s->fe->comp && (comp_algo_back = s->fe->comp->algos))) { for (comp_algo = comp_algo_back; comp_algo; comp_algo = comp_algo->next) { if (comp_algo->add_data == identity_add_data) { s->comp_algo = comp_algo; return 1; } } } s->comp_algo = NULL; return 0; } /* * Selects a comression algorithm depending of the server response. */ int select_compression_response_header(struct session *s, struct buffer *res) { struct http_txn *txn = &s->txn; struct http_msg *msg = &txn->rsp; struct hdr_ctx ctx; struct comp_type *comp_type; /* no common compression algorithm was found in request header */ if (s->comp_algo == NULL) goto fail; /* HTTP < 1.1 should not be compressed */ if (!(msg->flags & HTTP_MSGF_VER_11) || !(txn->req.flags & HTTP_MSGF_VER_11)) goto fail; /* 200 only */ if (txn->status != 200) goto fail; /* Content-Length is null */ if (!(msg->flags & HTTP_MSGF_TE_CHNK) && msg->body_len == 0) goto fail; /* content is already compressed */ ctx.idx = 0; if (http_find_header2("Content-Encoding", 16, res->p, &txn->hdr_idx, &ctx)) goto fail; /* no compression when Cache-Control: no-transform is present in the message */ ctx.idx = 0; while (http_find_header2("Cache-Control", 13, res->p, &txn->hdr_idx, &ctx)) { if (word_match(ctx.line + ctx.val, ctx.vlen, "no-transform", 12)) goto fail; } comp_type = NULL; /* we don't want to compress multipart content-types, nor content-types that are * not listed in the "compression type" directive if any. If no content-type was * found but configuration requires one, we don't compress either. Backend has * the priority. */ ctx.idx = 0; if (http_find_header2("Content-Type", 12, res->p, &txn->hdr_idx, &ctx)) { if (ctx.vlen >= 9 && strncasecmp("multipart", ctx.line+ctx.val, 9) == 0) goto fail; if ((s->be->comp && (comp_type = s->be->comp->types)) || (s->fe->comp && (comp_type = s->fe->comp->types))) { for (; comp_type; comp_type = comp_type->next) { if (ctx.vlen >= comp_type->name_len && strncasecmp(ctx.line+ctx.val, comp_type->name, comp_type->name_len) == 0) /* this Content-Type should be compressed */ break; } /* this Content-Type should not be compressed */ if (comp_type == NULL) goto fail; } } else { /* no content-type header */ if ((s->be->comp && s->be->comp->types) || (s->fe->comp && s->fe->comp->types)) goto fail; /* a content-type was required */ } /* limit compression rate */ if (global.comp_rate_lim > 0) if (read_freq_ctr(&global.comp_bps_in) > global.comp_rate_lim) goto fail; /* limit cpu usage */ if (idle_pct < compress_min_idle) goto fail; /* initialize compression */ if (s->comp_algo->init(&s->comp_ctx, global.tune.comp_maxlevel) < 0) goto fail; s->flags |= SN_COMP_READY; /* remove Content-Length header */ ctx.idx = 0; if ((msg->flags & HTTP_MSGF_CNT_LEN) && http_find_header2("Content-Length", 14, res->p, &txn->hdr_idx, &ctx)) http_remove_header2(msg, &txn->hdr_idx, &ctx); /* add Transfer-Encoding header */ if (!(msg->flags & HTTP_MSGF_TE_CHNK)) http_header_add_tail2(&txn->rsp, &txn->hdr_idx, "Transfer-Encoding: chunked", 26); /* * Add Content-Encoding header when it's not identity encoding. * RFC 2616 : Identity encoding: This content-coding is used only in the * Accept-Encoding header, and SHOULD NOT be used in the Content-Encoding * header. */ if (s->comp_algo->add_data != identity_add_data) { trash.len = 18; memcpy(trash.str, "Content-Encoding: ", trash.len); memcpy(trash.str + trash.len, s->comp_algo->name, s->comp_algo->name_len); trash.len += s->comp_algo->name_len; trash.str[trash.len] = '\0'; http_header_add_tail2(&txn->rsp, &txn->hdr_idx, trash.str, trash.len); } return 1; fail: s->comp_algo = NULL; return 0; } void http_adjust_conn_mode(struct session *s, struct http_txn *txn, struct http_msg *msg) { int tmp = TX_CON_WANT_KAL; if (!((s->fe->options2|s->be->options2) & PR_O2_FAKE_KA)) { if ((s->fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_TUN || (s->be->options & PR_O_HTTP_MODE) == PR_O_HTTP_TUN) tmp = TX_CON_WANT_TUN; if ((s->fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL || (s->be->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL) tmp = TX_CON_WANT_TUN; } if ((s->fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_SCL || (s->be->options & PR_O_HTTP_MODE) == PR_O_HTTP_SCL) { /* option httpclose + server_close => forceclose */ if ((s->fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL || (s->be->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL) tmp = TX_CON_WANT_CLO; else tmp = TX_CON_WANT_SCL; } if ((s->fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_FCL || (s->be->options & PR_O_HTTP_MODE) == PR_O_HTTP_FCL) tmp = TX_CON_WANT_CLO; if ((txn->flags & TX_CON_WANT_MSK) < tmp) txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | tmp; if (!(txn->flags & TX_HDR_CONN_PRS) && (txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN) { /* parse the Connection header and possibly clean it */ int to_del = 0; if ((msg->flags & HTTP_MSGF_VER_11) || ((txn->flags & TX_CON_WANT_MSK) >= TX_CON_WANT_SCL && !((s->fe->options2|s->be->options2) & PR_O2_FAKE_KA))) to_del |= 2; /* remove "keep-alive" */ if (!(msg->flags & HTTP_MSGF_VER_11)) to_del |= 1; /* remove "close" */ http_parse_connection_header(txn, msg, to_del); } /* check if client or config asks for explicit close in KAL/SCL */ if (((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL || (txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_SCL) && ((txn->flags & TX_HDR_CONN_CLO) || /* "connection: close" */ (!(msg->flags & HTTP_MSGF_VER_11) && !(txn->flags & TX_HDR_CONN_KAL)) || /* no "connection: k-a" in 1.0 */ !(msg->flags & HTTP_MSGF_XFER_LEN) || /* no length known => close */ s->fe->state == PR_STSTOPPED)) /* frontend is stopping */ txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_CLO; } /* This stream analyser waits for a complete HTTP request. It returns 1 if the * processing can continue on next analysers, or zero if it either needs more * data or wants to immediately abort the request (eg: timeout, error, ...). It * is tied to AN_REQ_WAIT_HTTP and may may remove itself from s->req->analysers * when it has nothing left to do, and may remove any analyser when it wants to * abort. */ int http_wait_for_request(struct session *s, struct channel *req, int an_bit) { /* * We will parse the partial (or complete) lines. * We will check the request syntax, and also join multi-line * headers. An index of all the lines will be elaborated while * parsing. * * For the parsing, we use a 28 states FSM. * * Here is the information we currently have : * req->buf->p = beginning of request * req->buf->p + msg->eoh = end of processed headers / start of current one * req->buf->p + req->buf->i = end of input data * msg->eol = end of current header or line (LF or CRLF) * msg->next = first non-visited byte * * At end of parsing, we may perform a capture of the error (if any), and * we will set a few fields (txn->meth, sn->flags/SN_REDIRECTABLE). * We also check for monitor-uri, logging, HTTP/0.9 to 1.0 conversion, and * finally headers capture. */ int cur_idx; int use_close_only; struct http_txn *txn = &s->txn; struct http_msg *msg = &txn->req; struct hdr_ctx ctx; DPRINTF(stderr,"[%u] %s: session=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%d analysers=%02x\n", now_ms, __FUNCTION__, s, req, req->rex, req->wex, req->flags, req->buf->i, req->analysers); /* we're speaking HTTP here, so let's speak HTTP to the client */ s->srv_error = http_return_srv_error; /* There's a protected area at the end of the buffer for rewriting * purposes. We don't want to start to parse the request if the * protected area is affected, because we may have to move processed * data later, which is much more complicated. */ if (buffer_not_empty(req->buf) && msg->msg_state < HTTP_MSG_ERROR) { if (txn->flags & TX_NOT_FIRST) { if (unlikely(!channel_reserved(req))) { if (req->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) goto failed_keep_alive; /* some data has still not left the buffer, wake us once that's done */ channel_dont_connect(req); req->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */ req->flags |= CF_WAKE_WRITE; return 0; } if (unlikely(bi_end(req->buf) < b_ptr(req->buf, msg->next) || bi_end(req->buf) > req->buf->data + req->buf->size - global.tune.maxrewrite)) buffer_slow_realign(req->buf); } /* Note that we have the same problem with the response ; we * may want to send a redirect, error or anything which requires * some spare space. So we'll ensure that we have at least * maxrewrite bytes available in the response buffer before * processing that one. This will only affect pipelined * keep-alive requests. */ if ((txn->flags & TX_NOT_FIRST) && unlikely(!channel_reserved(s->rep) || bi_end(s->rep->buf) < b_ptr(s->rep->buf, txn->rsp.next) || bi_end(s->rep->buf) > s->rep->buf->data + s->rep->buf->size - global.tune.maxrewrite)) { if (s->rep->buf->o) { if (s->rep->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) goto failed_keep_alive; /* don't let a connection request be initiated */ channel_dont_connect(req); s->rep->flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */ s->rep->flags |= CF_WAKE_WRITE; s->rep->analysers |= an_bit; /* wake us up once it changes */ return 0; } } if (likely(msg->next < req->buf->i)) /* some unparsed data are available */ http_msg_analyzer(msg, &txn->hdr_idx); } /* 1: we might have to print this header in debug mode */ if (unlikely((global.mode & MODE_DEBUG) && (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) && msg->msg_state >= HTTP_MSG_BODY)) { char *eol, *sol; sol = req->buf->p; /* this is a bit complex : in case of error on the request line, * we know that rq.l is still zero, so we display only the part * up to the end of the line (truncated by debug_hdr). */ eol = sol + (msg->sl.rq.l ? msg->sl.rq.l : req->buf->i); debug_hdr("clireq", s, sol, eol); sol += hdr_idx_first_pos(&txn->hdr_idx); cur_idx = hdr_idx_first_idx(&txn->hdr_idx); while (cur_idx) { eol = sol + txn->hdr_idx.v[cur_idx].len; debug_hdr("clihdr", s, sol, eol); sol = eol + txn->hdr_idx.v[cur_idx].cr + 1; cur_idx = txn->hdr_idx.v[cur_idx].next; } } /* * Now we quickly check if we have found a full valid request. * If not so, we check the FD and buffer states before leaving. * A full request is indicated by the fact that we have seen * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid * requests are checked first. When waiting for a second request * on a keep-alive session, if we encounter and error, close, t/o, * we note the error in the session flags but don't set any state. * Since the error will be noted there, it will not be counted by * process_session() as a frontend error. * Last, we may increase some tracked counters' http request errors on * the cases that are deliberately the client's fault. For instance, * a timeout or connection reset is not counted as an error. However * a bad request is. */ if (unlikely(msg->msg_state < HTTP_MSG_BODY)) { /* * First, let's catch bad requests. */ if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) { session_inc_http_req_ctr(s); session_inc_http_err_ctr(s); proxy_inc_fe_req_ctr(s->fe); goto return_bad_req; } /* 1: Since we are in header mode, if there's no space * left for headers, we won't be able to free more * later, so the session will never terminate. We * must terminate it now. */ if (unlikely(buffer_full(req->buf, global.tune.maxrewrite))) { /* FIXME: check if URI is set and return Status * 414 Request URI too long instead. */ session_inc_http_req_ctr(s); session_inc_http_err_ctr(s); proxy_inc_fe_req_ctr(s->fe); if (msg->err_pos < 0) msg->err_pos = req->buf->i; goto return_bad_req; } /* 2: have we encountered a read error ? */ else if (req->flags & CF_READ_ERROR) { if (!(s->flags & SN_ERR_MASK)) s->flags |= SN_ERR_CLICL; if (txn->flags & TX_WAIT_NEXT_RQ) goto failed_keep_alive; /* we cannot return any message on error */ if (msg->err_pos >= 0) { http_capture_bad_message(&s->fe->invalid_req, s, msg, msg->msg_state, s->fe); session_inc_http_err_ctr(s); } txn->status = 400; stream_int_retnclose(req->prod, NULL); msg->msg_state = HTTP_MSG_ERROR; req->analysers = 0; session_inc_http_req_ctr(s); proxy_inc_fe_req_ctr(s->fe); s->fe->fe_counters.failed_req++; if (s->listener->counters) s->listener->counters->failed_req++; if (!(s->flags & SN_FINST_MASK)) s->flags |= SN_FINST_R; return 0; } /* 3: has the read timeout expired ? */ else if (req->flags & CF_READ_TIMEOUT || tick_is_expired(req->analyse_exp, now_ms)) { if (!(s->flags & SN_ERR_MASK)) s->flags |= SN_ERR_CLITO; if (txn->flags & TX_WAIT_NEXT_RQ) goto failed_keep_alive; /* read timeout : give up with an error message. */ if (msg->err_pos >= 0) { http_capture_bad_message(&s->fe->invalid_req, s, msg, msg->msg_state, s->fe); session_inc_http_err_ctr(s); } txn->status = 408; stream_int_retnclose(req->prod, http_error_message(s, HTTP_ERR_408)); msg->msg_state = HTTP_MSG_ERROR; req->analysers = 0; session_inc_http_req_ctr(s); proxy_inc_fe_req_ctr(s->fe); s->fe->fe_counters.failed_req++; if (s->listener->counters) s->listener->counters->failed_req++; if (!(s->flags & SN_FINST_MASK)) s->flags |= SN_FINST_R; return 0; } /* 4: have we encountered a close ? */ else if (req->flags & CF_SHUTR) { if (!(s->flags & SN_ERR_MASK)) s->flags |= SN_ERR_CLICL; if (txn->flags & TX_WAIT_NEXT_RQ) goto failed_keep_alive; if (msg->err_pos >= 0) http_capture_bad_message(&s->fe->invalid_req, s, msg, msg->msg_state, s->fe); txn->status = 400; stream_int_retnclose(req->prod, http_error_message(s, HTTP_ERR_400)); msg->msg_state = HTTP_MSG_ERROR; req->analysers = 0; session_inc_http_err_ctr(s); session_inc_http_req_ctr(s); proxy_inc_fe_req_ctr(s->fe); s->fe->fe_counters.failed_req++; if (s->listener->counters) s->listener->counters->failed_req++; if (!(s->flags & SN_FINST_MASK)) s->flags |= SN_FINST_R; return 0; } channel_dont_connect(req); req->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */ s->rep->flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */ #ifdef TCP_QUICKACK if (s->listener->options & LI_O_NOQUICKACK && req->buf->i && objt_conn(s->req->prod->end) && conn_ctrl_ready(__objt_conn(s->req->prod->end))) { /* We need more data, we have to re-enable quick-ack in case we * previously disabled it, otherwise we might cause the client * to delay next data. */ setsockopt(__objt_conn(s->req->prod->end)->t.sock.fd, IPPROTO_TCP, TCP_QUICKACK, &one, sizeof(one)); } #endif if ((msg->msg_state != HTTP_MSG_RQBEFORE) && (txn->flags & TX_WAIT_NEXT_RQ)) { /* If the client starts to talk, let's fall back to * request timeout processing. */ txn->flags &= ~TX_WAIT_NEXT_RQ; req->analyse_exp = TICK_ETERNITY; } /* just set the request timeout once at the beginning of the request */ if (!tick_isset(req->analyse_exp)) { if ((msg->msg_state == HTTP_MSG_RQBEFORE) && (txn->flags & TX_WAIT_NEXT_RQ) && tick_isset(s->be->timeout.httpka)) req->analyse_exp = tick_add(now_ms, s->be->timeout.httpka); else req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq); } /* we're not ready yet */ return 0; failed_keep_alive: /* Here we process low-level errors for keep-alive requests. In * short, if the request is not the first one and it experiences * a timeout, read error or shutdown, we just silently close so * that the client can try again. */ txn->status = 0; msg->msg_state = HTTP_MSG_RQBEFORE; req->analysers = 0; s->logs.logwait = 0; s->logs.level = 0; s->rep->flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */ stream_int_retnclose(req->prod, NULL); return 0; } /* OK now we have a complete HTTP request with indexed headers. Let's * complete the request parsing by setting a few fields we will need * later. At this point, we have the last CRLF at req->buf->data + msg->eoh. * If the request is in HTTP/0.9 form, the rule is still true, and eoh * points to the CRLF of the request line. msg->next points to the first * byte after the last LF. msg->sov points to the first byte of data. * msg->eol cannot be trusted because it may have been left uninitialized * (for instance in the absence of headers). */ session_inc_http_req_ctr(s); proxy_inc_fe_req_ctr(s->fe); /* one more valid request for this FE */ if (txn->flags & TX_WAIT_NEXT_RQ) { /* kill the pending keep-alive timeout */ txn->flags &= ~TX_WAIT_NEXT_RQ; req->analyse_exp = TICK_ETERNITY; } /* Maybe we found in invalid header name while we were configured not * to block on that, so we have to capture it now. */ if (unlikely(msg->err_pos >= 0)) http_capture_bad_message(&s->fe->invalid_req, s, msg, msg->msg_state, s->fe); /* * 1: identify the method */ txn->meth = find_http_meth(req->buf->p, msg->sl.rq.m_l); /* we can make use of server redirect on GET and HEAD */ if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD) s->flags |= SN_REDIRECTABLE; /* * 2: check if the URI matches the monitor_uri. * We have to do this for every request which gets in, because * the monitor-uri is defined by the frontend. */ if (unlikely((s->fe->monitor_uri_len != 0) && (s->fe->monitor_uri_len == msg->sl.rq.u_l) && !memcmp(req->buf->p + msg->sl.rq.u, s->fe->monitor_uri, s->fe->monitor_uri_len))) { /* * We have found the monitor URI */ struct acl_cond *cond; s->flags |= SN_MONITOR; s->fe->fe_counters.intercepted_req++; /* Check if we want to fail this monitor request or not */ list_for_each_entry(cond, &s->fe->mon_fail_cond, list) { int ret = acl_exec_cond(cond, s->fe, s, txn, SMP_OPT_DIR_REQ|SMP_OPT_FINAL); ret = acl_pass(ret); if (cond->pol == ACL_COND_UNLESS) ret = !ret; if (ret) { /* we fail this request, let's return 503 service unavail */ txn->status = 503; stream_int_retnclose(req->prod, http_error_message(s, HTTP_ERR_503)); if (!(s->flags & SN_ERR_MASK)) s->flags |= SN_ERR_LOCAL; /* we don't want a real error here */ goto return_prx_cond; } } /* nothing to fail, let's reply normaly */ txn->status = 200; stream_int_retnclose(req->prod, http_error_message(s, HTTP_ERR_200)); if (!(s->flags & SN_ERR_MASK)) s->flags |= SN_ERR_LOCAL; /* we don't want a real error here */ goto return_prx_cond; } /* * 3: Maybe we have to copy the original REQURI for the logs ? * Note: we cannot log anymore if the request has been * classified as invalid. */ if (unlikely(s->logs.logwait & LW_REQ)) { /* we have a complete HTTP request that we must log */ if ((txn->uri = pool_alloc2(pool2_requri)) != NULL) { int urilen = msg->sl.rq.l; if (urilen >= REQURI_LEN) urilen = REQURI_LEN - 1; memcpy(txn->uri, req->buf->p, urilen); txn->uri[urilen] = 0; if (!(s->logs.logwait &= ~(LW_REQ|LW_INIT))) s->do_log(s); } else { Alert("HTTP logging : out of memory.\n"); } } /* 4. We may have to convert HTTP/0.9 requests to HTTP/1.0 */ if (unlikely(msg->sl.rq.v_l == 0) && !http_upgrade_v09_to_v10(txn)) goto return_bad_req; /* ... and check if the request is HTTP/1.1 or above */ if ((msg->sl.rq.v_l == 8) && ((req->buf->p[msg->sl.rq.v + 5] > '1') || ((req->buf->p[msg->sl.rq.v + 5] == '1') && (req->buf->p[msg->sl.rq.v + 7] >= '1')))) msg->flags |= HTTP_MSGF_VER_11; /* "connection" has not been parsed yet */ txn->flags &= ~(TX_HDR_CONN_PRS | TX_HDR_CONN_CLO | TX_HDR_CONN_KAL | TX_HDR_CONN_UPG); /* if the frontend has "option http-use-proxy-header", we'll check if * we have what looks like a proxied connection instead of a connection, * and in this case set the TX_USE_PX_CONN flag to use Proxy-connection. * Note that this is *not* RFC-compliant, however browsers and proxies * happen to do that despite being non-standard :-( * We consider that a request not beginning with either '/' or '*' is * a proxied connection, which covers both "scheme://location" and * CONNECT ip:port. */ if ((s->fe->options2 & PR_O2_USE_PXHDR) && req->buf->p[msg->sl.rq.u] != '/' && req->buf->p[msg->sl.rq.u] != '*') txn->flags |= TX_USE_PX_CONN; /* transfer length unknown*/ msg->flags &= ~HTTP_MSGF_XFER_LEN; /* 5: we may need to capture headers */ if (unlikely((s->logs.logwait & LW_REQHDR) && txn->req.cap)) capture_headers(req->buf->p, &txn->hdr_idx, txn->req.cap, s->fe->req_cap); /* 6: determine the transfer-length. * According to RFC2616 #4.4, amended by the HTTPbis working group, * the presence of a message-body in a REQUEST and its transfer length * must be determined that way (in order of precedence) : * 1. The presence of a message-body in a request is signaled by the * inclusion of a Content-Length or Transfer-Encoding header field * in the request's header fields. When a request message contains * both a message-body of non-zero length and a method that does * not define any semantics for that request message-body, then an * origin server SHOULD either ignore the message-body or respond * with an appropriate error message (e.g., 413). A proxy or * gateway, when presented the same request, SHOULD either forward * the request inbound with the message- body or ignore the * message-body when determining a response. * * 2. If a Transfer-Encoding header field (Section 9.7) is present * and the "chunked" transfer-coding (Section 6.2) is used, the * transfer-length is defined by the use of this transfer-coding. * If a Transfer-Encoding header field is present and the "chunked" * transfer-coding is not present, the transfer-length is defined * by the sender closing the connection. * * 3. If a Content-Length header field is present, its decimal value in * OCTETs represents both the entity-length and the transfer-length. * If a message is received with both a Transfer-Encoding header * field and a Content-Length header field, the latter MUST be ignored. * * 4. By the server closing the connection. (Closing the connection * cannot be used to indicate the end of a request body, since that * would leave no possibility for the server to send back a response.) * * Whenever a transfer-coding is applied to a message-body, the set of * transfer-codings MUST include "chunked", unless the message indicates * it is terminated by closing the connection. When the "chunked" * transfer-coding is used, it MUST be the last transfer-coding applied * to the message-body. */ use_close_only = 0; ctx.idx = 0; /* set TE_CHNK and XFER_LEN only if "chunked" is seen last */ while ((msg->flags & HTTP_MSGF_VER_11) && http_find_header2("Transfer-Encoding", 17, req->buf->p, &txn->hdr_idx, &ctx)) { if (ctx.vlen == 7 && strncasecmp(ctx.line + ctx.val, "chunked", 7) == 0) msg->flags |= (HTTP_MSGF_TE_CHNK | HTTP_MSGF_XFER_LEN); else if (msg->flags & HTTP_MSGF_TE_CHNK) { /* bad transfer-encoding (chunked followed by something else) */ use_close_only = 1; msg->flags &= ~(HTTP_MSGF_TE_CHNK | HTTP_MSGF_XFER_LEN); break; } } ctx.idx = 0; while (!(msg->flags & HTTP_MSGF_TE_CHNK) && !use_close_only && http_find_header2("Content-Length", 14, req->buf->p, &txn->hdr_idx, &ctx)) { signed long long cl; if (!ctx.vlen) { msg->err_pos = ctx.line + ctx.val - req->buf->p; goto return_bad_req; } if (strl2llrc(ctx.line + ctx.val, ctx.vlen, &cl)) { msg->err_pos = ctx.line + ctx.val - req->buf->p; goto return_bad_req; /* parse failure */ } if (cl < 0) { msg->err_pos = ctx.line + ctx.val - req->buf->p; goto return_bad_req; } if ((msg->flags & HTTP_MSGF_CNT_LEN) && (msg->chunk_len != cl)) { msg->err_pos = ctx.line + ctx.val - req->buf->p; goto return_bad_req; /* already specified, was different */ } msg->flags |= HTTP_MSGF_CNT_LEN | HTTP_MSGF_XFER_LEN; msg->body_len = msg->chunk_len = cl; } /* bodyless requests have a known length */ if (!use_close_only) msg->flags |= HTTP_MSGF_XFER_LEN; /* Until set to anything else, the connection mode is set as Keep-Alive. It will * only change if both the request and the config reference something else. * Option httpclose by itself sets tunnel mode where headers are mangled. * However, if another mode is set, it will affect it (eg: server-close/ * keep-alive + httpclose = close). Note that we avoid to redo the same work * if FE and BE have the same settings (common). The method consists in * checking if options changed between the two calls (implying that either * one is non-null, or one of them is non-null and we are there for the first * time. */ if (!(txn->flags & TX_HDR_CONN_PRS) || ((s->fe->options & PR_O_HTTP_MODE) != (s->be->options & PR_O_HTTP_MODE))) http_adjust_conn_mode(s, txn, msg); /* end of job, return OK */ req->analysers &= ~an_bit; req->analyse_exp = TICK_ETERNITY; return 1; return_bad_req: /* We centralize bad requests processing here */ if (unlikely(msg->msg_state == HTTP_MSG_ERROR) || msg->err_pos >= 0) { /* we detected a parsing error. We want to archive this request * in the dedicated proxy area for later troubleshooting. */ http_capture_bad_message(&s->fe->invalid_req, s, msg, msg->msg_state, s->fe); } txn->req.msg_state = HTTP_MSG_ERROR; txn->status = 400; stream_int_retnclose(req->prod, http_error_message(s, HTTP_ERR_400)); s->fe->fe_counters.failed_req++; if (s->listener->counters) s->listener->counters->failed_req++; return_prx_cond: if (!(s->flags & SN_ERR_MASK)) s->flags |= SN_ERR_PRXCOND; if (!(s->flags & SN_FINST_MASK)) s->flags |= SN_FINST_R; req->analysers = 0; req->analyse_exp = TICK_ETERNITY; return 0; } /* This function prepares an applet to handle the stats. It can deal with the * "100-continue" expectation, check that admin rules are met for POST requests, * and program a response message if something was unexpected. It cannot fail * and always relies on the stats applet to complete the job. It does not touch * analysers nor counters, which are left to the caller. It does not touch * s->target which is supposed to already point to the stats applet. The caller * is expected to have already assigned an appctx to the session. */ int http_handle_stats(struct session *s, struct channel *req) { struct stats_admin_rule *stats_admin_rule; struct stream_interface *si = s->rep->prod; struct http_txn *txn = &s->txn; struct http_msg *msg = &txn->req; struct uri_auth *uri_auth = s->be->uri_auth; const char *uri, *h, *lookup; struct appctx *appctx; appctx = si_appctx(si); memset(&appctx->ctx.stats, 0, sizeof(appctx->ctx.stats)); appctx->st1 = appctx->st2 = 0; appctx->ctx.stats.st_code = STAT_STATUS_INIT; appctx->ctx.stats.flags |= STAT_FMT_HTML; /* assume HTML mode by default */ if ((msg->flags & HTTP_MSGF_VER_11) && (s->txn.meth != HTTP_METH_HEAD)) appctx->ctx.stats.flags |= STAT_CHUNKED; uri = msg->chn->buf->p + msg->sl.rq.u; lookup = uri + uri_auth->uri_len; for (h = lookup; h <= uri + msg->sl.rq.u_l - 3; h++) { if (memcmp(h, ";up", 3) == 0) { appctx->ctx.stats.flags |= STAT_HIDE_DOWN; break; } } if (uri_auth->refresh) { for (h = lookup; h <= uri + msg->sl.rq.u_l - 10; h++) { if (memcmp(h, ";norefresh", 10) == 0) { appctx->ctx.stats.flags |= STAT_NO_REFRESH; break; } } } for (h = lookup; h <= uri + msg->sl.rq.u_l - 4; h++) { if (memcmp(h, ";csv", 4) == 0) { appctx->ctx.stats.flags &= ~STAT_FMT_HTML; break; } } for (h = lookup; h <= uri + msg->sl.rq.u_l - 8; h++) { if (memcmp(h, ";st=", 4) == 0) { int i; h += 4; appctx->ctx.stats.st_code = STAT_STATUS_UNKN; for (i = STAT_STATUS_INIT + 1; i < STAT_STATUS_SIZE; i++) { if (strncmp(stat_status_codes[i], h, 4) == 0) { appctx->ctx.stats.st_code = i; break; } } break; } } appctx->ctx.stats.scope_str = 0; appctx->ctx.stats.scope_len = 0; for (h = lookup; h <= uri + msg->sl.rq.u_l - 8; h++) { if (memcmp(h, STAT_SCOPE_INPUT_NAME "=", strlen(STAT_SCOPE_INPUT_NAME) + 1) == 0) { int itx = 0; const char *h2; char scope_txt[STAT_SCOPE_TXT_MAXLEN + 1]; const char *err; h += strlen(STAT_SCOPE_INPUT_NAME) + 1; h2 = h; appctx->ctx.stats.scope_str = h2 - msg->chn->buf->p; while (*h != ';' && *h != '\0' && *h != '&' && *h != ' ' && *h != '\n') { itx++; h++; } if (itx > STAT_SCOPE_TXT_MAXLEN) itx = STAT_SCOPE_TXT_MAXLEN; appctx->ctx.stats.scope_len = itx; /* scope_txt = search query, appctx->ctx.stats.scope_len is always <= STAT_SCOPE_TXT_MAXLEN */ memcpy(scope_txt, h2, itx); scope_txt[itx] = '\0'; err = invalid_char(scope_txt); if (err) { /* bad char in search text => clear scope */ appctx->ctx.stats.scope_str = 0; appctx->ctx.stats.scope_len = 0; } break; } } /* now check whether we have some admin rules for this request */ list_for_each_entry(stats_admin_rule, &uri_auth->admin_rules, list) { int ret = 1; if (stats_admin_rule->cond) { ret = acl_exec_cond(stats_admin_rule->cond, s->be, s, &s->txn, SMP_OPT_DIR_REQ|SMP_OPT_FINAL); ret = acl_pass(ret); if (stats_admin_rule->cond->pol == ACL_COND_UNLESS) ret = !ret; } if (ret) { /* no rule, or the rule matches */ appctx->ctx.stats.flags |= STAT_ADMIN; break; } } /* Was the status page requested with a POST ? */ if (unlikely(txn->meth == HTTP_METH_POST && txn->req.body_len > 0)) { if (appctx->ctx.stats.flags & STAT_ADMIN) { /* we'll need the request body, possibly after sending 100-continue */ req->analysers |= AN_REQ_HTTP_BODY; appctx->st0 = STAT_HTTP_POST; } else { appctx->ctx.stats.st_code = STAT_STATUS_DENY; appctx->st0 = STAT_HTTP_LAST; } } else { /* So it was another method (GET/HEAD) */ appctx->st0 = STAT_HTTP_HEAD; } s->task->nice = -32; /* small boost for HTTP statistics */ return 1; } /* Sets the TOS header in IPv4 and the traffic class header in IPv6 packets * (as per RFC3260 #4 and BCP37 #4.2 and #5.2). */ static inline void inet_set_tos(int fd, struct sockaddr_storage from, int tos) { #ifdef IP_TOS if (from.ss_family == AF_INET) setsockopt(fd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos)); #endif #ifdef IPV6_TCLASS if (from.ss_family == AF_INET6) { if (IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&from)->sin6_addr)) /* v4-mapped addresses need IP_TOS */ setsockopt(fd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos)); else setsockopt(fd, IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof(tos)); } #endif } /* Returns the number of characters written to destination, * -1 on internal error and -2 if no replacement took place. */ static int http_replace_header(struct my_regex *re, char *dst, uint dst_size, char *val, int len, const char *rep_str) { if (!regex_exec_match2(re, val, len, MAX_MATCH, pmatch)) return -2; return exp_replace(dst, dst_size, val, rep_str, pmatch); } /* Returns the number of characters written to destination, * -1 on internal error and -2 if no replacement took place. */ static int http_replace_value(struct my_regex *re, char *dst, uint dst_size, char *val, int len, char delim, const char *rep_str) { char* p = val; char* dst_end = dst + dst_size; char* dst_p = dst; for (;;) { char *p_delim; /* look for delim. */ p_delim = p; while (p_delim < p + len && *p_delim != delim) p_delim++; if (regex_exec_match2(re, p, p_delim-p, MAX_MATCH, pmatch)) { int replace_n = exp_replace(dst_p, dst_end - dst_p, p, rep_str, pmatch); if (replace_n < 0) return -1; dst_p += replace_n; } else { uint len = p_delim - p; if (dst_p + len >= dst_end) return -1; memcpy(dst_p, p, len); dst_p += len; } if (dst_p >= dst_end) return -1; /* end of the replacements. */ if (p_delim >= p + len) break; /* Next part. */ *dst_p++ = delim; p = p_delim + 1; } return dst_p - dst; } static int http_transform_header(struct session* s, struct http_msg *msg, const char* name, uint name_len, char* buf, struct hdr_idx* idx, struct list *fmt, struct my_regex *re, struct hdr_ctx* ctx, int action) { ctx->idx = 0; while (http_find_full_header2(name, name_len, buf, idx, ctx)) { struct hdr_idx_elem *hdr = idx->v + ctx->idx; int delta; char* val = (char*)ctx->line + name_len + 2; char* val_end = (char*)ctx->line + hdr->len; char* reg_dst_buf; uint reg_dst_buf_size; int n_replaced; trash.len = build_logline(s, trash.str, trash.size, fmt); if (trash.len >= trash.size - 1) return -1; reg_dst_buf = trash.str + trash.len + 1; reg_dst_buf_size = trash.size - trash.len - 1; switch (action) { case HTTP_REQ_ACT_REPLACE_VAL: case HTTP_RES_ACT_REPLACE_VAL: n_replaced = http_replace_value(re, reg_dst_buf, reg_dst_buf_size, val, val_end-val, ',', trash.str); break; case HTTP_REQ_ACT_REPLACE_HDR: case HTTP_RES_ACT_REPLACE_HDR: n_replaced = http_replace_header(re, reg_dst_buf, reg_dst_buf_size, val, val_end-val, trash.str); break; default: /* impossible */ return -1; } switch (n_replaced) { case -1: return -1; case -2: continue; } delta = buffer_replace2(msg->chn->buf, val, val_end, reg_dst_buf, n_replaced); hdr->len += delta; http_msg_move_end(msg, delta); } return 0; } /* Executes the http-request rules <rules> for session <s>, proxy <px> and * transaction <txn>. Returns the verdict of the first rule that prevents * further processing of the request (auth, deny, ...), and defaults to * HTTP_RULE_RES_STOP if it executed all rules or stopped on an allow, or * HTTP_RULE_RES_CONT if the last rule was reached. It may set the TX_CLTARPIT * on txn->flags if it encounters a tarpit rule. */ enum rule_result http_req_get_intercept_rule(struct proxy *px, struct list *rules, struct session *s, struct http_txn *txn) { struct connection *cli_conn; struct http_req_rule *rule; struct hdr_ctx ctx; const char *auth_realm; list_for_each_entry(rule, rules, list) { if (rule->action >= HTTP_REQ_ACT_MAX) continue; /* check optional condition */ if (rule->cond) { int ret; ret = acl_exec_cond(rule->cond, px, s, txn, SMP_OPT_DIR_REQ|SMP_OPT_FINAL); ret = acl_pass(ret); if (rule->cond->pol == ACL_COND_UNLESS) ret = !ret; if (!ret) /* condition not matched */ continue; } switch (rule->action) { case HTTP_REQ_ACT_ALLOW: return HTTP_RULE_RES_STOP; case HTTP_REQ_ACT_DENY: return HTTP_RULE_RES_DENY; case HTTP_REQ_ACT_TARPIT: txn->flags |= TX_CLTARPIT; return HTTP_RULE_RES_DENY; case HTTP_REQ_ACT_AUTH: /* Auth might be performed on regular http-req rules as well as on stats */ auth_realm = rule->arg.auth.realm; if (!auth_realm) { if (px->uri_auth && rules == &px->uri_auth->http_req_rules) auth_realm = STATS_DEFAULT_REALM; else auth_realm = px->id; } /* send 401/407 depending on whether we use a proxy or not. We still * count one error, because normal browsing won't significantly * increase the counter but brute force attempts will. */ chunk_printf(&trash, (txn->flags & TX_USE_PX_CONN) ? HTTP_407_fmt : HTTP_401_fmt, auth_realm); txn->status = (txn->flags & TX_USE_PX_CONN) ? 407 : 401; stream_int_retnclose(&s->si[0], &trash); session_inc_http_err_ctr(s); return HTTP_RULE_RES_ABRT; case HTTP_REQ_ACT_REDIR: if (!http_apply_redirect_rule(rule->arg.redir, s, txn)) return HTTP_RULE_RES_BADREQ; return HTTP_RULE_RES_DONE; case HTTP_REQ_ACT_SET_NICE: s->task->nice = rule->arg.nice; break; case HTTP_REQ_ACT_SET_TOS: if ((cli_conn = objt_conn(s->req->prod->end)) && conn_ctrl_ready(cli_conn)) inet_set_tos(cli_conn->t.sock.fd, cli_conn->addr.from, rule->arg.tos); break; case HTTP_REQ_ACT_SET_MARK: #ifdef SO_MARK if ((cli_conn = objt_conn(s->req->prod->end)) && conn_ctrl_ready(cli_conn)) setsockopt(cli_conn->t.sock.fd, SOL_SOCKET, SO_MARK, &rule->arg.mark, sizeof(rule->arg.mark)); #endif break; case HTTP_REQ_ACT_SET_LOGL: s->logs.level = rule->arg.loglevel; break; case HTTP_REQ_ACT_REPLACE_HDR: case HTTP_REQ_ACT_REPLACE_VAL: if (http_transform_header(s, &txn->req, rule->arg.hdr_add.name, rule->arg.hdr_add.name_len, txn->req.chn->buf->p, &txn->hdr_idx, &rule->arg.hdr_add.fmt, &rule->arg.hdr_add.re, &ctx, rule->action)) return HTTP_RULE_RES_BADREQ; break; case HTTP_REQ_ACT_DEL_HDR: case HTTP_REQ_ACT_SET_HDR: ctx.idx = 0; /* remove all occurrences of the header */ while (http_find_header2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len, txn->req.chn->buf->p, &txn->hdr_idx, &ctx)) { http_remove_header2(&txn->req, &txn->hdr_idx, &ctx); } if (rule->action == HTTP_REQ_ACT_DEL_HDR) break; /* now fall through to header addition */ case HTTP_REQ_ACT_ADD_HDR: chunk_printf(&trash, "%s: ", rule->arg.hdr_add.name); memcpy(trash.str, rule->arg.hdr_add.name, rule->arg.hdr_add.name_len); trash.len = rule->arg.hdr_add.name_len; trash.str[trash.len++] = ':'; trash.str[trash.len++] = ' '; trash.len += build_logline(s, trash.str + trash.len, trash.size - trash.len, &rule->arg.hdr_add.fmt); http_header_add_tail2(&txn->req, &txn->hdr_idx, trash.str, trash.len); break; case HTTP_REQ_ACT_DEL_ACL: case HTTP_REQ_ACT_DEL_MAP: { struct pat_ref *ref; char *key; int len; /* collect reference */ ref = pat_ref_lookup(rule->arg.map.ref); if (!ref) continue; /* collect key */ len = build_logline(s, trash.str, trash.size, &rule->arg.map.key); key = trash.str; key[len] = '\0'; /* perform update */ /* returned code: 1=ok, 0=ko */ pat_ref_delete(ref, key); break; } case HTTP_REQ_ACT_ADD_ACL: { struct pat_ref *ref; char *key; struct chunk *trash_key; int len; trash_key = get_trash_chunk(); /* collect reference */ ref = pat_ref_lookup(rule->arg.map.ref); if (!ref) continue; /* collect key */ len = build_logline(s, trash_key->str, trash_key->size, &rule->arg.map.key); key = trash_key->str; key[len] = '\0'; /* perform update */ /* add entry only if it does not already exist */ if (pat_ref_find_elt(ref, key) == NULL) pat_ref_add(ref, key, NULL, NULL); break; } case HTTP_REQ_ACT_SET_MAP: { struct pat_ref *ref; char *key, *value; struct chunk *trash_key, *trash_value; int len; trash_key = get_trash_chunk(); trash_value = get_trash_chunk(); /* collect reference */ ref = pat_ref_lookup(rule->arg.map.ref); if (!ref) continue; /* collect key */ len = build_logline(s, trash_key->str, trash_key->size, &rule->arg.map.key); key = trash_key->str; key[len] = '\0'; /* collect value */ len = build_logline(s, trash_value->str, trash_value->size, &rule->arg.map.value); value = trash_value->str; value[len] = '\0'; /* perform update */ if (pat_ref_find_elt(ref, key) != NULL) /* update entry if it exists */ pat_ref_set(ref, key, value, NULL); else /* insert a new entry */ pat_ref_add(ref, key, value, NULL); break; } case HTTP_REQ_ACT_CUSTOM_CONT: rule->action_ptr(rule, px, s, txn); break; case HTTP_REQ_ACT_CUSTOM_STOP: rule->action_ptr(rule, px, s, txn); return HTTP_RULE_RES_DONE; } } /* we reached the end of the rules, nothing to report */ return HTTP_RULE_RES_CONT; } /* Executes the http-response rules <rules> for session <s>, proxy <px> and * transaction <txn>. Returns the first rule that prevents further processing * of the response (deny, ...) or NULL if it executed all rules or stopped * on an allow. It may set the TX_SVDENY on txn->flags if it encounters a deny * rule. */ static struct http_res_rule * http_res_get_intercept_rule(struct proxy *px, struct list *rules, struct session *s, struct http_txn *txn) { struct connection *cli_conn; struct http_res_rule *rule; struct hdr_ctx ctx; list_for_each_entry(rule, rules, list) { if (rule->action >= HTTP_RES_ACT_MAX) continue; /* check optional condition */ if (rule->cond) { int ret; ret = acl_exec_cond(rule->cond, px, s, txn, SMP_OPT_DIR_RES|SMP_OPT_FINAL); ret = acl_pass(ret); if (rule->cond->pol == ACL_COND_UNLESS) ret = !ret; if (!ret) /* condition not matched */ continue; } switch (rule->action) { case HTTP_RES_ACT_ALLOW: return NULL; /* "allow" rules are OK */ case HTTP_RES_ACT_DENY: txn->flags |= TX_SVDENY; return rule; case HTTP_RES_ACT_SET_NICE: s->task->nice = rule->arg.nice; break; case HTTP_RES_ACT_SET_TOS: if ((cli_conn = objt_conn(s->req->prod->end)) && conn_ctrl_ready(cli_conn)) inet_set_tos(cli_conn->t.sock.fd, cli_conn->addr.from, rule->arg.tos); break; case HTTP_RES_ACT_SET_MARK: #ifdef SO_MARK if ((cli_conn = objt_conn(s->req->prod->end)) && conn_ctrl_ready(cli_conn)) setsockopt(cli_conn->t.sock.fd, SOL_SOCKET, SO_MARK, &rule->arg.mark, sizeof(rule->arg.mark)); #endif break; case HTTP_RES_ACT_SET_LOGL: s->logs.level = rule->arg.loglevel; break; case HTTP_RES_ACT_REPLACE_HDR: case HTTP_RES_ACT_REPLACE_VAL: if (http_transform_header(s, &txn->rsp, rule->arg.hdr_add.name, rule->arg.hdr_add.name_len, txn->rsp.chn->buf->p, &txn->hdr_idx, &rule->arg.hdr_add.fmt, &rule->arg.hdr_add.re, &ctx, rule->action)) return NULL; /* note: we should report an error here */ break; case HTTP_RES_ACT_DEL_HDR: case HTTP_RES_ACT_SET_HDR: ctx.idx = 0; /* remove all occurrences of the header */ while (http_find_header2(rule->arg.hdr_add.name, rule->arg.hdr_add.name_len, txn->rsp.chn->buf->p, &txn->hdr_idx, &ctx)) { http_remove_header2(&txn->rsp, &txn->hdr_idx, &ctx); } if (rule->action == HTTP_RES_ACT_DEL_HDR) break; /* now fall through to header addition */ case HTTP_RES_ACT_ADD_HDR: chunk_printf(&trash, "%s: ", rule->arg.hdr_add.name); memcpy(trash.str, rule->arg.hdr_add.name, rule->arg.hdr_add.name_len); trash.len = rule->arg.hdr_add.name_len; trash.str[trash.len++] = ':'; trash.str[trash.len++] = ' '; trash.len += build_logline(s, trash.str + trash.len, trash.size - trash.len, &rule->arg.hdr_add.fmt); http_header_add_tail2(&txn->rsp, &txn->hdr_idx, trash.str, trash.len); break; case HTTP_RES_ACT_DEL_ACL: case HTTP_RES_ACT_DEL_MAP: { struct pat_ref *ref; char *key; int len; /* collect reference */ ref = pat_ref_lookup(rule->arg.map.ref); if (!ref) continue; /* collect key */ len = build_logline(s, trash.str, trash.size, &rule->arg.map.key); key = trash.str; key[len] = '\0'; /* perform update */ /* returned code: 1=ok, 0=ko */ pat_ref_delete(ref, key); break; } case HTTP_RES_ACT_ADD_ACL: { struct pat_ref *ref; char *key; struct chunk *trash_key; int len; trash_key = get_trash_chunk(); /* collect reference */ ref = pat_ref_lookup(rule->arg.map.ref); if (!ref) continue; /* collect key */ len = build_logline(s, trash_key->str, trash_key->size, &rule->arg.map.key); key = trash_key->str; key[len] = '\0'; /* perform update */ /* check if the entry already exists */ if (pat_ref_find_elt(ref, key) == NULL) pat_ref_add(ref, key, NULL, NULL); break; } case HTTP_RES_ACT_SET_MAP: { struct pat_ref *ref; char *key, *value; struct chunk *trash_key, *trash_value; int len; trash_key = get_trash_chunk(); trash_value = get_trash_chunk(); /* collect reference */ ref = pat_ref_lookup(rule->arg.map.ref); if (!ref) continue; /* collect key */ len = build_logline(s, trash_key->str, trash_key->size, &rule->arg.map.key); key = trash_key->str; key[len] = '\0'; /* collect value */ len = build_logline(s, trash_value->str, trash_value->size, &rule->arg.map.value); value = trash_value->str; value[len] = '\0'; /* perform update */ if (pat_ref_find_elt(ref, key) != NULL) /* update entry if it exists */ pat_ref_set(ref, key, value, NULL); else /* insert a new entry */ pat_ref_add(ref, key, value, NULL); break; } case HTTP_RES_ACT_CUSTOM_CONT: rule->action_ptr(rule, px, s, txn); break; case HTTP_RES_ACT_CUSTOM_STOP: rule->action_ptr(rule, px, s, txn); return rule; } } /* we reached the end of the rules, nothing to report */ return NULL; } /* Perform an HTTP redirect based on the information in <rule>. The function * returns non-zero on success, or zero in case of a, irrecoverable error such * as too large a request to build a valid response. */ static int http_apply_redirect_rule(struct redirect_rule *rule, struct session *s, struct http_txn *txn) { struct http_msg *msg = &txn->req; const char *msg_fmt; const char *location; /* build redirect message */ switch(rule->code) { case 308: msg_fmt = HTTP_308; break; case 307: msg_fmt = HTTP_307; break; case 303: msg_fmt = HTTP_303; break; case 301: msg_fmt = HTTP_301; break; case 302: default: msg_fmt = HTTP_302; break; } if (unlikely(!chunk_strcpy(&trash, msg_fmt))) return 0; location = trash.str + trash.len; switch(rule->type) { case REDIRECT_TYPE_SCHEME: { const char *path; const char *host; struct hdr_ctx ctx; int pathlen; int hostlen; host = ""; hostlen = 0; ctx.idx = 0; if (http_find_header2("Host", 4, txn->req.chn->buf->p, &txn->hdr_idx, &ctx)) { host = ctx.line + ctx.val; hostlen = ctx.vlen; } path = http_get_path(txn); /* build message using path */ if (path) { pathlen = txn->req.sl.rq.u_l + (txn->req.chn->buf->p + txn->req.sl.rq.u) - path; if (rule->flags & REDIRECT_FLAG_DROP_QS) { int qs = 0; while (qs < pathlen) { if (path[qs] == '?') { pathlen = qs; break; } qs++; } } } else { path = "/"; pathlen = 1; } if (rule->rdr_str) { /* this is an old "redirect" rule */ /* check if we can add scheme + "://" + host + path */ if (trash.len + rule->rdr_len + 3 + hostlen + pathlen > trash.size - 4) return 0; /* add scheme */ memcpy(trash.str + trash.len, rule->rdr_str, rule->rdr_len); trash.len += rule->rdr_len; } else { /* add scheme with executing log format */ trash.len += build_logline(s, trash.str + trash.len, trash.size - trash.len, &rule->rdr_fmt); /* check if we can add scheme + "://" + host + path */ if (trash.len + 3 + hostlen + pathlen > trash.size - 4) return 0; } /* add "://" */ memcpy(trash.str + trash.len, "://", 3); trash.len += 3; /* add host */ memcpy(trash.str + trash.len, host, hostlen); trash.len += hostlen; /* add path */ memcpy(trash.str + trash.len, path, pathlen); trash.len += pathlen; /* append a slash at the end of the location if needed and missing */ if (trash.len && trash.str[trash.len - 1] != '/' && (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) { if (trash.len > trash.size - 5) return 0; trash.str[trash.len] = '/'; trash.len++; } break; } case REDIRECT_TYPE_PREFIX: { const char *path; int pathlen; path = http_get_path(txn); /* build message using path */ if (path) { pathlen = txn->req.sl.rq.u_l + (txn->req.chn->buf->p + txn->req.sl.rq.u) - path; if (rule->flags & REDIRECT_FLAG_DROP_QS) { int qs = 0; while (qs < pathlen) { if (path[qs] == '?') { pathlen = qs; break; } qs++; } } } else { path = "/"; pathlen = 1; } if (rule->rdr_str) { /* this is an old "redirect" rule */ if (trash.len + rule->rdr_len + pathlen > trash.size - 4) return 0; /* add prefix. Note that if prefix == "/", we don't want to * add anything, otherwise it makes it hard for the user to * configure a self-redirection. */ if (rule->rdr_len != 1 || *rule->rdr_str != '/') { memcpy(trash.str + trash.len, rule->rdr_str, rule->rdr_len); trash.len += rule->rdr_len; } } else { /* add prefix with executing log format */ trash.len += build_logline(s, trash.str + trash.len, trash.size - trash.len, &rule->rdr_fmt); /* Check length */ if (trash.len + pathlen > trash.size - 4) return 0; } /* add path */ memcpy(trash.str + trash.len, path, pathlen); trash.len += pathlen; /* append a slash at the end of the location if needed and missing */ if (trash.len && trash.str[trash.len - 1] != '/' && (rule->flags & REDIRECT_FLAG_APPEND_SLASH)) { if (trash.len > trash.size - 5) return 0; trash.str[trash.len] = '/'; trash.len++; } break; } case REDIRECT_TYPE_LOCATION: default: if (rule->rdr_str) { /* this is an old "redirect" rule */ if (trash.len + rule->rdr_len > trash.size - 4) return 0; /* add location */ memcpy(trash.str + trash.len, rule->rdr_str, rule->rdr_len); trash.len += rule->rdr_len; } else { /* add location with executing log format */ trash.len += build_logline(s, trash.str + trash.len, trash.size - trash.len, &rule->rdr_fmt); /* Check left length */ if (trash.len > trash.size - 4) return 0; } break; } if (rule->cookie_len) { memcpy(trash.str + trash.len, "\r\nSet-Cookie: ", 14); trash.len += 14; memcpy(trash.str + trash.len, rule->cookie_str, rule->cookie_len); trash.len += rule->cookie_len; memcpy(trash.str + trash.len, "\r\n", 2); trash.len += 2; } /* add end of headers and the keep-alive/close status. * We may choose to set keep-alive if the Location begins * with a slash, because the client will come back to the * same server. */ txn->status = rule->code; /* let's log the request time */ s->logs.tv_request = now; if (*location == '/' && (msg->flags & HTTP_MSGF_XFER_LEN) && !(msg->flags & HTTP_MSGF_TE_CHNK) && !txn->req.body_len && ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_SCL || (txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)) { /* keep-alive possible */ if (!(msg->flags & HTTP_MSGF_VER_11)) { if (unlikely(txn->flags & TX_USE_PX_CONN)) { memcpy(trash.str + trash.len, "\r\nProxy-Connection: keep-alive", 30); trash.len += 30; } else { memcpy(trash.str + trash.len, "\r\nConnection: keep-alive", 24); trash.len += 24; } } memcpy(trash.str + trash.len, "\r\n\r\n", 4); trash.len += 4; bo_inject(txn->rsp.chn, trash.str, trash.len); /* "eat" the request */ bi_fast_delete(txn->req.chn->buf, msg->sov); msg->next -= msg->sov; msg->sov = 0; txn->req.chn->analysers = AN_REQ_HTTP_XFER_BODY; s->rep->analysers = AN_RES_HTTP_XFER_BODY; txn->req.msg_state = HTTP_MSG_CLOSED; txn->rsp.msg_state = HTTP_MSG_DONE; } else { /* keep-alive not possible */ if (unlikely(txn->flags & TX_USE_PX_CONN)) { memcpy(trash.str + trash.len, "\r\nProxy-Connection: close\r\n\r\n", 29); trash.len += 29; } else { memcpy(trash.str + trash.len, "\r\nConnection: close\r\n\r\n", 23); trash.len += 23; } stream_int_retnclose(txn->req.chn->prod, &trash); txn->req.chn->analysers = 0; } if (!(s->flags & SN_ERR_MASK)) s->flags |= SN_ERR_LOCAL; if (!(s->flags & SN_FINST_MASK)) s->flags |= SN_FINST_R; return 1; } /* This stream analyser runs all HTTP request processing which is common to * frontends and backends, which means blocking ACLs, filters, connection-close, * reqadd, stats and redirects. This is performed for the designated proxy. * It returns 1 if the processing can continue on next analysers, or zero if it * either needs more data or wants to immediately abort the request (eg: deny, * error, ...). */ int http_process_req_common(struct session *s, struct channel *req, int an_bit, struct proxy *px) { struct http_txn *txn = &s->txn; struct http_msg *msg = &txn->req; struct redirect_rule *rule; struct cond_wordlist *wl; enum rule_result verdict; if (unlikely(msg->msg_state < HTTP_MSG_BODY)) { /* we need more data */ channel_dont_connect(req); return 0; } DPRINTF(stderr,"[%u] %s: session=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%d analysers=%02x\n", now_ms, __FUNCTION__, s, req, req->rex, req->wex, req->flags, req->buf->i, req->analysers); /* just in case we have some per-backend tracking */ session_inc_be_http_req_ctr(s); /* evaluate http-request rules */ if (!LIST_ISEMPTY(&px->http_req_rules)) { verdict = http_req_get_intercept_rule(px, &px->http_req_rules, s, txn); switch (verdict) { case HTTP_RULE_RES_CONT: case HTTP_RULE_RES_STOP: /* nothing to do */ break; case HTTP_RULE_RES_DENY: /* deny or tarpit */ if (txn->flags & TX_CLTARPIT) goto tarpit; goto deny; case HTTP_RULE_RES_ABRT: /* abort request, response already sent. Eg: auth */ goto return_prx_cond; case HTTP_RULE_RES_DONE: /* OK, but terminate request processing (eg: redirect) */ goto done; case HTTP_RULE_RES_BADREQ: /* failed with a bad request */ goto return_bad_req; } } /* OK at this stage, we know that the request was accepted according to * the http-request rules, we can check for the stats. Note that the * URI is detected *before* the req* rules in order not to be affected * by a possible reqrep, while they are processed *after* so that a * reqdeny can still block them. This clearly needs to change in 1.6! */ if (stats_check_uri(s->rep->prod, txn, px)) { s->target = &http_stats_applet.obj_type; if (unlikely(!stream_int_register_handler(s->rep->prod, objt_applet(s->target)))) { txn->status = 500; s->logs.tv_request = now; stream_int_retnclose(req->prod, http_error_message(s, HTTP_ERR_500)); if (!(s->flags & SN_ERR_MASK)) s->flags |= SN_ERR_RESOURCE; goto return_prx_cond; } /* parse the whole stats request and extract the relevant information */ http_handle_stats(s, req); verdict = http_req_get_intercept_rule(px, &px->uri_auth->http_req_rules, s, txn); /* not all actions implemented: deny, allow, auth */ if (verdict == HTTP_RULE_RES_DENY) /* stats http-request deny */ goto deny; if (verdict == HTTP_RULE_RES_ABRT) /* stats auth / stats http-request auth */ goto return_prx_cond; } /* evaluate the req* rules except reqadd */ if (px->req_exp != NULL) { if (apply_filters_to_request(s, req, px) < 0) goto return_bad_req; if (txn->flags & TX_CLDENY) goto deny; if (txn->flags & TX_CLTARPIT) goto tarpit; } /* add request headers from the rule sets in the same order */ list_for_each_entry(wl, &px->req_add, list) { if (wl->cond) { int ret = acl_exec_cond(wl->cond, px, s, txn, SMP_OPT_DIR_REQ|SMP_OPT_FINAL); ret = acl_pass(ret); if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS) ret = !ret; if (!ret) continue; } if (unlikely(http_header_add_tail(&txn->req, &txn->hdr_idx, wl->s) < 0)) goto return_bad_req; } /* Proceed with the stats now. */ if (unlikely(objt_applet(s->target) == &http_stats_applet)) { /* process the stats request now */ if (s->fe == s->be) /* report it if the request was intercepted by the frontend */ s->fe->fe_counters.intercepted_req++; if (!(s->flags & SN_ERR_MASK)) // this is not really an error but it is s->flags |= SN_ERR_LOCAL; // to mark that it comes from the proxy if (!(s->flags & SN_FINST_MASK)) s->flags |= SN_FINST_R; /* we may want to compress the stats page */ if (s->fe->comp || s->be->comp) select_compression_request_header(s, req->buf); /* enable the minimally required analyzers to handle keep-alive and compression on the HTTP response */ req->analysers = (req->analysers & AN_REQ_HTTP_BODY) | AN_REQ_HTTP_XFER_BODY | AN_RES_WAIT_HTTP | AN_RES_HTTP_PROCESS_BE | AN_RES_HTTP_XFER_BODY; goto done; } /* check whether we have some ACLs set to redirect this request */ list_for_each_entry(rule, &px->redirect_rules, list) { if (rule->cond) { int ret; ret = acl_exec_cond(rule->cond, px, s, txn, SMP_OPT_DIR_REQ|SMP_OPT_FINAL); ret = acl_pass(ret); if (rule->cond->pol == ACL_COND_UNLESS) ret = !ret; if (!ret) continue; } if (!http_apply_redirect_rule(rule, s, txn)) goto return_bad_req; goto done; } /* POST requests may be accompanied with an "Expect: 100-Continue" header. * If this happens, then the data will not come immediately, so we must * send all what we have without waiting. Note that due to the small gain * in waiting for the body of the request, it's easier to simply put the * CF_SEND_DONTWAIT flag any time. It's a one-shot flag so it will remove * itself once used. */ req->flags |= CF_SEND_DONTWAIT; done: /* done with this analyser, continue with next ones that the calling * points will have set, if any. */ req->analyse_exp = TICK_ETERNITY; done_without_exp: /* done with this analyser, but dont reset the analyse_exp. */ req->analysers &= ~an_bit; return 1; tarpit: /* When a connection is tarpitted, we use the tarpit timeout, * which may be the same as the connect timeout if unspecified. * If unset, then set it to zero because we really want it to * eventually expire. We build the tarpit as an analyser. */ channel_erase(s->req); /* wipe the request out so that we can drop the connection early * if the client closes first. */ channel_dont_connect(req); req->analysers = 0; /* remove switching rules etc... */ req->analysers |= AN_REQ_HTTP_TARPIT; req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.tarpit); if (!req->analyse_exp) req->analyse_exp = tick_add(now_ms, 0); session_inc_http_err_ctr(s); s->fe->fe_counters.denied_req++; if (s->fe != s->be) s->be->be_counters.denied_req++; if (s->listener->counters) s->listener->counters->denied_req++; goto done_without_exp; deny: /* this request was blocked (denied) */ txn->flags |= TX_CLDENY; txn->status = 403; s->logs.tv_request = now; stream_int_retnclose(req->prod, http_error_message(s, HTTP_ERR_403)); session_inc_http_err_ctr(s); s->fe->fe_counters.denied_req++; if (s->fe != s->be) s->be->be_counters.denied_req++; if (s->listener->counters) s->listener->counters->denied_req++; goto return_prx_cond; return_bad_req: /* We centralize bad requests processing here */ if (unlikely(msg->msg_state == HTTP_MSG_ERROR) || msg->err_pos >= 0) { /* we detected a parsing error. We want to archive this request * in the dedicated proxy area for later troubleshooting. */ http_capture_bad_message(&s->fe->invalid_req, s, msg, msg->msg_state, s->fe); } txn->req.msg_state = HTTP_MSG_ERROR; txn->status = 400; stream_int_retnclose(req->prod, http_error_message(s, HTTP_ERR_400)); s->fe->fe_counters.failed_req++; if (s->listener->counters) s->listener->counters->failed_req++; return_prx_cond: if (!(s->flags & SN_ERR_MASK)) s->flags |= SN_ERR_PRXCOND; if (!(s->flags & SN_FINST_MASK)) s->flags |= SN_FINST_R; req->analysers = 0; req->analyse_exp = TICK_ETERNITY; return 0; } /* This function performs all the processing enabled for the current request. * It returns 1 if the processing can continue on next analysers, or zero if it * needs more data, encounters an error, or wants to immediately abort the * request. It relies on buffers flags, and updates s->req->analysers. */ int http_process_request(struct session *s, struct channel *req, int an_bit) { struct http_txn *txn = &s->txn; struct http_msg *msg = &txn->req; struct connection *cli_conn = objt_conn(req->prod->end); if (unlikely(msg->msg_state < HTTP_MSG_BODY)) { /* we need more data */ channel_dont_connect(req); return 0; } DPRINTF(stderr,"[%u] %s: session=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%d analysers=%02x\n", now_ms, __FUNCTION__, s, req, req->rex, req->wex, req->flags, req->buf->i, req->analysers); if (s->fe->comp || s->be->comp) select_compression_request_header(s, req->buf); /* * Right now, we know that we have processed the entire headers * and that unwanted requests have been filtered out. We can do * whatever we want with the remaining request. Also, now we * may have separate values for ->fe, ->be. */ /* * If HTTP PROXY is set we simply get remote server address parsing * incoming request. Note that this requires that a connection is * allocated on the server side. */ if ((s->be->options & PR_O_HTTP_PROXY) && !(s->flags & SN_ADDR_SET)) { struct connection *conn; char *path; /* Note that for now we don't reuse existing proxy connections */ if (unlikely((conn = si_alloc_conn(req->cons, 0)) == NULL)) { txn->req.msg_state = HTTP_MSG_ERROR; txn->status = 500; req->analysers = 0; stream_int_retnclose(req->prod, http_error_message(s, HTTP_ERR_500)); if (!(s->flags & SN_ERR_MASK)) s->flags |= SN_ERR_RESOURCE; if (!(s->flags & SN_FINST_MASK)) s->flags |= SN_FINST_R; return 0; } path = http_get_path(txn); url2sa(req->buf->p + msg->sl.rq.u, path ? path - (req->buf->p + msg->sl.rq.u) : msg->sl.rq.u_l, &conn->addr.to, NULL); /* if the path was found, we have to remove everything between * req->buf->p + msg->sl.rq.u and path (excluded). If it was not * found, we need to replace from req->buf->p + msg->sl.rq.u for * u_l characters by a single "/". */ if (path) { char *cur_ptr = req->buf->p; char *cur_end = cur_ptr + txn->req.sl.rq.l; int delta; delta = buffer_replace2(req->buf, req->buf->p + msg->sl.rq.u, path, NULL, 0); http_msg_move_end(&txn->req, delta); cur_end += delta; if (http_parse_reqline(&txn->req, HTTP_MSG_RQMETH, cur_ptr, cur_end + 1, NULL, NULL) == NULL) goto return_bad_req; } else { char *cur_ptr = req->buf->p; char *cur_end = cur_ptr + txn->req.sl.rq.l; int delta; delta = buffer_replace2(req->buf, req->buf->p + msg->sl.rq.u, req->buf->p + msg->sl.rq.u + msg->sl.rq.u_l, "/", 1); http_msg_move_end(&txn->req, delta); cur_end += delta; if (http_parse_reqline(&txn->req, HTTP_MSG_RQMETH, cur_ptr, cur_end + 1, NULL, NULL) == NULL) goto return_bad_req; } } /* * 7: Now we can work with the cookies. * Note that doing so might move headers in the request, but * the fields will stay coherent and the URI will not move. * This should only be performed in the backend. */ if ((s->be->cookie_name || s->be->appsession_name || s->fe->capture_name) && !(txn->flags & (TX_CLDENY|TX_CLTARPIT))) manage_client_side_cookies(s, req); /* * 8: the appsession cookie was looked up very early in 1.2, * so let's do the same now. */ /* It needs to look into the URI unless persistence must be ignored */ if ((txn->sessid == NULL) && s->be->appsession_name && !(s->flags & SN_IGNORE_PRST)) { get_srv_from_appsession(s, req->buf->p + msg->sl.rq.u, msg->sl.rq.u_l); } /* add unique-id if "header-unique-id" is specified */ if (!LIST_ISEMPTY(&s->fe->format_unique_id)) { if ((s->unique_id = pool_alloc2(pool2_uniqueid)) == NULL) goto return_bad_req; s->unique_id[0] = '\0'; build_logline(s, s->unique_id, UNIQUEID_LEN, &s->fe->format_unique_id); } if (s->fe->header_unique_id && s->unique_id) { chunk_printf(&trash, "%s: %s", s->fe->header_unique_id, s->unique_id); if (trash.len < 0) goto return_bad_req; if (unlikely(http_header_add_tail2(&txn->req, &txn->hdr_idx, trash.str, trash.len) < 0)) goto return_bad_req; } /* * 9: add X-Forwarded-For if either the frontend or the backend * asks for it. */ if ((s->fe->options | s->be->options) & PR_O_FWDFOR) { struct hdr_ctx ctx = { .idx = 0 }; if (!((s->fe->options | s->be->options) & PR_O_FF_ALWAYS) && http_find_header2(s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_name : s->fe->fwdfor_hdr_name, s->be->fwdfor_hdr_len ? s->be->fwdfor_hdr_len : s->fe->fwdfor_hdr_len, req->buf->p, &txn->hdr_idx, &ctx)) { /* The header is set to be added only if none is present * and we found it, so don't do anything. */ } else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) { /* Add an X-Forwarded-For header unless the source IP is * in the 'except' network range. */ if ((!s->fe->except_mask.s_addr || (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & s->fe->except_mask.s_addr) != s->fe->except_net.s_addr) && (!s->be->except_mask.s_addr || (((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr.s_addr & s->be->except_mask.s_addr) != s->be->except_net.s_addr)) { int len; unsigned char *pn; pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr; /* Note: we rely on the backend to get the header name to be used for * x-forwarded-for, because the header is really meant for the backends. * However, if the backend did not specify any option, we have to rely * on the frontend's header name. */ if (s->be->fwdfor_hdr_len) { len = s->be->fwdfor_hdr_len; memcpy(trash.str, s->be->fwdfor_hdr_name, len); } else { len = s->fe->fwdfor_hdr_len; memcpy(trash.str, s->fe->fwdfor_hdr_name, len); } len += snprintf(trash.str + len, trash.size - len, ": %d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]); if (unlikely(http_header_add_tail2(&txn->req, &txn->hdr_idx, trash.str, len) < 0)) goto return_bad_req; } } else if (cli_conn && cli_conn->addr.from.ss_family == AF_INET6) { /* FIXME: for the sake of completeness, we should also support * 'except' here, although it is mostly useless in this case. */ int len; char pn[INET6_ADDRSTRLEN]; inet_ntop(AF_INET6, (const void *)&((struct sockaddr_in6 *)(&cli_conn->addr.from))->sin6_addr, pn, sizeof(pn)); /* Note: we rely on the backend to get the header name to be used for * x-forwarded-for, because the header is really meant for the backends. * However, if the backend did not specify any option, we have to rely * on the frontend's header name. */ if (s->be->fwdfor_hdr_len) { len = s->be->fwdfor_hdr_len; memcpy(trash.str, s->be->fwdfor_hdr_name, len); } else { len = s->fe->fwdfor_hdr_len; memcpy(trash.str, s->fe->fwdfor_hdr_name, len); } len += snprintf(trash.str + len, trash.size - len, ": %s", pn); if (unlikely(http_header_add_tail2(&txn->req, &txn->hdr_idx, trash.str, len) < 0)) goto return_bad_req; } } /* * 10: add X-Original-To if either the frontend or the backend * asks for it. */ if ((s->fe->options | s->be->options) & PR_O_ORGTO) { /* FIXME: don't know if IPv6 can handle that case too. */ if (cli_conn && cli_conn->addr.from.ss_family == AF_INET) { /* Add an X-Original-To header unless the destination IP is * in the 'except' network range. */ conn_get_to_addr(cli_conn); if (cli_conn->addr.to.ss_family == AF_INET && ((!s->fe->except_mask_to.s_addr || (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & s->fe->except_mask_to.s_addr) != s->fe->except_to.s_addr) && (!s->be->except_mask_to.s_addr || (((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr.s_addr & s->be->except_mask_to.s_addr) != s->be->except_to.s_addr))) { int len; unsigned char *pn; pn = (unsigned char *)&((struct sockaddr_in *)&cli_conn->addr.to)->sin_addr; /* Note: we rely on the backend to get the header name to be used for * x-original-to, because the header is really meant for the backends. * However, if the backend did not specify any option, we have to rely * on the frontend's header name. */ if (s->be->orgto_hdr_len) { len = s->be->orgto_hdr_len; memcpy(trash.str, s->be->orgto_hdr_name, len); } else { len = s->fe->orgto_hdr_len; memcpy(trash.str, s->fe->orgto_hdr_name, len); } len += snprintf(trash.str + len, trash.size - len, ": %d.%d.%d.%d", pn[0], pn[1], pn[2], pn[3]); if (unlikely(http_header_add_tail2(&txn->req, &txn->hdr_idx, trash.str, len) < 0)) goto return_bad_req; } } } /* 11: add "Connection: close" or "Connection: keep-alive" if needed and not yet set. * If an "Upgrade" token is found, the header is left untouched in order not to have * to deal with some servers bugs : some of them fail an Upgrade if anything but * "Upgrade" is present in the Connection header. */ if (!(txn->flags & TX_HDR_CONN_UPG) && (((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN) || ((s->fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL || (s->be->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL))) { unsigned int want_flags = 0; if (msg->flags & HTTP_MSGF_VER_11) { if (((txn->flags & TX_CON_WANT_MSK) >= TX_CON_WANT_SCL || ((s->fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL || (s->be->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL)) && !((s->fe->options2|s->be->options2) & PR_O2_FAKE_KA)) want_flags |= TX_CON_CLO_SET; } else { if (((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL && ((s->fe->options & PR_O_HTTP_MODE) != PR_O_HTTP_PCL && (s->be->options & PR_O_HTTP_MODE) != PR_O_HTTP_PCL)) || ((s->fe->options2|s->be->options2) & PR_O2_FAKE_KA)) want_flags |= TX_CON_KAL_SET; } if (want_flags != (txn->flags & (TX_CON_CLO_SET|TX_CON_KAL_SET))) http_change_connection_header(txn, msg, want_flags); } /* If we have no server assigned yet and we're balancing on url_param * with a POST request, we may be interested in checking the body for * that parameter. This will be done in another analyser. */ if (!(s->flags & (SN_ASSIGNED|SN_DIRECT)) && s->txn.meth == HTTP_METH_POST && s->be->url_param_name != NULL && (msg->flags & (HTTP_MSGF_CNT_LEN|HTTP_MSGF_TE_CHNK))) { channel_dont_connect(req); req->analysers |= AN_REQ_HTTP_BODY; } if (msg->flags & HTTP_MSGF_XFER_LEN) { req->analysers |= AN_REQ_HTTP_XFER_BODY; #ifdef TCP_QUICKACK /* We expect some data from the client. Unless we know for sure * we already have a full request, we have to re-enable quick-ack * in case we previously disabled it, otherwise we might cause * the client to delay further data. */ if ((s->listener->options & LI_O_NOQUICKACK) && cli_conn && conn_ctrl_ready(cli_conn) && ((msg->flags & HTTP_MSGF_TE_CHNK) || (msg->body_len > req->buf->i - txn->req.eoh - 2))) setsockopt(cli_conn->t.sock.fd, IPPROTO_TCP, TCP_QUICKACK, &one, sizeof(one)); #endif } /************************************************************* * OK, that's finished for the headers. We have done what we * * could. Let's switch to the DATA state. * ************************************************************/ req->analyse_exp = TICK_ETERNITY; req->analysers &= ~an_bit; /* if the server closes the connection, we want to immediately react * and close the socket to save packets and syscalls. */ if (!(req->analysers & AN_REQ_HTTP_XFER_BODY)) req->cons->flags |= SI_FL_NOHALF; s->logs.tv_request = now; /* OK let's go on with the BODY now */ return 1; return_bad_req: /* let's centralize all bad requests */ if (unlikely(msg->msg_state == HTTP_MSG_ERROR) || msg->err_pos >= 0) { /* we detected a parsing error. We want to archive this request * in the dedicated proxy area for later troubleshooting. */ http_capture_bad_message(&s->fe->invalid_req, s, msg, msg->msg_state, s->fe); } txn->req.msg_state = HTTP_MSG_ERROR; txn->status = 400; req->analysers = 0; stream_int_retnclose(req->prod, http_error_message(s, HTTP_ERR_400)); s->fe->fe_counters.failed_req++; if (s->listener->counters) s->listener->counters->failed_req++; if (!(s->flags & SN_ERR_MASK)) s->flags |= SN_ERR_PRXCOND; if (!(s->flags & SN_FINST_MASK)) s->flags |= SN_FINST_R; return 0; } /* This function is an analyser which processes the HTTP tarpit. It always * returns zero, at the beginning because it prevents any other processing * from occurring, and at the end because it terminates the request. */ int http_process_tarpit(struct session *s, struct channel *req, int an_bit) { struct http_txn *txn = &s->txn; /* This connection is being tarpitted. The CLIENT side has * already set the connect expiration date to the right * timeout. We just have to check that the client is still * there and that the timeout has not expired. */ channel_dont_connect(req); if ((req->flags & (CF_SHUTR|CF_READ_ERROR)) == 0 && !tick_is_expired(req->analyse_exp, now_ms)) return 0; /* We will set the queue timer to the time spent, just for * logging purposes. We fake a 500 server error, so that the * attacker will not suspect his connection has been tarpitted. * It will not cause trouble to the logs because we can exclude * the tarpitted connections by filtering on the 'PT' status flags. */ s->logs.t_queue = tv_ms_elapsed(&s->logs.tv_accept, &now); txn->status = 500; if (!(req->flags & CF_READ_ERROR)) stream_int_retnclose(req->prod, http_error_message(s, HTTP_ERR_500)); req->analysers = 0; req->analyse_exp = TICK_ETERNITY; if (!(s->flags & SN_ERR_MASK)) s->flags |= SN_ERR_PRXCOND; if (!(s->flags & SN_FINST_MASK)) s->flags |= SN_FINST_T; return 0; } /* This function is an analyser which waits for the HTTP request body. It waits * for either the buffer to be full, or the full advertised contents to have * reached the buffer. It must only be called after the standard HTTP request * processing has occurred, because it expects the request to be parsed and will * look for the Expect header. It may send a 100-Continue interim response. It * takes in input any state starting from HTTP_MSG_BODY and leaves with one of * HTTP_MSG_CHK_SIZE, HTTP_MSG_DATA or HTTP_MSG_TRAILERS. It returns zero if it * needs to read more data, or 1 once it has completed its analysis. */ int http_wait_for_request_body(struct session *s, struct channel *req, int an_bit) { struct http_txn *txn = &s->txn; struct http_msg *msg = &s->txn.req; /* We have to parse the HTTP request body to find any required data. * "balance url_param check_post" should have been the only way to get * into this. We were brought here after HTTP header analysis, so all * related structures are ready. */ if (msg->msg_state < HTTP_MSG_CHUNK_SIZE) { /* This is the first call */ if (msg->msg_state < HTTP_MSG_BODY) goto missing_data; if (msg->msg_state < HTTP_MSG_100_SENT) { /* If we have HTTP/1.1 and Expect: 100-continue, then we must * send an HTTP/1.1 100 Continue intermediate response. */ if (msg->flags & HTTP_MSGF_VER_11) { struct hdr_ctx ctx; ctx.idx = 0; /* Expect is allowed in 1.1, look for it */ if (http_find_header2("Expect", 6, req->buf->p, &txn->hdr_idx, &ctx) && unlikely(ctx.vlen == 12 && strncasecmp(ctx.line+ctx.val, "100-continue", 12) == 0)) { bo_inject(s->rep, http_100_chunk.str, http_100_chunk.len); } } msg->msg_state = HTTP_MSG_100_SENT; } /* we have msg->sov which points to the first byte of message body. * req->buf->p still points to the beginning of the message. We * must save the body in msg->next because it survives buffer * re-alignments. */ msg->next = msg->sov; if (msg->flags & HTTP_MSGF_TE_CHNK) msg->msg_state = HTTP_MSG_CHUNK_SIZE; else msg->msg_state = HTTP_MSG_DATA; } if (!(msg->flags & HTTP_MSGF_TE_CHNK)) { /* We're in content-length mode, we just have to wait for enough data. */ if (req->buf->i - msg->sov < msg->body_len) goto missing_data; /* OK we have everything we need now */ goto http_end; } /* OK here we're parsing a chunked-encoded message */ if (msg->msg_state == HTTP_MSG_CHUNK_SIZE) { /* read the chunk size and assign it to ->chunk_len, then * set ->sov and ->next to point to the body and switch to DATA or * TRAILERS state. */ int ret = http_parse_chunk_size(msg); if (!ret) goto missing_data; else if (ret < 0) { session_inc_http_err_ctr(s); goto return_bad_req; } } /* Now we're in HTTP_MSG_DATA or HTTP_MSG_TRAILERS state. * We have the first data byte is in msg->sov. We're waiting for at * least a whole chunk or the whole content length bytes after msg->sov. */ if (msg->msg_state == HTTP_MSG_TRAILERS) goto http_end; if (req->buf->i - msg->sov >= msg->body_len) /* we have enough bytes now */ goto http_end; missing_data: /* we get here if we need to wait for more data. If the buffer is full, * we have the maximum we can expect. */ if (buffer_full(req->buf, global.tune.maxrewrite)) goto http_end; if ((req->flags & CF_READ_TIMEOUT) || tick_is_expired(req->analyse_exp, now_ms)) { txn->status = 408; stream_int_retnclose(req->prod, http_error_message(s, HTTP_ERR_408)); if (!(s->flags & SN_ERR_MASK)) s->flags |= SN_ERR_CLITO; if (!(s->flags & SN_FINST_MASK)) s->flags |= SN_FINST_D; goto return_err_msg; } /* we get here if we need to wait for more data */ if (!(req->flags & (CF_SHUTR | CF_READ_ERROR))) { /* Not enough data. We'll re-use the http-request * timeout here. Ideally, we should set the timeout * relative to the accept() date. We just set the * request timeout once at the beginning of the * request. */ channel_dont_connect(req); if (!tick_isset(req->analyse_exp)) req->analyse_exp = tick_add_ifset(now_ms, s->be->timeout.httpreq); return 0; } http_end: /* The situation will not evolve, so let's give up on the analysis. */ s->logs.tv_request = now; /* update the request timer to reflect full request */ req->analysers &= ~an_bit; req->analyse_exp = TICK_ETERNITY; return 1; return_bad_req: /* let's centralize all bad requests */ txn->req.msg_state = HTTP_MSG_ERROR; txn->status = 400; stream_int_retnclose(req->prod, http_error_message(s, HTTP_ERR_400)); if (!(s->flags & SN_ERR_MASK)) s->flags |= SN_ERR_PRXCOND; if (!(s->flags & SN_FINST_MASK)) s->flags |= SN_FINST_R; return_err_msg: req->analysers = 0; s->fe->fe_counters.failed_req++; if (s->listener->counters) s->listener->counters->failed_req++; return 0; } /* send a server's name with an outgoing request over an established connection. * Note: this function is designed to be called once the request has been scheduled * for being forwarded. This is the reason why it rewinds the buffer before * proceeding. */ int http_send_name_header(struct http_txn *txn, struct proxy* be, const char* srv_name) { struct hdr_ctx ctx; char *hdr_name = be->server_id_hdr_name; int hdr_name_len = be->server_id_hdr_len; struct channel *chn = txn->req.chn; char *hdr_val; unsigned int old_o, old_i; ctx.idx = 0; old_o = http_hdr_rewind(&txn->req); if (old_o) { /* The request was already skipped, let's restore it */ b_rew(chn->buf, old_o); txn->req.next += old_o; txn->req.sov += old_o; } old_i = chn->buf->i; while (http_find_header2(hdr_name, hdr_name_len, txn->req.chn->buf->p, &txn->hdr_idx, &ctx)) { /* remove any existing values from the header */ http_remove_header2(&txn->req, &txn->hdr_idx, &ctx); } /* Add the new header requested with the server value */ hdr_val = trash.str; memcpy(hdr_val, hdr_name, hdr_name_len); hdr_val += hdr_name_len; *hdr_val++ = ':'; *hdr_val++ = ' '; hdr_val += strlcpy2(hdr_val, srv_name, trash.str + trash.size - hdr_val); http_header_add_tail2(&txn->req, &txn->hdr_idx, trash.str, hdr_val - trash.str); if (old_o) { /* If this was a forwarded request, we must readjust the amount of * data to be forwarded in order to take into account the size * variations. Note that the current state is >= HTTP_MSG_BODY, * so we don't have to adjust ->sol. */ old_o += chn->buf->i - old_i; b_adv(chn->buf, old_o); txn->req.next -= old_o; txn->req.sov -= old_o; } return 0; } /* Terminate current transaction and prepare a new one. This is very tricky * right now but it works. */ void http_end_txn_clean_session(struct session *s) { int prev_status = s->txn.status; /* FIXME: We need a more portable way of releasing a backend's and a * server's connections. We need a safer way to reinitialize buffer * flags. We also need a more accurate method for computing per-request * data. */ /* unless we're doing keep-alive, we want to quickly close the connection * to the server. */ if (((s->txn.flags & TX_CON_WANT_MSK) != TX_CON_WANT_KAL) || !si_conn_ready(s->req->cons)) { s->req->cons->flags |= SI_FL_NOLINGER | SI_FL_NOHALF; si_shutr(s->req->cons); si_shutw(s->req->cons); } if (s->flags & SN_BE_ASSIGNED) { s->be->beconn--; if (unlikely(s->srv_conn)) sess_change_server(s, NULL); } s->logs.t_close = tv_ms_elapsed(&s->logs.tv_accept, &now); session_process_counters(s); if (s->txn.status) { int n; n = s->txn.status / 100; if (n < 1 || n > 5) n = 0; if (s->fe->mode == PR_MODE_HTTP) { s->fe->fe_counters.p.http.rsp[n]++; if (s->comp_algo && (s->flags & SN_COMP_READY)) s->fe->fe_counters.p.http.comp_rsp++; } if ((s->flags & SN_BE_ASSIGNED) && (s->be->mode == PR_MODE_HTTP)) { s->be->be_counters.p.http.rsp[n]++; s->be->be_counters.p.http.cum_req++; if (s->comp_algo && (s->flags & SN_COMP_READY)) s->be->be_counters.p.http.comp_rsp++; } } /* don't count other requests' data */ s->logs.bytes_in -= s->req->buf->i; s->logs.bytes_out -= s->rep->buf->i; /* let's do a final log if we need it */ if (!LIST_ISEMPTY(&s->fe->logformat) && s->logs.logwait && !(s->flags & SN_MONITOR) && (!(s->fe->options & PR_O_NULLNOLOG) || s->req->total)) { s->do_log(s); } /* stop tracking content-based counters */ session_stop_content_counters(s); session_update_time_stats(s); s->logs.accept_date = date; /* user-visible date for logging */ s->logs.tv_accept = now; /* corrected date for internal use */ tv_zero(&s->logs.tv_request); s->logs.t_queue = -1; s->logs.t_connect = -1; s->logs.t_data = -1; s->logs.t_close = 0; s->logs.prx_queue_size = 0; /* we get the number of pending conns before us */ s->logs.srv_queue_size = 0; /* we will get this number soon */ s->logs.bytes_in = s->req->total = s->req->buf->i; s->logs.bytes_out = s->rep->total = s->rep->buf->i; if (s->pend_pos) pendconn_free(s->pend_pos); if (objt_server(s->target)) { if (s->flags & SN_CURR_SESS) { s->flags &= ~SN_CURR_SESS; objt_server(s->target)->cur_sess--; } if (may_dequeue_tasks(objt_server(s->target), s->be)) process_srv_queue(objt_server(s->target)); } s->target = NULL; /* only release our endpoint if we don't intend to reuse the * connection. */ if (((s->txn.flags & TX_CON_WANT_MSK) != TX_CON_WANT_KAL) || !si_conn_ready(s->req->cons)) { si_release_endpoint(s->req->cons); } s->req->cons->state = s->req->cons->prev_state = SI_ST_INI; s->req->cons->err_type = SI_ET_NONE; s->req->cons->conn_retries = 0; /* used for logging too */ s->req->cons->exp = TICK_ETERNITY; s->req->cons->flags &= SI_FL_DONT_WAKE; /* we're in the context of process_session */ s->req->flags &= ~(CF_SHUTW|CF_SHUTW_NOW|CF_AUTO_CONNECT|CF_WRITE_ERROR|CF_STREAMER|CF_STREAMER_FAST|CF_NEVER_WAIT|CF_WAKE_CONNECT|CF_WROTE_DATA); s->rep->flags &= ~(CF_SHUTR|CF_SHUTR_NOW|CF_READ_ATTACHED|CF_READ_ERROR|CF_READ_NOEXP|CF_STREAMER|CF_STREAMER_FAST|CF_WRITE_PARTIAL|CF_NEVER_WAIT|CF_WROTE_DATA); s->flags &= ~(SN_DIRECT|SN_ASSIGNED|SN_ADDR_SET|SN_BE_ASSIGNED|SN_FORCE_PRST|SN_IGNORE_PRST); s->flags &= ~(SN_CURR_SESS|SN_REDIRECTABLE|SN_SRV_REUSED); s->flags &= ~(SN_ERR_MASK|SN_FINST_MASK|SN_REDISP); s->txn.meth = 0; http_reset_txn(s); s->txn.flags |= TX_NOT_FIRST | TX_WAIT_NEXT_RQ; if (prev_status == 401 || prev_status == 407) { /* In HTTP keep-alive mode, if we receive a 401, we still have * a chance of being able to send the visitor again to the same * server over the same connection. This is required by some * broken protocols such as NTLM, and anyway whenever there is * an opportunity for sending the challenge to the proper place, * it's better to do it (at least it helps with debugging). */ s->txn.flags |= TX_PREFER_LAST; } if (s->fe->options2 & PR_O2_INDEPSTR) s->req->cons->flags |= SI_FL_INDEP_STR; if (s->fe->options2 & PR_O2_NODELAY) { s->req->flags |= CF_NEVER_WAIT; s->rep->flags |= CF_NEVER_WAIT; } /* if the request buffer is not empty, it means we're * about to process another request, so send pending * data with MSG_MORE to merge TCP packets when possible. * Just don't do this if the buffer is close to be full, * because the request will wait for it to flush a little * bit before proceeding. */ if (s->req->buf->i) { if (s->rep->buf->o && !buffer_full(s->rep->buf, global.tune.maxrewrite) && bi_end(s->rep->buf) <= s->rep->buf->data + s->rep->buf->size - global.tune.maxrewrite) s->rep->flags |= CF_EXPECT_MORE; } /* we're removing the analysers, we MUST re-enable events detection */ channel_auto_read(s->req); channel_auto_close(s->req); channel_auto_read(s->rep); channel_auto_close(s->rep); /* we're in keep-alive with an idle connection, monitor it */ si_idle_conn(s->req->cons); s->req->analysers = s->listener->analysers; s->rep->analysers = 0; } /* This function updates the request state machine according to the response * state machine and buffer flags. It returns 1 if it changes anything (flag * or state), otherwise zero. It ignores any state before HTTP_MSG_DONE, as * it is only used to find when a request/response couple is complete. Both * this function and its equivalent should loop until both return zero. It * can set its own state to DONE, CLOSING, CLOSED, TUNNEL, ERROR. */ int http_sync_req_state(struct session *s) { struct channel *chn = s->req; struct http_txn *txn = &s->txn; unsigned int old_flags = chn->flags; unsigned int old_state = txn->req.msg_state; if (unlikely(txn->req.msg_state < HTTP_MSG_BODY)) return 0; if (txn->req.msg_state == HTTP_MSG_DONE) { /* No need to read anymore, the request was completely parsed. * We can shut the read side unless we want to abort_on_close, * or we have a POST request. The issue with POST requests is * that some browsers still send a CRLF after the request, and * this CRLF must be read so that it does not remain in the kernel * buffers, otherwise a close could cause an RST on some systems * (eg: Linux). * Note that if we're using keep-alive on the client side, we'd * rather poll now and keep the polling enabled for the whole * session's life than enabling/disabling it between each * response and next request. */ if (((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_SCL) && ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_KAL) && !(s->be->options & PR_O_ABRT_CLOSE) && txn->meth != HTTP_METH_POST) channel_dont_read(chn); /* if the server closes the connection, we want to immediately react * and close the socket to save packets and syscalls. */ chn->cons->flags |= SI_FL_NOHALF; if (txn->rsp.msg_state == HTTP_MSG_ERROR) goto wait_other_side; if (txn->rsp.msg_state < HTTP_MSG_DONE) { /* The server has not finished to respond, so we * don't want to move in order not to upset it. */ goto wait_other_side; } if (txn->rsp.msg_state == HTTP_MSG_TUNNEL) { /* if any side switches to tunnel mode, the other one does too */ channel_auto_read(chn); txn->req.msg_state = HTTP_MSG_TUNNEL; chn->flags |= CF_NEVER_WAIT; goto wait_other_side; } /* When we get here, it means that both the request and the * response have finished receiving. Depending on the connection * mode, we'll have to wait for the last bytes to leave in either * direction, and sometimes for a close to be effective. */ if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_SCL) { /* Server-close mode : queue a connection close to the server */ if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) channel_shutw_now(chn); } else if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_CLO) { /* Option forceclose is set, or either side wants to close, * let's enforce it now that we're not expecting any new * data to come. The caller knows the session is complete * once both states are CLOSED. */ if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) { channel_shutr_now(chn); channel_shutw_now(chn); } } else { /* The last possible modes are keep-alive and tunnel. Tunnel mode * will not have any analyser so it needs to poll for reads. */ if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) { channel_auto_read(chn); txn->req.msg_state = HTTP_MSG_TUNNEL; chn->flags |= CF_NEVER_WAIT; } } if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) { /* if we've just closed an output, let's switch */ chn->cons->flags |= SI_FL_NOLINGER; /* we want to close ASAP */ if (!channel_is_empty(chn)) { txn->req.msg_state = HTTP_MSG_CLOSING; goto http_msg_closing; } else { txn->req.msg_state = HTTP_MSG_CLOSED; goto http_msg_closed; } } goto wait_other_side; } if (txn->req.msg_state == HTTP_MSG_CLOSING) { http_msg_closing: /* nothing else to forward, just waiting for the output buffer * to be empty and for the shutw_now to take effect. */ if (channel_is_empty(chn)) { txn->req.msg_state = HTTP_MSG_CLOSED; goto http_msg_closed; } else if (chn->flags & CF_SHUTW) { txn->req.msg_state = HTTP_MSG_ERROR; goto wait_other_side; } } if (txn->req.msg_state == HTTP_MSG_CLOSED) { http_msg_closed: /* see above in MSG_DONE why we only do this in these states */ if (((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_SCL) && ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_KAL) && !(s->be->options & PR_O_ABRT_CLOSE)) channel_dont_read(chn); goto wait_other_side; } wait_other_side: return txn->req.msg_state != old_state || chn->flags != old_flags; } /* This function updates the response state machine according to the request * state machine and buffer flags. It returns 1 if it changes anything (flag * or state), otherwise zero. It ignores any state before HTTP_MSG_DONE, as * it is only used to find when a request/response couple is complete. Both * this function and its equivalent should loop until both return zero. It * can set its own state to DONE, CLOSING, CLOSED, TUNNEL, ERROR. */ int http_sync_res_state(struct session *s) { struct channel *chn = s->rep; struct http_txn *txn = &s->txn; unsigned int old_flags = chn->flags; unsigned int old_state = txn->rsp.msg_state; if (unlikely(txn->rsp.msg_state < HTTP_MSG_BODY)) return 0; if (txn->rsp.msg_state == HTTP_MSG_DONE) { /* In theory, we don't need to read anymore, but we must * still monitor the server connection for a possible close * while the request is being uploaded, so we don't disable * reading. */ /* channel_dont_read(chn); */ if (txn->req.msg_state == HTTP_MSG_ERROR) goto wait_other_side; if (txn->req.msg_state < HTTP_MSG_DONE) { /* The client seems to still be sending data, probably * because we got an error response during an upload. * We have the choice of either breaking the connection * or letting it pass through. Let's do the later. */ goto wait_other_side; } if (txn->req.msg_state == HTTP_MSG_TUNNEL) { /* if any side switches to tunnel mode, the other one does too */ channel_auto_read(chn); txn->rsp.msg_state = HTTP_MSG_TUNNEL; chn->flags |= CF_NEVER_WAIT; goto wait_other_side; } /* When we get here, it means that both the request and the * response have finished receiving. Depending on the connection * mode, we'll have to wait for the last bytes to leave in either * direction, and sometimes for a close to be effective. */ if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_SCL) { /* Server-close mode : shut read and wait for the request * side to close its output buffer. The caller will detect * when we're in DONE and the other is in CLOSED and will * catch that for the final cleanup. */ if (!(chn->flags & (CF_SHUTR|CF_SHUTR_NOW))) channel_shutr_now(chn); } else if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_CLO) { /* Option forceclose is set, or either side wants to close, * let's enforce it now that we're not expecting any new * data to come. The caller knows the session is complete * once both states are CLOSED. */ if (!(chn->flags & (CF_SHUTW|CF_SHUTW_NOW))) { channel_shutr_now(chn); channel_shutw_now(chn); } } else { /* The last possible modes are keep-alive and tunnel. Tunnel will * need to forward remaining data. Keep-alive will need to monitor * for connection closing. */ channel_auto_read(chn); chn->flags |= CF_NEVER_WAIT; if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) txn->rsp.msg_state = HTTP_MSG_TUNNEL; } if (chn->flags & (CF_SHUTW|CF_SHUTW_NOW)) { /* if we've just closed an output, let's switch */ if (!channel_is_empty(chn)) { txn->rsp.msg_state = HTTP_MSG_CLOSING; goto http_msg_closing; } else { txn->rsp.msg_state = HTTP_MSG_CLOSED; goto http_msg_closed; } } goto wait_other_side; } if (txn->rsp.msg_state == HTTP_MSG_CLOSING) { http_msg_closing: /* nothing else to forward, just waiting for the output buffer * to be empty and for the shutw_now to take effect. */ if (channel_is_empty(chn)) { txn->rsp.msg_state = HTTP_MSG_CLOSED; goto http_msg_closed; } else if (chn->flags & CF_SHUTW) { txn->rsp.msg_state = HTTP_MSG_ERROR; s->be->be_counters.cli_aborts++; if (objt_server(s->target)) objt_server(s->target)->counters.cli_aborts++; goto wait_other_side; } } if (txn->rsp.msg_state == HTTP_MSG_CLOSED) { http_msg_closed: /* drop any pending data */ bi_erase(chn); channel_auto_close(chn); channel_auto_read(chn); goto wait_other_side; } wait_other_side: /* We force the response to leave immediately if we're waiting for the * other side, since there is no pending shutdown to push it out. */ if (!channel_is_empty(chn)) chn->flags |= CF_SEND_DONTWAIT; return txn->rsp.msg_state != old_state || chn->flags != old_flags; } /* Resync the request and response state machines. Return 1 if either state * changes. */ int http_resync_states(struct session *s) { struct http_txn *txn = &s->txn; int old_req_state = txn->req.msg_state; int old_res_state = txn->rsp.msg_state; http_sync_req_state(s); while (1) { if (!http_sync_res_state(s)) break; if (!http_sync_req_state(s)) break; } /* OK, both state machines agree on a compatible state. * There are a few cases we're interested in : * - HTTP_MSG_TUNNEL on either means we have to disable both analysers * - HTTP_MSG_CLOSED on both sides means we've reached the end in both * directions, so let's simply disable both analysers. * - HTTP_MSG_CLOSED on the response only means we must abort the * request. * - HTTP_MSG_CLOSED on the request and HTTP_MSG_DONE on the response * with server-close mode means we've completed one request and we * must re-initialize the server connection. */ if (txn->req.msg_state == HTTP_MSG_TUNNEL || txn->rsp.msg_state == HTTP_MSG_TUNNEL || (txn->req.msg_state == HTTP_MSG_CLOSED && txn->rsp.msg_state == HTTP_MSG_CLOSED)) { s->req->analysers = 0; channel_auto_close(s->req); channel_auto_read(s->req); s->rep->analysers = 0; channel_auto_close(s->rep); channel_auto_read(s->rep); } else if ((txn->req.msg_state >= HTTP_MSG_DONE && (txn->rsp.msg_state == HTTP_MSG_CLOSED || (s->rep->flags & CF_SHUTW))) || txn->rsp.msg_state == HTTP_MSG_ERROR || txn->req.msg_state == HTTP_MSG_ERROR) { s->rep->analysers = 0; channel_auto_close(s->rep); channel_auto_read(s->rep); s->req->analysers = 0; channel_abort(s->req); channel_auto_close(s->req); channel_auto_read(s->req); bi_erase(s->req); } else if ((txn->req.msg_state == HTTP_MSG_DONE || txn->req.msg_state == HTTP_MSG_CLOSED) && txn->rsp.msg_state == HTTP_MSG_DONE && ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_SCL || (txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL)) { /* server-close/keep-alive: terminate this transaction, * possibly killing the server connection and reinitialize * a fresh-new transaction. */ http_end_txn_clean_session(s); } return txn->req.msg_state != old_req_state || txn->rsp.msg_state != old_res_state; } /* This function is an analyser which forwards request body (including chunk * sizes if any). It is called as soon as we must forward, even if we forward * zero byte. The only situation where it must not be called is when we're in * tunnel mode and we want to forward till the close. It's used both to forward * remaining data and to resync after end of body. It expects the msg_state to * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to * read more data, or 1 once we can go on with next request or end the session. * When in MSG_DATA or MSG_TRAILERS, it will automatically forward chunk_len * bytes of pending data + the headers if not already done. */ int http_request_forward_body(struct session *s, struct channel *req, int an_bit) { struct http_txn *txn = &s->txn; struct http_msg *msg = &s->txn.req; if (unlikely(msg->msg_state < HTTP_MSG_BODY)) return 0; if ((req->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) || ((req->flags & CF_SHUTW) && (req->to_forward || req->buf->o))) { /* Output closed while we were sending data. We must abort and * wake the other side up. */ msg->msg_state = HTTP_MSG_ERROR; http_resync_states(s); return 1; } /* Note that we don't have to send 100-continue back because we don't * need the data to complete our job, and it's up to the server to * decide whether to return 100, 417 or anything else in return of * an "Expect: 100-continue" header. */ if (msg->sov > 0) { /* we have msg->sov which points to the first byte of message * body, and req->buf.p still points to the beginning of the * message. We forward the headers now, as we don't need them * anymore, and we want to flush them. */ b_adv(req->buf, msg->sov); msg->next -= msg->sov; msg->sov = 0; /* The previous analysers guarantee that the state is somewhere * between MSG_BODY and the first MSG_DATA. So msg->sol and * msg->next are always correct. */ if (msg->msg_state < HTTP_MSG_CHUNK_SIZE) { if (msg->flags & HTTP_MSGF_TE_CHNK) msg->msg_state = HTTP_MSG_CHUNK_SIZE; else msg->msg_state = HTTP_MSG_DATA; } } /* Some post-connect processing might want us to refrain from starting to * forward data. Currently, the only reason for this is "balance url_param" * whichs need to parse/process the request after we've enabled forwarding. */ if (unlikely(msg->flags & HTTP_MSGF_WAIT_CONN)) { if (!(s->rep->flags & CF_READ_ATTACHED)) { channel_auto_connect(req); req->flags |= CF_WAKE_CONNECT; goto missing_data; } msg->flags &= ~HTTP_MSGF_WAIT_CONN; } /* in most states, we should abort in case of early close */ channel_auto_close(req); if (req->to_forward) { /* We can't process the buffer's contents yet */ req->flags |= CF_WAKE_WRITE; goto missing_data; } while (1) { if (msg->msg_state == HTTP_MSG_DATA) { /* must still forward */ /* we may have some pending data starting at req->buf->p */ if (msg->chunk_len > req->buf->i - msg->next) { req->flags |= CF_WAKE_WRITE; goto missing_data; } msg->next += msg->chunk_len; msg->chunk_len = 0; /* nothing left to forward */ if (msg->flags & HTTP_MSGF_TE_CHNK) msg->msg_state = HTTP_MSG_CHUNK_CRLF; else msg->msg_state = HTTP_MSG_DONE; } else if (msg->msg_state == HTTP_MSG_CHUNK_SIZE) { /* read the chunk size and assign it to ->chunk_len, then * set ->next to point to the body and switch to DATA or * TRAILERS state. */ int ret = http_parse_chunk_size(msg); if (ret == 0) goto missing_data; else if (ret < 0) { session_inc_http_err_ctr(s); if (msg->err_pos >= 0) http_capture_bad_message(&s->fe->invalid_req, s, msg, HTTP_MSG_CHUNK_SIZE, s->be); goto return_bad_req; } /* otherwise we're in HTTP_MSG_DATA or HTTP_MSG_TRAILERS state */ } else if (msg->msg_state == HTTP_MSG_CHUNK_CRLF) { /* we want the CRLF after the data */ int ret = http_skip_chunk_crlf(msg); if (ret == 0) goto missing_data; else if (ret < 0) { session_inc_http_err_ctr(s); if (msg->err_pos >= 0) http_capture_bad_message(&s->fe->invalid_req, s, msg, HTTP_MSG_CHUNK_CRLF, s->be); goto return_bad_req; } /* we're in MSG_CHUNK_SIZE now */ } else if (msg->msg_state == HTTP_MSG_TRAILERS) { int ret = http_forward_trailers(msg); if (ret == 0) goto missing_data; else if (ret < 0) { session_inc_http_err_ctr(s); if (msg->err_pos >= 0) http_capture_bad_message(&s->fe->invalid_req, s, msg, HTTP_MSG_TRAILERS, s->be); goto return_bad_req; } /* we're in HTTP_MSG_DONE now */ } else { int old_state = msg->msg_state; /* other states, DONE...TUNNEL */ /* we may have some pending data starting at req->buf->p * such as last chunk of data or trailers. */ b_adv(req->buf, msg->next); if (unlikely(!(s->req->flags & CF_WROTE_DATA))) msg->sov -= msg->next; msg->next = 0; /* for keep-alive we don't want to forward closes on DONE */ if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL || (txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_SCL) channel_dont_close(req); if (http_resync_states(s)) { /* some state changes occurred, maybe the analyser * was disabled too. */ if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) { if (req->flags & CF_SHUTW) { /* request errors are most likely due to * the server aborting the transfer. */ goto aborted_xfer; } if (msg->err_pos >= 0) http_capture_bad_message(&s->fe->invalid_req, s, msg, old_state, s->be); goto return_bad_req; } return 1; } /* If "option abortonclose" is set on the backend, we * want to monitor the client's connection and forward * any shutdown notification to the server, which will * decide whether to close or to go on processing the * request. */ if (s->be->options & PR_O_ABRT_CLOSE) { channel_auto_read(req); channel_auto_close(req); } else if (s->txn.meth == HTTP_METH_POST) { /* POST requests may require to read extra CRLF * sent by broken browsers and which could cause * an RST to be sent upon close on some systems * (eg: Linux). */ channel_auto_read(req); } return 0; } } missing_data: /* we may have some pending data starting at req->buf->p */ b_adv(req->buf, msg->next); if (unlikely(!(s->req->flags & CF_WROTE_DATA))) msg->sov -= msg->next + MIN(msg->chunk_len, req->buf->i); msg->next = 0; msg->chunk_len -= channel_forward(req, msg->chunk_len); /* stop waiting for data if the input is closed before the end */ if (req->flags & CF_SHUTR) { if (!(s->flags & SN_ERR_MASK)) s->flags |= SN_ERR_CLICL; if (!(s->flags & SN_FINST_MASK)) { if (txn->rsp.msg_state < HTTP_MSG_ERROR) s->flags |= SN_FINST_H; else s->flags |= SN_FINST_D; } s->fe->fe_counters.cli_aborts++; s->be->be_counters.cli_aborts++; if (objt_server(s->target)) objt_server(s->target)->counters.cli_aborts++; goto return_bad_req_stats_ok; } /* waiting for the last bits to leave the buffer */ if (req->flags & CF_SHUTW) goto aborted_xfer; /* When TE: chunked is used, we need to get there again to parse remaining * chunks even if the client has closed, so we don't want to set CF_DONTCLOSE. */ if (msg->flags & HTTP_MSGF_TE_CHNK) channel_dont_close(req); /* We know that more data are expected, but we couldn't send more that * what we did. So we always set the CF_EXPECT_MORE flag so that the * system knows it must not set a PUSH on this first part. Interactive * modes are already handled by the stream sock layer. We must not do * this in content-length mode because it could present the MSG_MORE * flag with the last block of forwarded data, which would cause an * additional delay to be observed by the receiver. */ if (msg->flags & HTTP_MSGF_TE_CHNK) req->flags |= CF_EXPECT_MORE; return 0; return_bad_req: /* let's centralize all bad requests */ s->fe->fe_counters.failed_req++; if (s->listener->counters) s->listener->counters->failed_req++; return_bad_req_stats_ok: /* we may have some pending data starting at req->buf->p */ b_adv(req->buf, msg->next); msg->next = 0; txn->req.msg_state = HTTP_MSG_ERROR; if (txn->status) { /* Note: we don't send any error if some data were already sent */ stream_int_retnclose(req->prod, NULL); } else { txn->status = 400; stream_int_retnclose(req->prod, http_error_message(s, HTTP_ERR_400)); } req->analysers = 0; s->rep->analysers = 0; /* we're in data phase, we want to abort both directions */ if (!(s->flags & SN_ERR_MASK)) s->flags |= SN_ERR_PRXCOND; if (!(s->flags & SN_FINST_MASK)) { if (txn->rsp.msg_state < HTTP_MSG_ERROR) s->flags |= SN_FINST_H; else s->flags |= SN_FINST_D; } return 0; aborted_xfer: txn->req.msg_state = HTTP_MSG_ERROR; if (txn->status) { /* Note: we don't send any error if some data were already sent */ stream_int_retnclose(req->prod, NULL); } else { txn->status = 502; stream_int_retnclose(req->prod, http_error_message(s, HTTP_ERR_502)); } req->analysers = 0; s->rep->analysers = 0; /* we're in data phase, we want to abort both directions */ s->fe->fe_counters.srv_aborts++; s->be->be_counters.srv_aborts++; if (objt_server(s->target)) objt_server(s->target)->counters.srv_aborts++; if (!(s->flags & SN_ERR_MASK)) s->flags |= SN_ERR_SRVCL; if (!(s->flags & SN_FINST_MASK)) { if (txn->rsp.msg_state < HTTP_MSG_ERROR) s->flags |= SN_FINST_H; else s->flags |= SN_FINST_D; } return 0; } /* This stream analyser waits for a complete HTTP response. It returns 1 if the * processing can continue on next analysers, or zero if it either needs more * data or wants to immediately abort the response (eg: timeout, error, ...). It * is tied to AN_RES_WAIT_HTTP and may may remove itself from s->rep->analysers * when it has nothing left to do, and may remove any analyser when it wants to * abort. */ int http_wait_for_response(struct session *s, struct channel *rep, int an_bit) { struct http_txn *txn = &s->txn; struct http_msg *msg = &txn->rsp; struct hdr_ctx ctx; int use_close_only; int cur_idx; int n; DPRINTF(stderr,"[%u] %s: session=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%d analysers=%02x\n", now_ms, __FUNCTION__, s, rep, rep->rex, rep->wex, rep->flags, rep->buf->i, rep->analysers); /* * Now parse the partial (or complete) lines. * We will check the response syntax, and also join multi-line * headers. An index of all the lines will be elaborated while * parsing. * * For the parsing, we use a 28 states FSM. * * Here is the information we currently have : * rep->buf->p = beginning of response * rep->buf->p + msg->eoh = end of processed headers / start of current one * rep->buf->p + rep->buf->i = end of input data * msg->eol = end of current header or line (LF or CRLF) * msg->next = first non-visited byte */ next_one: /* There's a protected area at the end of the buffer for rewriting * purposes. We don't want to start to parse the request if the * protected area is affected, because we may have to move processed * data later, which is much more complicated. */ if (buffer_not_empty(rep->buf) && msg->msg_state < HTTP_MSG_ERROR) { if (unlikely(!channel_reserved(rep))) { /* some data has still not left the buffer, wake us once that's done */ if (rep->flags & (CF_SHUTW|CF_SHUTW_NOW|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) goto abort_response; channel_dont_close(rep); rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */ rep->flags |= CF_WAKE_WRITE; return 0; } if (unlikely(bi_end(rep->buf) < b_ptr(rep->buf, msg->next) || bi_end(rep->buf) > rep->buf->data + rep->buf->size - global.tune.maxrewrite)) buffer_slow_realign(rep->buf); if (likely(msg->next < rep->buf->i)) http_msg_analyzer(msg, &txn->hdr_idx); } /* 1: we might have to print this header in debug mode */ if (unlikely((global.mode & MODE_DEBUG) && (!(global.mode & MODE_QUIET) || (global.mode & MODE_VERBOSE)) && msg->msg_state >= HTTP_MSG_BODY)) { char *eol, *sol; sol = rep->buf->p; eol = sol + (msg->sl.st.l ? msg->sl.st.l : rep->buf->i); debug_hdr("srvrep", s, sol, eol); sol += hdr_idx_first_pos(&txn->hdr_idx); cur_idx = hdr_idx_first_idx(&txn->hdr_idx); while (cur_idx) { eol = sol + txn->hdr_idx.v[cur_idx].len; debug_hdr("srvhdr", s, sol, eol); sol = eol + txn->hdr_idx.v[cur_idx].cr + 1; cur_idx = txn->hdr_idx.v[cur_idx].next; } } /* * Now we quickly check if we have found a full valid response. * If not so, we check the FD and buffer states before leaving. * A full response is indicated by the fact that we have seen * the double LF/CRLF, so the state is >= HTTP_MSG_BODY. Invalid * responses are checked first. * * Depending on whether the client is still there or not, we * may send an error response back or not. Note that normally * we should only check for HTTP status there, and check I/O * errors somewhere else. */ if (unlikely(msg->msg_state < HTTP_MSG_BODY)) { /* Invalid response */ if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) { /* we detected a parsing error. We want to archive this response * in the dedicated proxy area for later troubleshooting. */ hdr_response_bad: if (msg->msg_state == HTTP_MSG_ERROR || msg->err_pos >= 0) http_capture_bad_message(&s->be->invalid_rep, s, msg, msg->msg_state, s->fe); s->be->be_counters.failed_resp++; if (objt_server(s->target)) { objt_server(s->target)->counters.failed_resp++; health_adjust(objt_server(s->target), HANA_STATUS_HTTP_HDRRSP); } abort_response: channel_auto_close(rep); rep->analysers = 0; txn->status = 502; rep->prod->flags |= SI_FL_NOLINGER; bi_erase(rep); stream_int_retnclose(rep->cons, http_error_message(s, HTTP_ERR_502)); if (!(s->flags & SN_ERR_MASK)) s->flags |= SN_ERR_PRXCOND; if (!(s->flags & SN_FINST_MASK)) s->flags |= SN_FINST_H; return 0; } /* too large response does not fit in buffer. */ else if (buffer_full(rep->buf, global.tune.maxrewrite)) { if (msg->err_pos < 0) msg->err_pos = rep->buf->i; goto hdr_response_bad; } /* read error */ else if (rep->flags & CF_READ_ERROR) { if (msg->err_pos >= 0) http_capture_bad_message(&s->be->invalid_rep, s, msg, msg->msg_state, s->fe); else if (txn->flags & TX_NOT_FIRST) goto abort_keep_alive; s->be->be_counters.failed_resp++; if (objt_server(s->target)) { objt_server(s->target)->counters.failed_resp++; health_adjust(objt_server(s->target), HANA_STATUS_HTTP_READ_ERROR); } channel_auto_close(rep); rep->analysers = 0; txn->status = 502; rep->prod->flags |= SI_FL_NOLINGER; bi_erase(rep); stream_int_retnclose(rep->cons, http_error_message(s, HTTP_ERR_502)); if (!(s->flags & SN_ERR_MASK)) s->flags |= SN_ERR_SRVCL; if (!(s->flags & SN_FINST_MASK)) s->flags |= SN_FINST_H; return 0; } /* read timeout : return a 504 to the client. */ else if (rep->flags & CF_READ_TIMEOUT) { if (msg->err_pos >= 0) http_capture_bad_message(&s->be->invalid_rep, s, msg, msg->msg_state, s->fe); else if (txn->flags & TX_NOT_FIRST) goto abort_keep_alive; s->be->be_counters.failed_resp++; if (objt_server(s->target)) { objt_server(s->target)->counters.failed_resp++; health_adjust(objt_server(s->target), HANA_STATUS_HTTP_READ_TIMEOUT); } channel_auto_close(rep); rep->analysers = 0; txn->status = 504; rep->prod->flags |= SI_FL_NOLINGER; bi_erase(rep); stream_int_retnclose(rep->cons, http_error_message(s, HTTP_ERR_504)); if (!(s->flags & SN_ERR_MASK)) s->flags |= SN_ERR_SRVTO; if (!(s->flags & SN_FINST_MASK)) s->flags |= SN_FINST_H; return 0; } /* client abort with an abortonclose */ else if ((rep->flags & CF_SHUTR) && ((s->req->flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW))) { s->fe->fe_counters.cli_aborts++; s->be->be_counters.cli_aborts++; if (objt_server(s->target)) objt_server(s->target)->counters.cli_aborts++; rep->analysers = 0; channel_auto_close(rep); txn->status = 400; bi_erase(rep); stream_int_retnclose(rep->cons, http_error_message(s, HTTP_ERR_400)); if (!(s->flags & SN_ERR_MASK)) s->flags |= SN_ERR_CLICL; if (!(s->flags & SN_FINST_MASK)) s->flags |= SN_FINST_H; /* process_session() will take care of the error */ return 0; } /* close from server, capture the response if the server has started to respond */ else if (rep->flags & CF_SHUTR) { if (msg->msg_state >= HTTP_MSG_RPVER || msg->err_pos >= 0) http_capture_bad_message(&s->be->invalid_rep, s, msg, msg->msg_state, s->fe); else if (txn->flags & TX_NOT_FIRST) goto abort_keep_alive; s->be->be_counters.failed_resp++; if (objt_server(s->target)) { objt_server(s->target)->counters.failed_resp++; health_adjust(objt_server(s->target), HANA_STATUS_HTTP_BROKEN_PIPE); } channel_auto_close(rep); rep->analysers = 0; txn->status = 502; rep->prod->flags |= SI_FL_NOLINGER; bi_erase(rep); stream_int_retnclose(rep->cons, http_error_message(s, HTTP_ERR_502)); if (!(s->flags & SN_ERR_MASK)) s->flags |= SN_ERR_SRVCL; if (!(s->flags & SN_FINST_MASK)) s->flags |= SN_FINST_H; return 0; } /* write error to client (we don't send any message then) */ else if (rep->flags & CF_WRITE_ERROR) { if (msg->err_pos >= 0) http_capture_bad_message(&s->be->invalid_rep, s, msg, msg->msg_state, s->fe); else if (txn->flags & TX_NOT_FIRST) goto abort_keep_alive; s->be->be_counters.failed_resp++; rep->analysers = 0; channel_auto_close(rep); if (!(s->flags & SN_ERR_MASK)) s->flags |= SN_ERR_CLICL; if (!(s->flags & SN_FINST_MASK)) s->flags |= SN_FINST_H; /* process_session() will take care of the error */ return 0; } channel_dont_close(rep); rep->flags |= CF_READ_DONTWAIT; /* try to get back here ASAP */ return 0; } /* More interesting part now : we know that we have a complete * response which at least looks like HTTP. We have an indicator * of each header's length, so we can parse them quickly. */ if (unlikely(msg->err_pos >= 0)) http_capture_bad_message(&s->be->invalid_rep, s, msg, msg->msg_state, s->fe); /* * 1: get the status code */ n = rep->buf->p[msg->sl.st.c] - '0'; if (n < 1 || n > 5) n = 0; /* when the client triggers a 4xx from the server, it's most often due * to a missing object or permission. These events should be tracked * because if they happen often, it may indicate a brute force or a * vulnerability scan. */ if (n == 4) session_inc_http_err_ctr(s); if (objt_server(s->target)) objt_server(s->target)->counters.p.http.rsp[n]++; /* check if the response is HTTP/1.1 or above */ if ((msg->sl.st.v_l == 8) && ((rep->buf->p[5] > '1') || ((rep->buf->p[5] == '1') && (rep->buf->p[7] >= '1')))) msg->flags |= HTTP_MSGF_VER_11; /* "connection" has not been parsed yet */ txn->flags &= ~(TX_HDR_CONN_PRS|TX_HDR_CONN_CLO|TX_HDR_CONN_KAL|TX_HDR_CONN_UPG|TX_CON_CLO_SET|TX_CON_KAL_SET); /* transfer length unknown*/ msg->flags &= ~HTTP_MSGF_XFER_LEN; txn->status = strl2ui(rep->buf->p + msg->sl.st.c, msg->sl.st.c_l); /* Adjust server's health based on status code. Note: status codes 501 * and 505 are triggered on demand by client request, so we must not * count them as server failures. */ if (objt_server(s->target)) { if (txn->status >= 100 && (txn->status < 500 || txn->status == 501 || txn->status == 505)) health_adjust(objt_server(s->target), HANA_STATUS_HTTP_OK); else health_adjust(objt_server(s->target), HANA_STATUS_HTTP_STS); } /* * 2: check for cacheability. */ switch (txn->status) { case 100: /* * We may be facing a 100-continue response, in which case this * is not the right response, and we're waiting for the next one. * Let's allow this response to go to the client and wait for the * next one. */ hdr_idx_init(&txn->hdr_idx); msg->next -= channel_forward(rep, msg->next); msg->msg_state = HTTP_MSG_RPBEFORE; txn->status = 0; s->logs.t_data = -1; /* was not a response yet */ goto next_one; case 200: case 203: case 206: case 300: case 301: case 410: /* RFC2616 @13.4: * "A response received with a status code of * 200, 203, 206, 300, 301 or 410 MAY be stored * by a cache (...) unless a cache-control * directive prohibits caching." * * RFC2616 @9.5: POST method : * "Responses to this method are not cacheable, * unless the response includes appropriate * Cache-Control or Expires header fields." */ if (likely(txn->meth != HTTP_METH_POST) && ((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC))) txn->flags |= TX_CACHEABLE | TX_CACHE_COOK; break; default: break; } /* * 3: we may need to capture headers */ s->logs.logwait &= ~LW_RESP; if (unlikely((s->logs.logwait & LW_RSPHDR) && txn->rsp.cap)) capture_headers(rep->buf->p, &txn->hdr_idx, txn->rsp.cap, s->fe->rsp_cap); /* 4: determine the transfer-length. * According to RFC2616 #4.4, amended by the HTTPbis working group, * the presence of a message-body in a RESPONSE and its transfer length * must be determined that way : * * All responses to the HEAD request method MUST NOT include a * message-body, even though the presence of entity-header fields * might lead one to believe they do. All 1xx (informational), 204 * (No Content), and 304 (Not Modified) responses MUST NOT include a * message-body. All other responses do include a message-body, * although it MAY be of zero length. * * 1. Any response which "MUST NOT" include a message-body (such as the * 1xx, 204 and 304 responses and any response to a HEAD request) is * always terminated by the first empty line after the header fields, * regardless of the entity-header fields present in the message. * * 2. If a Transfer-Encoding header field (Section 9.7) is present and * the "chunked" transfer-coding (Section 6.2) is used, the * transfer-length is defined by the use of this transfer-coding. * If a Transfer-Encoding header field is present and the "chunked" * transfer-coding is not present, the transfer-length is defined by * the sender closing the connection. * * 3. If a Content-Length header field is present, its decimal value in * OCTETs represents both the entity-length and the transfer-length. * If a message is received with both a Transfer-Encoding header * field and a Content-Length header field, the latter MUST be ignored. * * 4. If the message uses the media type "multipart/byteranges", and * the transfer-length is not otherwise specified, then this self- * delimiting media type defines the transfer-length. This media * type MUST NOT be used unless the sender knows that the recipient * can parse it; the presence in a request of a Range header with * multiple byte-range specifiers from a 1.1 client implies that the * client can parse multipart/byteranges responses. * * 5. By the server closing the connection. */ /* Skip parsing if no content length is possible. The response flags * remain 0 as well as the chunk_len, which may or may not mirror * the real header value, and we note that we know the response's length. * FIXME: should we parse anyway and return an error on chunked encoding ? */ if (txn->meth == HTTP_METH_HEAD || (txn->status >= 100 && txn->status < 200) || txn->status == 204 || txn->status == 304) { msg->flags |= HTTP_MSGF_XFER_LEN; s->comp_algo = NULL; goto skip_content_length; } use_close_only = 0; ctx.idx = 0; while ((msg->flags & HTTP_MSGF_VER_11) && http_find_header2("Transfer-Encoding", 17, rep->buf->p, &txn->hdr_idx, &ctx)) { if (ctx.vlen == 7 && strncasecmp(ctx.line + ctx.val, "chunked", 7) == 0) msg->flags |= (HTTP_MSGF_TE_CHNK | HTTP_MSGF_XFER_LEN); else if (msg->flags & HTTP_MSGF_TE_CHNK) { /* bad transfer-encoding (chunked followed by something else) */ use_close_only = 1; msg->flags &= ~(HTTP_MSGF_TE_CHNK | HTTP_MSGF_XFER_LEN); break; } } /* FIXME: below we should remove the content-length header(s) in case of chunked encoding */ ctx.idx = 0; while (!(msg->flags & HTTP_MSGF_TE_CHNK) && !use_close_only && http_find_header2("Content-Length", 14, rep->buf->p, &txn->hdr_idx, &ctx)) { signed long long cl; if (!ctx.vlen) { msg->err_pos = ctx.line + ctx.val - rep->buf->p; goto hdr_response_bad; } if (strl2llrc(ctx.line + ctx.val, ctx.vlen, &cl)) { msg->err_pos = ctx.line + ctx.val - rep->buf->p; goto hdr_response_bad; /* parse failure */ } if (cl < 0) { msg->err_pos = ctx.line + ctx.val - rep->buf->p; goto hdr_response_bad; } if ((msg->flags & HTTP_MSGF_CNT_LEN) && (msg->chunk_len != cl)) { msg->err_pos = ctx.line + ctx.val - rep->buf->p; goto hdr_response_bad; /* already specified, was different */ } msg->flags |= HTTP_MSGF_CNT_LEN | HTTP_MSGF_XFER_LEN; msg->body_len = msg->chunk_len = cl; } if (s->fe->comp || s->be->comp) select_compression_response_header(s, rep->buf); skip_content_length: /* Now we have to check if we need to modify the Connection header. * This is more difficult on the response than it is on the request, * because we can have two different HTTP versions and we don't know * how the client will interprete a response. For instance, let's say * that the client sends a keep-alive request in HTTP/1.0 and gets an * HTTP/1.1 response without any header. Maybe it will bound itself to * HTTP/1.0 because it only knows about it, and will consider the lack * of header as a close, or maybe it knows HTTP/1.1 and can consider * the lack of header as a keep-alive. Thus we will use two flags * indicating how a request MAY be understood by the client. In case * of multiple possibilities, we'll fix the header to be explicit. If * ambiguous cases such as both close and keepalive are seen, then we * will fall back to explicit close. Note that we won't take risks with * HTTP/1.0 clients which may not necessarily understand keep-alive. * See doc/internals/connection-header.txt for the complete matrix. */ if (unlikely((txn->meth == HTTP_METH_CONNECT && txn->status == 200) || txn->status == 101)) { /* Either we've established an explicit tunnel, or we're * switching the protocol. In both cases, we're very unlikely * to understand the next protocols. We have to switch to tunnel * mode, so that we transfer the request and responses then let * this protocol pass unmodified. When we later implement specific * parsers for such protocols, we'll want to check the Upgrade * header which contains information about that protocol for * responses with status 101 (eg: see RFC2817 about TLS). */ txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_TUN; } else if ((txn->status >= 200) && !(txn->flags & TX_HDR_CONN_PRS) && ((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN || ((s->fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL || (s->be->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL))) { int to_del = 0; /* this situation happens when combining pretend-keepalive with httpclose. */ if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL && ((s->fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL || (s->be->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL)) txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_CLO; /* on unknown transfer length, we must close */ if (!(msg->flags & HTTP_MSGF_XFER_LEN) && (txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN) txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_CLO; /* now adjust header transformations depending on current state */ if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN || (txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_CLO) { to_del |= 2; /* remove "keep-alive" on any response */ if (!(msg->flags & HTTP_MSGF_VER_11)) to_del |= 1; /* remove "close" for HTTP/1.0 responses */ } else { /* SCL / KAL */ to_del |= 1; /* remove "close" on any response */ if (txn->req.flags & msg->flags & HTTP_MSGF_VER_11) to_del |= 2; /* remove "keep-alive" on pure 1.1 responses */ } /* Parse and remove some headers from the connection header */ http_parse_connection_header(txn, msg, to_del); /* Some keep-alive responses are converted to Server-close if * the server wants to close. */ if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL) { if ((txn->flags & TX_HDR_CONN_CLO) || (!(txn->flags & TX_HDR_CONN_KAL) && !(msg->flags & HTTP_MSGF_VER_11))) txn->flags = (txn->flags & ~TX_CON_WANT_MSK) | TX_CON_WANT_SCL; } } /* we want to have the response time before we start processing it */ s->logs.t_data = tv_ms_elapsed(&s->logs.tv_accept, &now); /* end of job, return OK */ rep->analysers &= ~an_bit; rep->analyse_exp = TICK_ETERNITY; channel_auto_close(rep); return 1; abort_keep_alive: /* A keep-alive request to the server failed on a network error. * The client is required to retry. We need to close without returning * any other information so that the client retries. */ txn->status = 0; rep->analysers = 0; s->req->analysers = 0; channel_auto_close(rep); s->logs.logwait = 0; s->logs.level = 0; s->rep->flags &= ~CF_EXPECT_MORE; /* speed up sending a previous response */ bi_erase(rep); stream_int_retnclose(rep->cons, NULL); return 0; } /* This function performs all the processing enabled for the current response. * It normally returns 1 unless it wants to break. It relies on buffers flags, * and updates s->rep->analysers. It might make sense to explode it into several * other functions. It works like process_request (see indications above). */ int http_process_res_common(struct session *s, struct channel *rep, int an_bit, struct proxy *px) { struct http_txn *txn = &s->txn; struct http_msg *msg = &txn->rsp; struct proxy *cur_proxy; struct cond_wordlist *wl; struct http_res_rule *http_res_last_rule = NULL; DPRINTF(stderr,"[%u] %s: session=%p b=%p, exp(r,w)=%u,%u bf=%08x bh=%d analysers=%02x\n", now_ms, __FUNCTION__, s, rep, rep->rex, rep->wex, rep->flags, rep->buf->i, rep->analysers); if (unlikely(msg->msg_state < HTTP_MSG_BODY)) /* we need more data */ return 0; rep->analysers &= ~an_bit; rep->analyse_exp = TICK_ETERNITY; /* The stats applet needs to adjust the Connection header but we don't * apply any filter there. */ if (unlikely(objt_applet(s->target) == &http_stats_applet)) goto skip_filters; /* * We will have to evaluate the filters. * As opposed to version 1.2, now they will be evaluated in the * filters order and not in the header order. This means that * each filter has to be validated among all headers. * * Filters are tried with ->be first, then with ->fe if it is * different from ->be. */ cur_proxy = s->be; while (1) { struct proxy *rule_set = cur_proxy; /* evaluate http-response rules */ if (!http_res_last_rule) http_res_last_rule = http_res_get_intercept_rule(cur_proxy, &cur_proxy->http_res_rules, s, txn); /* try headers filters */ if (rule_set->rsp_exp != NULL) { if (apply_filters_to_response(s, rep, rule_set) < 0) { return_bad_resp: if (objt_server(s->target)) { objt_server(s->target)->counters.failed_resp++; health_adjust(objt_server(s->target), HANA_STATUS_HTTP_RSP); } s->be->be_counters.failed_resp++; return_srv_prx_502: rep->analysers = 0; txn->status = 502; s->logs.t_data = -1; /* was not a valid response */ rep->prod->flags |= SI_FL_NOLINGER; bi_erase(rep); stream_int_retnclose(rep->cons, http_error_message(s, HTTP_ERR_502)); if (!(s->flags & SN_ERR_MASK)) s->flags |= SN_ERR_PRXCOND; if (!(s->flags & SN_FINST_MASK)) s->flags |= SN_FINST_H; return 0; } } /* has the response been denied ? */ if (txn->flags & TX_SVDENY) { if (objt_server(s->target)) objt_server(s->target)->counters.failed_secu++; s->be->be_counters.denied_resp++; s->fe->fe_counters.denied_resp++; if (s->listener->counters) s->listener->counters->denied_resp++; goto return_srv_prx_502; } /* add response headers from the rule sets in the same order */ list_for_each_entry(wl, &rule_set->rsp_add, list) { if (txn->status < 200 && txn->status != 101) break; if (wl->cond) { int ret = acl_exec_cond(wl->cond, px, s, txn, SMP_OPT_DIR_RES|SMP_OPT_FINAL); ret = acl_pass(ret); if (((struct acl_cond *)wl->cond)->pol == ACL_COND_UNLESS) ret = !ret; if (!ret) continue; } if (unlikely(http_header_add_tail(&txn->rsp, &txn->hdr_idx, wl->s) < 0)) goto return_bad_resp; } /* check whether we're already working on the frontend */ if (cur_proxy == s->fe) break; cur_proxy = s->fe; } /* OK that's all we can do for 1xx responses */ if (unlikely(txn->status < 200 && txn->status != 101)) goto skip_header_mangling; /* * Now check for a server cookie. */ if (s->be->cookie_name || s->be->appsession_name || s->fe->capture_name || (s->be->options & PR_O_CHK_CACHE)) manage_server_side_cookies(s, rep); /* * Check for cache-control or pragma headers if required. */ if (((s->be->options & PR_O_CHK_CACHE) || (s->be->ck_opts & PR_CK_NOC)) && txn->status != 101) check_response_for_cacheability(s, rep); /* * Add server cookie in the response if needed */ if (objt_server(s->target) && (s->be->ck_opts & PR_CK_INS) && !((txn->flags & TX_SCK_FOUND) && (s->be->ck_opts & PR_CK_PSV)) && (!(s->flags & SN_DIRECT) || ((s->be->cookie_maxidle || txn->cookie_last_date) && (!txn->cookie_last_date || (txn->cookie_last_date - date.tv_sec) < 0)) || (s->be->cookie_maxlife && !txn->cookie_first_date) || // set the first_date (!s->be->cookie_maxlife && txn->cookie_first_date)) && // remove the first_date (!(s->be->ck_opts & PR_CK_POST) || (txn->meth == HTTP_METH_POST)) && !(s->flags & SN_IGNORE_PRST)) { /* the server is known, it's not the one the client requested, or the * cookie's last seen date needs to be refreshed. We have to * insert a set-cookie here, except if we want to insert only on POST * requests and this one isn't. Note that servers which don't have cookies * (eg: some backup servers) will return a full cookie removal request. */ if (!objt_server(s->target)->cookie) { chunk_printf(&trash, "Set-Cookie: %s=; Expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/", s->be->cookie_name); } else { chunk_printf(&trash, "Set-Cookie: %s=%s", s->be->cookie_name, objt_server(s->target)->cookie); if (s->be->cookie_maxidle || s->be->cookie_maxlife) { /* emit last_date, which is mandatory */ trash.str[trash.len++] = COOKIE_DELIM_DATE; s30tob64((date.tv_sec+3) >> 2, trash.str + trash.len); trash.len += 5; if (s->be->cookie_maxlife) { /* emit first_date, which is either the original one or * the current date. */ trash.str[trash.len++] = COOKIE_DELIM_DATE; s30tob64(txn->cookie_first_date ? txn->cookie_first_date >> 2 : (date.tv_sec+3) >> 2, trash.str + trash.len); trash.len += 5; } } chunk_appendf(&trash, "; path=/"); } if (s->be->cookie_domain) chunk_appendf(&trash, "; domain=%s", s->be->cookie_domain); if (s->be->ck_opts & PR_CK_HTTPONLY) chunk_appendf(&trash, "; HttpOnly"); if (s->be->ck_opts & PR_CK_SECURE) chunk_appendf(&trash, "; Secure"); if (unlikely(http_header_add_tail2(&txn->rsp, &txn->hdr_idx, trash.str, trash.len) < 0)) goto return_bad_resp; txn->flags &= ~TX_SCK_MASK; if (objt_server(s->target)->cookie && (s->flags & SN_DIRECT)) /* the server did not change, only the date was updated */ txn->flags |= TX_SCK_UPDATED; else txn->flags |= TX_SCK_INSERTED; /* Here, we will tell an eventual cache on the client side that we don't * want it to cache this reply because HTTP/1.0 caches also cache cookies ! * Some caches understand the correct form: 'no-cache="set-cookie"', but * others don't (eg: apache <= 1.3.26). So we use 'private' instead. */ if ((s->be->ck_opts & PR_CK_NOC) && (txn->flags & TX_CACHEABLE)) { txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK; if (unlikely(http_header_add_tail2(&txn->rsp, &txn->hdr_idx, "Cache-control: private", 22) < 0)) goto return_bad_resp; } } /* * Check if result will be cacheable with a cookie. * We'll block the response if security checks have caught * nasty things such as a cacheable cookie. */ if (((txn->flags & (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) == (TX_CACHEABLE | TX_CACHE_COOK | TX_SCK_PRESENT)) && (s->be->options & PR_O_CHK_CACHE)) { /* we're in presence of a cacheable response containing * a set-cookie header. We'll block it as requested by * the 'checkcache' option, and send an alert. */ if (objt_server(s->target)) objt_server(s->target)->counters.failed_secu++; s->be->be_counters.denied_resp++; s->fe->fe_counters.denied_resp++; if (s->listener->counters) s->listener->counters->denied_resp++; Alert("Blocking cacheable cookie in response from instance %s, server %s.\n", s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>"); send_log(s->be, LOG_ALERT, "Blocking cacheable cookie in response from instance %s, server %s.\n", s->be->id, objt_server(s->target) ? objt_server(s->target)->id : "<dispatch>"); goto return_srv_prx_502; } skip_filters: /* * Adjust "Connection: close" or "Connection: keep-alive" if needed. * If an "Upgrade" token is found, the header is left untouched in order * not to have to deal with some client bugs : some of them fail an upgrade * if anything but "Upgrade" is present in the Connection header. We don't * want to touch any 101 response either since it's switching to another * protocol. */ if ((txn->status != 101) && !(txn->flags & TX_HDR_CONN_UPG) && (((txn->flags & TX_CON_WANT_MSK) != TX_CON_WANT_TUN) || ((s->fe->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL || (s->be->options & PR_O_HTTP_MODE) == PR_O_HTTP_PCL))) { unsigned int want_flags = 0; if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL || (txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_SCL) { /* we want a keep-alive response here. Keep-alive header * required if either side is not 1.1. */ if (!(txn->req.flags & msg->flags & HTTP_MSGF_VER_11)) want_flags |= TX_CON_KAL_SET; } else { /* we want a close response here. Close header required if * the server is 1.1, regardless of the client. */ if (msg->flags & HTTP_MSGF_VER_11) want_flags |= TX_CON_CLO_SET; } if (want_flags != (txn->flags & (TX_CON_CLO_SET|TX_CON_KAL_SET))) http_change_connection_header(txn, msg, want_flags); } skip_header_mangling: if ((msg->flags & HTTP_MSGF_XFER_LEN) || (txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_TUN) rep->analysers |= AN_RES_HTTP_XFER_BODY; /* if the user wants to log as soon as possible, without counting * bytes from the server, then this is the right moment. We have * to temporarily assign bytes_out to log what we currently have. */ if (!LIST_ISEMPTY(&s->fe->logformat) && !(s->logs.logwait & LW_BYTES)) { s->logs.t_close = s->logs.t_data; /* to get a valid end date */ s->logs.bytes_out = txn->rsp.eoh; s->do_log(s); s->logs.bytes_out = 0; } return 1; } /* This function is an analyser which forwards response body (including chunk * sizes if any). It is called as soon as we must forward, even if we forward * zero byte. The only situation where it must not be called is when we're in * tunnel mode and we want to forward till the close. It's used both to forward * remaining data and to resync after end of body. It expects the msg_state to * be between MSG_BODY and MSG_DONE (inclusive). It returns zero if it needs to * read more data, or 1 once we can go on with next request or end the session. * * It is capable of compressing response data both in content-length mode and * in chunked mode. The state machines follows different flows depending on * whether content-length and chunked modes are used, since there are no * trailers in content-length : * * chk-mode cl-mode * ,----- BODY -----. * / \ * V size > 0 V chk-mode * .--> SIZE -------------> DATA -------------> CRLF * | | size == 0 | last byte | * | v final crlf v inspected | * | TRAILERS -----------> DONE | * | | * `----------------------------------------------' * * Compression only happens in the DATA state, and must be flushed in final * states (TRAILERS/DONE) or when leaving on missing data. Normal forwarding * is performed at once on final states for all bytes parsed, or when leaving * on missing data. */ int http_response_forward_body(struct session *s, struct channel *res, int an_bit) { struct http_txn *txn = &s->txn; struct http_msg *msg = &s->txn.rsp; static struct buffer *tmpbuf = NULL; int compressing = 0; int ret; if (unlikely(msg->msg_state < HTTP_MSG_BODY)) return 0; if ((res->flags & (CF_READ_ERROR|CF_READ_TIMEOUT|CF_WRITE_ERROR|CF_WRITE_TIMEOUT)) || ((res->flags & CF_SHUTW) && (res->to_forward || res->buf->o)) || !s->req->analysers) { /* Output closed while we were sending data. We must abort and * wake the other side up. */ msg->msg_state = HTTP_MSG_ERROR; http_resync_states(s); return 1; } /* in most states, we should abort in case of early close */ channel_auto_close(res); if (msg->sov > 0) { /* we have msg->sov which points to the first byte of message * body, and res->buf.p still points to the beginning of the * message. We forward the headers now, as we don't need them * anymore, and we want to flush them. */ b_adv(res->buf, msg->sov); msg->next -= msg->sov; msg->sov = 0; /* The previous analysers guarantee that the state is somewhere * between MSG_BODY and the first MSG_DATA. So msg->sol and * msg->next are always correct. */ if (msg->msg_state < HTTP_MSG_CHUNK_SIZE) { if (msg->flags & HTTP_MSGF_TE_CHNK) msg->msg_state = HTTP_MSG_CHUNK_SIZE; else msg->msg_state = HTTP_MSG_DATA; } } if (res->to_forward) { /* We can't process the buffer's contents yet */ res->flags |= CF_WAKE_WRITE; goto missing_data; } if (unlikely(s->comp_algo != NULL) && msg->msg_state < HTTP_MSG_TRAILERS) { /* We need a compression buffer in the DATA state to put the * output of compressed data, and in CRLF state to let the * TRAILERS state finish the job of removing the trailing CRLF. */ if (unlikely(tmpbuf == NULL)) { /* this is the first time we need the compression buffer */ tmpbuf = pool_alloc2(pool2_buffer); if (tmpbuf == NULL) goto aborted_xfer; /* no memory */ } ret = http_compression_buffer_init(s, res->buf, tmpbuf); if (ret < 0) { res->flags |= CF_WAKE_WRITE; goto missing_data; /* not enough spaces in buffers */ } compressing = 1; } while (1) { switch (msg->msg_state - HTTP_MSG_DATA) { case HTTP_MSG_DATA - HTTP_MSG_DATA: /* must still forward */ /* we may have some pending data starting at res->buf->p */ if (unlikely(s->comp_algo)) { ret = http_compression_buffer_add_data(s, res->buf, tmpbuf); if (ret < 0) goto aborted_xfer; if (msg->chunk_len) { /* input empty or output full */ if (res->buf->i > msg->next) res->flags |= CF_WAKE_WRITE; goto missing_data; } } else { if (msg->chunk_len > res->buf->i - msg->next) { /* output full */ res->flags |= CF_WAKE_WRITE; goto missing_data; } msg->next += msg->chunk_len; msg->chunk_len = 0; } /* nothing left to forward */ if (msg->flags & HTTP_MSGF_TE_CHNK) { msg->msg_state = HTTP_MSG_CHUNK_CRLF; } else { msg->msg_state = HTTP_MSG_DONE; break; } /* fall through for HTTP_MSG_CHUNK_CRLF */ case HTTP_MSG_CHUNK_CRLF - HTTP_MSG_DATA: /* we want the CRLF after the data */ ret = http_skip_chunk_crlf(msg); if (ret == 0) goto missing_data; else if (ret < 0) { if (msg->err_pos >= 0) http_capture_bad_message(&s->be->invalid_rep, s, msg, HTTP_MSG_CHUNK_CRLF, s->fe); goto return_bad_res; } /* we're in MSG_CHUNK_SIZE now, fall through */ case HTTP_MSG_CHUNK_SIZE - HTTP_MSG_DATA: /* read the chunk size and assign it to ->chunk_len, then * set ->next to point to the body and switch to DATA or * TRAILERS state. */ ret = http_parse_chunk_size(msg); if (ret == 0) goto missing_data; else if (ret < 0) { if (msg->err_pos >= 0) http_capture_bad_message(&s->be->invalid_rep, s, msg, HTTP_MSG_CHUNK_SIZE, s->fe); goto return_bad_res; } /* otherwise we're in HTTP_MSG_DATA or HTTP_MSG_TRAILERS state */ break; case HTTP_MSG_TRAILERS - HTTP_MSG_DATA: if (unlikely(compressing)) { /* we need to flush output contents before syncing FSMs */ http_compression_buffer_end(s, &res->buf, &tmpbuf, 1); compressing = 0; } ret = http_forward_trailers(msg); if (ret == 0) goto missing_data; else if (ret < 0) { if (msg->err_pos >= 0) http_capture_bad_message(&s->be->invalid_rep, s, msg, HTTP_MSG_TRAILERS, s->fe); goto return_bad_res; } /* we're in HTTP_MSG_DONE now, fall through */ default: /* other states, DONE...TUNNEL */ if (unlikely(compressing)) { /* we need to flush output contents before syncing FSMs */ http_compression_buffer_end(s, &res->buf, &tmpbuf, 1); compressing = 0; } /* we may have some pending data starting at res->buf->p * such as a last chunk of data or trailers. */ b_adv(res->buf, msg->next); msg->next = 0; ret = msg->msg_state; /* for keep-alive we don't want to forward closes on DONE */ if ((txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL || (txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_SCL) channel_dont_close(res); if (http_resync_states(s)) { /* some state changes occurred, maybe the analyser * was disabled too. */ if (unlikely(msg->msg_state == HTTP_MSG_ERROR)) { if (res->flags & CF_SHUTW) { /* response errors are most likely due to * the client aborting the transfer. */ goto aborted_xfer; } if (msg->err_pos >= 0) http_capture_bad_message(&s->be->invalid_rep, s, msg, ret, s->fe); goto return_bad_res; } return 1; } return 0; } } missing_data: /* we may have some pending data starting at res->buf->p */ if (unlikely(compressing)) { http_compression_buffer_end(s, &res->buf, &tmpbuf, msg->msg_state >= HTTP_MSG_TRAILERS); compressing = 0; } if ((s->comp_algo == NULL || msg->msg_state >= HTTP_MSG_TRAILERS)) { b_adv(res->buf, msg->next); msg->next = 0; msg->chunk_len -= channel_forward(res, msg->chunk_len); } if (res->flags & CF_SHUTW) goto aborted_xfer; /* stop waiting for data if the input is closed before the end. If the * client side was already closed, it means that the client has aborted, * so we don't want to count this as a server abort. Otherwise it's a * server abort. */ if (res->flags & CF_SHUTR) { if ((s->req->flags & (CF_SHUTR|CF_SHUTW)) == (CF_SHUTR|CF_SHUTW)) goto aborted_xfer; if (!(s->flags & SN_ERR_MASK)) s->flags |= SN_ERR_SRVCL; s->be->be_counters.srv_aborts++; if (objt_server(s->target)) objt_server(s->target)->counters.srv_aborts++; goto return_bad_res_stats_ok; } /* we need to obey the req analyser, so if it leaves, we must too */ if (!s->req->analysers) goto return_bad_res; /* When TE: chunked is used, we need to get there again to parse remaining * chunks even if the server has closed, so we don't want to set CF_DONTCLOSE. * Similarly, with keep-alive on the client side, we don't want to forward a * close. */ if ((msg->flags & HTTP_MSGF_TE_CHNK) || s->comp_algo || (txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_KAL || (txn->flags & TX_CON_WANT_MSK) == TX_CON_WANT_SCL) channel_dont_close(res); /* We know that more data are expected, but we couldn't send more that * what we did. So we always set the CF_EXPECT_MORE flag so that the * system knows it must not set a PUSH on this first part. Interactive * modes are already handled by the stream sock layer. We must not do * this in content-length mode because it could present the MSG_MORE * flag with the last block of forwarded data, which would cause an * additional delay to be observed by the receiver. */ if ((msg->flags & HTTP_MSGF_TE_CHNK) || s->comp_algo) res->flags |= CF_EXPECT_MORE; /* the session handler will take care of timeouts and errors */ return 0; return_bad_res: /* let's centralize all bad responses */ s->be->be_counters.failed_resp++; if (objt_server(s->target)) objt_server(s->target)->counters.failed_resp++; return_bad_res_stats_ok: if (unlikely(compressing)) { http_compression_buffer_end(s, &res->buf, &tmpbuf, msg->msg_state >= HTTP_MSG_TRAILERS); compressing = 0; } /* we may have some pending data starting at res->buf->p */ if (s->comp_algo == NULL) { b_adv(res->buf, msg->next); msg->next = 0; } txn->rsp.msg_state = HTTP_MSG_ERROR; /* don't send any error message as we're in the body */ stream_int_retnclose(res->cons, NULL); res->analysers = 0; s->req->analysers = 0; /* we're in data phase, we want to abort both directions */ if (objt_server(s->target)) health_adjust(objt_server(s->target), HANA_STATUS_HTTP_HDRRSP); if (!(s->flags & SN_ERR_MASK)) s->flags |= SN_ERR_PRXCOND; if (!(s->flags & SN_FINST_MASK)) s->flags |= SN_FINST_D; return 0; aborted_xfer: if (unlikely(compressing)) { http_compression_buffer_end(s, &res->buf, &tmpbuf, msg->msg_state >= HTTP_MSG_TRAILERS); compressing = 0; } txn->rsp.msg_state = HTTP_MSG_ERROR; /* don't send any error message as we're in the body */ stream_int_retnclose(res->cons, NULL); res->analysers = 0; s->req->analysers = 0; /* we're in data phase, we want to abort both directions */ s->fe->fe_counters.cli_aborts++; s->be->be_counters.cli_aborts++; if (objt_server(s->target)) objt_server(s->target)->counters.cli_aborts++; if (!(s->flags & SN_ERR_MASK)) s->flags |= SN_ERR_CLICL; if (!(s->flags & SN_FINST_MASK)) s->flags |= SN_FINST_D; return 0; } /* Iterate the same filter through all request headers. * Returns 1 if this filter can be stopped upon return, otherwise 0. * Since it can manage the switch to another backend, it updates the per-proxy * DENY stats. */ int apply_filter_to_req_headers(struct session *s, struct channel *req, struct hdr_exp *exp) { char *cur_ptr, *cur_end, *cur_next; int cur_idx, old_idx, last_hdr; struct http_txn *txn = &s->txn; struct hdr_idx_elem *cur_hdr; int delta; last_hdr = 0; cur_next = req->buf->p + hdr_idx_first_pos(&txn->hdr_idx); old_idx = 0; while (!last_hdr) { if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT))) return 1; else if (unlikely(txn->flags & TX_CLALLOW) && (exp->action == ACT_ALLOW || exp->action == ACT_DENY || exp->action == ACT_TARPIT)) return 0; cur_idx = txn->hdr_idx.v[old_idx].next; if (!cur_idx) break; cur_hdr = &txn->hdr_idx.v[cur_idx]; cur_ptr = cur_next; cur_end = cur_ptr + cur_hdr->len; cur_next = cur_end + cur_hdr->cr + 1; /* Now we have one header between cur_ptr and cur_end, * and the next header starts at cur_next. */ if (regex_exec_match2(exp->preg, cur_ptr, cur_end-cur_ptr, MAX_MATCH, pmatch)) { switch (exp->action) { case ACT_SETBE: /* It is not possible to jump a second time. * FIXME: should we return an HTTP/500 here so that * the admin knows there's a problem ? */ if (s->be != s->fe) break; /* Swithing Proxy */ session_set_backend(s, (struct proxy *)exp->replace); last_hdr = 1; break; case ACT_ALLOW: txn->flags |= TX_CLALLOW; last_hdr = 1; break; case ACT_DENY: txn->flags |= TX_CLDENY; last_hdr = 1; break; case ACT_TARPIT: txn->flags |= TX_CLTARPIT; last_hdr = 1; break; case ACT_REPLACE: trash.len = exp_replace(trash.str, trash.size, cur_ptr, exp->replace, pmatch); if (trash.len < 0) return -1; delta = buffer_replace2(req->buf, cur_ptr, cur_end, trash.str, trash.len); /* FIXME: if the user adds a newline in the replacement, the * index will not be recalculated for now, and the new line * will not be counted as a new header. */ cur_end += delta; cur_next += delta; cur_hdr->len += delta; http_msg_move_end(&txn->req, delta); break; case ACT_REMOVE: delta = buffer_replace2(req->buf, cur_ptr, cur_next, NULL, 0); cur_next += delta; http_msg_move_end(&txn->req, delta); txn->hdr_idx.v[old_idx].next = cur_hdr->next; txn->hdr_idx.used--; cur_hdr->len = 0; cur_end = NULL; /* null-term has been rewritten */ cur_idx = old_idx; break; } } /* keep the link from this header to next one in case of later * removal of next header. */ old_idx = cur_idx; } return 0; } /* Apply the filter to the request line. * Returns 0 if nothing has been done, 1 if the filter has been applied, * or -1 if a replacement resulted in an invalid request line. * Since it can manage the switch to another backend, it updates the per-proxy * DENY stats. */ int apply_filter_to_req_line(struct session *s, struct channel *req, struct hdr_exp *exp) { char *cur_ptr, *cur_end; int done; struct http_txn *txn = &s->txn; int delta; if (unlikely(txn->flags & (TX_CLDENY | TX_CLTARPIT))) return 1; else if (unlikely(txn->flags & TX_CLALLOW) && (exp->action == ACT_ALLOW || exp->action == ACT_DENY || exp->action == ACT_TARPIT)) return 0; else if (exp->action == ACT_REMOVE) return 0; done = 0; cur_ptr = req->buf->p; cur_end = cur_ptr + txn->req.sl.rq.l; /* Now we have the request line between cur_ptr and cur_end */ if (regex_exec_match2(exp->preg, cur_ptr, cur_end-cur_ptr, MAX_MATCH, pmatch)) { switch (exp->action) { case ACT_SETBE: /* It is not possible to jump a second time. * FIXME: should we return an HTTP/500 here so that * the admin knows there's a problem ? */ if (s->be != s->fe) break; /* Swithing Proxy */ session_set_backend(s, (struct proxy *)exp->replace); done = 1; break; case ACT_ALLOW: txn->flags |= TX_CLALLOW; done = 1; break; case ACT_DENY: txn->flags |= TX_CLDENY; done = 1; break; case ACT_TARPIT: txn->flags |= TX_CLTARPIT; done = 1; break; case ACT_REPLACE: trash.len = exp_replace(trash.str, trash.size, cur_ptr, exp->replace, pmatch); if (trash.len < 0) return -1; delta = buffer_replace2(req->buf, cur_ptr, cur_end, trash.str, trash.len); /* FIXME: if the user adds a newline in the replacement, the * index will not be recalculated for now, and the new line * will not be counted as a new header. */ http_msg_move_end(&txn->req, delta); cur_end += delta; cur_end = (char *)http_parse_reqline(&txn->req, HTTP_MSG_RQMETH, cur_ptr, cur_end + 1, NULL, NULL); if (unlikely(!cur_end)) return -1; /* we have a full request and we know that we have either a CR * or an LF at <ptr>. */ txn->meth = find_http_meth(cur_ptr, txn->req.sl.rq.m_l); hdr_idx_set_start(&txn->hdr_idx, txn->req.sl.rq.l, *cur_end == '\r'); /* there is no point trying this regex on headers */ return 1; } } return done; } /* * Apply all the req filters of proxy <px> to all headers in buffer <req> of session <s>. * Returns 0 if everything is alright, or -1 in case a replacement lead to an * unparsable request. Since it can manage the switch to another backend, it * updates the per-proxy DENY stats. */ int apply_filters_to_request(struct session *s, struct channel *req, struct proxy *px) { struct http_txn *txn = &s->txn; struct hdr_exp *exp; for (exp = px->req_exp; exp; exp = exp->next) { int ret; /* * The interleaving of transformations and verdicts * makes it difficult to decide to continue or stop * the evaluation. */ if (txn->flags & (TX_CLDENY|TX_CLTARPIT)) break; if ((txn->flags & TX_CLALLOW) && (exp->action == ACT_ALLOW || exp->action == ACT_DENY || exp->action == ACT_TARPIT || exp->action == ACT_PASS)) continue; /* if this filter had a condition, evaluate it now and skip to * next filter if the condition does not match. */ if (exp->cond) { ret = acl_exec_cond(exp->cond, px, s, txn, SMP_OPT_DIR_REQ|SMP_OPT_FINAL); ret = acl_pass(ret); if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS) ret = !ret; if (!ret) continue; } /* Apply the filter to the request line. */ ret = apply_filter_to_req_line(s, req, exp); if (unlikely(ret < 0)) return -1; if (likely(ret == 0)) { /* The filter did not match the request, it can be * iterated through all headers. */ apply_filter_to_req_headers(s, req, exp); } } return 0; } /* * Try to retrieve the server associated to the appsession. * If the server is found, it's assigned to the session. */ void manage_client_side_appsession(struct session *s, const char *buf, int len) { struct http_txn *txn = &s->txn; appsess *asession = NULL; char *sessid_temp = NULL; if (len > s->be->appsession_len) { len = s->be->appsession_len; } if (s->be->options2 & PR_O2_AS_REQL) { /* request-learn option is enabled : store the sessid in the session for future use */ if (txn->sessid != NULL) { /* free previously allocated memory as we don't need the session id found in the URL anymore */ pool_free2(apools.sessid, txn->sessid); } if ((txn->sessid = pool_alloc2(apools.sessid)) == NULL) { Alert("Not enough memory process_cli():asession->sessid:malloc().\n"); send_log(s->be, LOG_ALERT, "Not enough memory process_cli():asession->sessid:malloc().\n"); return; } memcpy(txn->sessid, buf, len); txn->sessid[len] = 0; } if ((sessid_temp = pool_alloc2(apools.sessid)) == NULL) { Alert("Not enough memory process_cli():asession->sessid:malloc().\n"); send_log(s->be, LOG_ALERT, "Not enough memory process_cli():asession->sessid:malloc().\n"); return; } memcpy(sessid_temp, buf, len); sessid_temp[len] = 0; asession = appsession_hash_lookup(&(s->be->htbl_proxy), sessid_temp); /* free previously allocated memory */ pool_free2(apools.sessid, sessid_temp); if (asession != NULL) { asession->expire = tick_add_ifset(now_ms, s->be->timeout.appsession); if (!(s->be->options2 & PR_O2_AS_REQL)) asession->request_count++; if (asession->serverid != NULL) { struct server *srv = s->be->srv; while (srv) { if (strcmp(srv->id, asession->serverid) == 0) { if ((srv->state != SRV_ST_STOPPED) || (s->be->options & PR_O_PERSIST) || (s->flags & SN_FORCE_PRST)) { /* we found the server and it's usable */ txn->flags &= ~TX_CK_MASK; txn->flags |= (srv->state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN; s->flags |= SN_DIRECT | SN_ASSIGNED; s->target = &srv->obj_type; break; } else { txn->flags &= ~TX_CK_MASK; txn->flags |= TX_CK_DOWN; } } srv = srv->next; } } } } /* Find the end of a cookie value contained between <s> and <e>. It works the * same way as with headers above except that the semi-colon also ends a token. * See RFC2965 for more information. Note that it requires a valid header to * return a valid result. */ char *find_cookie_value_end(char *s, const char *e) { int quoted, qdpair; quoted = qdpair = 0; for (; s < e; s++) { if (qdpair) qdpair = 0; else if (quoted) { if (*s == '\\') qdpair = 1; else if (*s == '"') quoted = 0; } else if (*s == '"') quoted = 1; else if (*s == ',' || *s == ';') return s; } return s; } /* Delete a value in a header between delimiters <from> and <next> in buffer * <buf>. The number of characters displaced is returned, and the pointer to * the first delimiter is updated if required. The function tries as much as * possible to respect the following principles : * - replace <from> delimiter by the <next> one unless <from> points to a * colon, in which case <next> is simply removed * - set exactly one space character after the new first delimiter, unless * there are not enough characters in the block being moved to do so. * - remove unneeded spaces before the previous delimiter and after the new * one. * * It is the caller's responsibility to ensure that : * - <from> points to a valid delimiter or the colon ; * - <next> points to a valid delimiter or the final CR/LF ; * - there are non-space chars before <from> ; * - there is a CR/LF at or after <next>. */ int del_hdr_value(struct buffer *buf, char **from, char *next) { char *prev = *from; if (*prev == ':') { /* We're removing the first value, preserve the colon and add a * space if possible. */ if (!http_is_crlf[(unsigned char)*next]) next++; prev++; if (prev < next) *prev++ = ' '; while (http_is_spht[(unsigned char)*next]) next++; } else { /* Remove useless spaces before the old delimiter. */ while (http_is_spht[(unsigned char)*(prev-1)]) prev--; *from = prev; /* copy the delimiter and if possible a space if we're * not at the end of the line. */ if (!http_is_crlf[(unsigned char)*next]) { *prev++ = *next++; if (prev + 1 < next) *prev++ = ' '; while (http_is_spht[(unsigned char)*next]) next++; } } return buffer_replace2(buf, prev, next, NULL, 0); } /* * Manage client-side cookie. It can impact performance by about 2% so it is * desirable to call it only when needed. This code is quite complex because * of the multiple very crappy and ambiguous syntaxes we have to support. it * highly recommended not to touch this part without a good reason ! */ void manage_client_side_cookies(struct session *s, struct channel *req) { struct http_txn *txn = &s->txn; int preserve_hdr; int cur_idx, old_idx; char *hdr_beg, *hdr_end, *hdr_next, *del_from; char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next; /* Iterate through the headers, we start with the start line. */ old_idx = 0; hdr_next = req->buf->p + hdr_idx_first_pos(&txn->hdr_idx); while ((cur_idx = txn->hdr_idx.v[old_idx].next)) { struct hdr_idx_elem *cur_hdr; int val; cur_hdr = &txn->hdr_idx.v[cur_idx]; hdr_beg = hdr_next; hdr_end = hdr_beg + cur_hdr->len; hdr_next = hdr_end + cur_hdr->cr + 1; /* We have one full header between hdr_beg and hdr_end, and the * next header starts at hdr_next. We're only interested in * "Cookie:" headers. */ val = http_header_match2(hdr_beg, hdr_end, "Cookie", 6); if (!val) { old_idx = cur_idx; continue; } del_from = NULL; /* nothing to be deleted */ preserve_hdr = 0; /* assume we may kill the whole header */ /* Now look for cookies. Conforming to RFC2109, we have to support * attributes whose name begin with a '$', and associate them with * the right cookie, if we want to delete this cookie. * So there are 3 cases for each cookie read : * 1) it's a special attribute, beginning with a '$' : ignore it. * 2) it's a server id cookie that we *MAY* want to delete : save * some pointers on it (last semi-colon, beginning of cookie...) * 3) it's an application cookie : we *MAY* have to delete a previous * "special" cookie. * At the end of loop, if a "special" cookie remains, we may have to * remove it. If no application cookie persists in the header, we * *MUST* delete it. * * Note: RFC2965 is unclear about the processing of spaces around * the equal sign in the ATTR=VALUE form. A careful inspection of * the RFC explicitly allows spaces before it, and not within the * tokens (attrs or values). An inspection of RFC2109 allows that * too but section 10.1.3 lets one think that spaces may be allowed * after the equal sign too, resulting in some (rare) buggy * implementations trying to do that. So let's do what servers do. * Latest ietf draft forbids spaces all around. Also, earlier RFCs * allowed quoted strings in values, with any possible character * after a backslash, including control chars and delimitors, which * causes parsing to become ambiguous. Browsers also allow spaces * within values even without quotes. * * We have to keep multiple pointers in order to support cookie * removal at the beginning, middle or end of header without * corrupting the header. All of these headers are valid : * * Cookie:NAME1=VALUE1;NAME2=VALUE2;NAME3=VALUE3\r\n * Cookie:NAME1=VALUE1;NAME2_ONLY ;NAME3=VALUE3\r\n * Cookie: NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3\r\n * | | | | | | | | | * | | | | | | | | hdr_end <--+ * | | | | | | | +--> next * | | | | | | +----> val_end * | | | | | +-----------> val_beg * | | | | +--------------> equal * | | | +----------------> att_end * | | +---------------------> att_beg * | +--------------------------> prev * +--------------------------------> hdr_beg */ for (prev = hdr_beg + 6; prev < hdr_end; prev = next) { /* Iterate through all cookies on this line */ /* find att_beg */ att_beg = prev + 1; while (att_beg < hdr_end && http_is_spht[(unsigned char)*att_beg]) att_beg++; /* find att_end : this is the first character after the last non * space before the equal. It may be equal to hdr_end. */ equal = att_end = att_beg; while (equal < hdr_end) { if (*equal == '=' || *equal == ',' || *equal == ';') break; if (http_is_spht[(unsigned char)*equal++]) continue; att_end = equal; } /* here, <equal> points to '=', a delimitor or the end. <att_end> * is between <att_beg> and <equal>, both may be identical. */ /* look for end of cookie if there is an equal sign */ if (equal < hdr_end && *equal == '=') { /* look for the beginning of the value */ val_beg = equal + 1; while (val_beg < hdr_end && http_is_spht[(unsigned char)*val_beg]) val_beg++; /* find the end of the value, respecting quotes */ next = find_cookie_value_end(val_beg, hdr_end); /* make val_end point to the first white space or delimitor after the value */ val_end = next; while (val_end > val_beg && http_is_spht[(unsigned char)*(val_end - 1)]) val_end--; } else { val_beg = val_end = next = equal; } /* We have nothing to do with attributes beginning with '$'. However, * they will automatically be removed if a header before them is removed, * since they're supposed to be linked together. */ if (*att_beg == '$') continue; /* Ignore cookies with no equal sign */ if (equal == next) { /* This is not our cookie, so we must preserve it. But if we already * scheduled another cookie for removal, we cannot remove the * complete header, but we can remove the previous block itself. */ preserve_hdr = 1; if (del_from != NULL) { int delta = del_hdr_value(req->buf, &del_from, prev); val_end += delta; next += delta; hdr_end += delta; hdr_next += delta; cur_hdr->len += delta; http_msg_move_end(&txn->req, delta); prev = del_from; del_from = NULL; } continue; } /* if there are spaces around the equal sign, we need to * strip them otherwise we'll get trouble for cookie captures, * or even for rewrites. Since this happens extremely rarely, * it does not hurt performance. */ if (unlikely(att_end != equal || val_beg > equal + 1)) { int stripped_before = 0; int stripped_after = 0; if (att_end != equal) { stripped_before = buffer_replace2(req->buf, att_end, equal, NULL, 0); equal += stripped_before; val_beg += stripped_before; } if (val_beg > equal + 1) { stripped_after = buffer_replace2(req->buf, equal + 1, val_beg, NULL, 0); val_beg += stripped_after; stripped_before += stripped_after; } val_end += stripped_before; next += stripped_before; hdr_end += stripped_before; hdr_next += stripped_before; cur_hdr->len += stripped_before; http_msg_move_end(&txn->req, stripped_before); } /* now everything is as on the diagram above */ /* First, let's see if we want to capture this cookie. We check * that we don't already have a client side cookie, because we * can only capture one. Also as an optimisation, we ignore * cookies shorter than the declared name. */ if (s->fe->capture_name != NULL && txn->cli_cookie == NULL && (val_end - att_beg >= s->fe->capture_namelen) && memcmp(att_beg, s->fe->capture_name, s->fe->capture_namelen) == 0) { int log_len = val_end - att_beg; if ((txn->cli_cookie = pool_alloc2(pool2_capture)) == NULL) { Alert("HTTP logging : out of memory.\n"); } else { if (log_len > s->fe->capture_len) log_len = s->fe->capture_len; memcpy(txn->cli_cookie, att_beg, log_len); txn->cli_cookie[log_len] = 0; } } /* Persistence cookies in passive, rewrite or insert mode have the * following form : * * Cookie: NAME=SRV[|<lastseen>[|<firstseen>]] * * For cookies in prefix mode, the form is : * * Cookie: NAME=SRV~VALUE */ if ((att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) && (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) { struct server *srv = s->be->srv; char *delim; /* if we're in cookie prefix mode, we'll search the delimitor so that we * have the server ID between val_beg and delim, and the original cookie between * delim+1 and val_end. Otherwise, delim==val_end : * * Cookie: NAME=SRV; # in all but prefix modes * Cookie: NAME=SRV~OPAQUE ; # in prefix mode * | || || | |+-> next * | || || | +--> val_end * | || || +---------> delim * | || |+------------> val_beg * | || +-------------> att_end = equal * | |+-----------------> att_beg * | +------------------> prev * +-------------------------> hdr_beg */ if (s->be->ck_opts & PR_CK_PFX) { for (delim = val_beg; delim < val_end; delim++) if (*delim == COOKIE_DELIM) break; } else { char *vbar1; delim = val_end; /* Now check if the cookie contains a date field, which would * appear after a vertical bar ('|') just after the server name * and before the delimiter. */ vbar1 = memchr(val_beg, COOKIE_DELIM_DATE, val_end - val_beg); if (vbar1) { /* OK, so left of the bar is the server's cookie and * right is the last seen date. It is a base64 encoded * 30-bit value representing the UNIX date since the * epoch in 4-second quantities. */ int val; delim = vbar1++; if (val_end - vbar1 >= 5) { val = b64tos30(vbar1); if (val > 0) txn->cookie_last_date = val << 2; } /* look for a second vertical bar */ vbar1 = memchr(vbar1, COOKIE_DELIM_DATE, val_end - vbar1); if (vbar1 && (val_end - vbar1 > 5)) { val = b64tos30(vbar1 + 1); if (val > 0) txn->cookie_first_date = val << 2; } } } /* if the cookie has an expiration date and the proxy wants to check * it, then we do that now. We first check if the cookie is too old, * then only if it has expired. We detect strict overflow because the * time resolution here is not great (4 seconds). Cookies with dates * in the future are ignored if their offset is beyond one day. This * allows an admin to fix timezone issues without expiring everyone * and at the same time avoids keeping unwanted side effects for too * long. */ if (txn->cookie_first_date && s->be->cookie_maxlife && (((signed)(date.tv_sec - txn->cookie_first_date) > (signed)s->be->cookie_maxlife) || ((signed)(txn->cookie_first_date - date.tv_sec) > 86400))) { txn->flags &= ~TX_CK_MASK; txn->flags |= TX_CK_OLD; delim = val_beg; // let's pretend we have not found the cookie txn->cookie_first_date = 0; txn->cookie_last_date = 0; } else if (txn->cookie_last_date && s->be->cookie_maxidle && (((signed)(date.tv_sec - txn->cookie_last_date) > (signed)s->be->cookie_maxidle) || ((signed)(txn->cookie_last_date - date.tv_sec) > 86400))) { txn->flags &= ~TX_CK_MASK; txn->flags |= TX_CK_EXPIRED; delim = val_beg; // let's pretend we have not found the cookie txn->cookie_first_date = 0; txn->cookie_last_date = 0; } /* Here, we'll look for the first running server which supports the cookie. * This allows to share a same cookie between several servers, for example * to dedicate backup servers to specific servers only. * However, to prevent clients from sticking to cookie-less backup server * when they have incidentely learned an empty cookie, we simply ignore * empty cookies and mark them as invalid. * The same behaviour is applied when persistence must be ignored. */ if ((delim == val_beg) || (s->flags & (SN_IGNORE_PRST | SN_ASSIGNED))) srv = NULL; while (srv) { if (srv->cookie && (srv->cklen == delim - val_beg) && !memcmp(val_beg, srv->cookie, delim - val_beg)) { if ((srv->state != SRV_ST_STOPPED) || (s->be->options & PR_O_PERSIST) || (s->flags & SN_FORCE_PRST)) { /* we found the server and we can use it */ txn->flags &= ~TX_CK_MASK; txn->flags |= (srv->state != SRV_ST_STOPPED) ? TX_CK_VALID : TX_CK_DOWN; s->flags |= SN_DIRECT | SN_ASSIGNED; s->target = &srv->obj_type; break; } else { /* we found a server, but it's down, * mark it as such and go on in case * another one is available. */ txn->flags &= ~TX_CK_MASK; txn->flags |= TX_CK_DOWN; } } srv = srv->next; } if (!srv && !(txn->flags & (TX_CK_DOWN|TX_CK_EXPIRED|TX_CK_OLD))) { /* no server matched this cookie or we deliberately skipped it */ txn->flags &= ~TX_CK_MASK; if ((s->flags & (SN_IGNORE_PRST | SN_ASSIGNED))) txn->flags |= TX_CK_UNUSED; else txn->flags |= TX_CK_INVALID; } /* depending on the cookie mode, we may have to either : * - delete the complete cookie if we're in insert+indirect mode, so that * the server never sees it ; * - remove the server id from the cookie value, and tag the cookie as an * application cookie so that it does not get accidentely removed later, * if we're in cookie prefix mode */ if ((s->be->ck_opts & PR_CK_PFX) && (delim != val_end)) { int delta; /* negative */ delta = buffer_replace2(req->buf, val_beg, delim + 1, NULL, 0); val_end += delta; next += delta; hdr_end += delta; hdr_next += delta; cur_hdr->len += delta; http_msg_move_end(&txn->req, delta); del_from = NULL; preserve_hdr = 1; /* we want to keep this cookie */ } else if (del_from == NULL && (s->be->ck_opts & (PR_CK_INS | PR_CK_IND)) == (PR_CK_INS | PR_CK_IND)) { del_from = prev; } } else { /* This is not our cookie, so we must preserve it. But if we already * scheduled another cookie for removal, we cannot remove the * complete header, but we can remove the previous block itself. */ preserve_hdr = 1; if (del_from != NULL) { int delta = del_hdr_value(req->buf, &del_from, prev); if (att_beg >= del_from) att_beg += delta; if (att_end >= del_from) att_end += delta; val_beg += delta; val_end += delta; next += delta; hdr_end += delta; hdr_next += delta; cur_hdr->len += delta; http_msg_move_end(&txn->req, delta); prev = del_from; del_from = NULL; } } /* Look for the appsession cookie unless persistence must be ignored */ if (!(s->flags & SN_IGNORE_PRST) && (s->be->appsession_name != NULL)) { int cmp_len, value_len; char *value_begin; if (s->be->options2 & PR_O2_AS_PFX) { cmp_len = MIN(val_end - att_beg, s->be->appsession_name_len); value_begin = att_beg + s->be->appsession_name_len; value_len = val_end - att_beg - s->be->appsession_name_len; } else { cmp_len = att_end - att_beg; value_begin = val_beg; value_len = val_end - val_beg; } /* let's see if the cookie is our appcookie */ if (cmp_len == s->be->appsession_name_len && memcmp(att_beg, s->be->appsession_name, cmp_len) == 0) { manage_client_side_appsession(s, value_begin, value_len); } } /* continue with next cookie on this header line */ att_beg = next; } /* for each cookie */ /* There are no more cookies on this line. * We may still have one (or several) marked for deletion at the * end of the line. We must do this now in two ways : * - if some cookies must be preserved, we only delete from the * mark to the end of line ; * - if nothing needs to be preserved, simply delete the whole header */ if (del_from) { int delta; if (preserve_hdr) { delta = del_hdr_value(req->buf, &del_from, hdr_end); hdr_end = del_from; cur_hdr->len += delta; } else { delta = buffer_replace2(req->buf, hdr_beg, hdr_next, NULL, 0); /* FIXME: this should be a separate function */ txn->hdr_idx.v[old_idx].next = cur_hdr->next; txn->hdr_idx.used--; cur_hdr->len = 0; cur_idx = old_idx; } hdr_next += delta; http_msg_move_end(&txn->req, delta); } /* check next header */ old_idx = cur_idx; } } /* Iterate the same filter through all response headers contained in <rtr>. * Returns 1 if this filter can be stopped upon return, otherwise 0. */ int apply_filter_to_resp_headers(struct session *s, struct channel *rtr, struct hdr_exp *exp) { char *cur_ptr, *cur_end, *cur_next; int cur_idx, old_idx, last_hdr; struct http_txn *txn = &s->txn; struct hdr_idx_elem *cur_hdr; int delta; last_hdr = 0; cur_next = rtr->buf->p + hdr_idx_first_pos(&txn->hdr_idx); old_idx = 0; while (!last_hdr) { if (unlikely(txn->flags & TX_SVDENY)) return 1; else if (unlikely(txn->flags & TX_SVALLOW) && (exp->action == ACT_ALLOW || exp->action == ACT_DENY)) return 0; cur_idx = txn->hdr_idx.v[old_idx].next; if (!cur_idx) break; cur_hdr = &txn->hdr_idx.v[cur_idx]; cur_ptr = cur_next; cur_end = cur_ptr + cur_hdr->len; cur_next = cur_end + cur_hdr->cr + 1; /* Now we have one header between cur_ptr and cur_end, * and the next header starts at cur_next. */ if (regex_exec_match2(exp->preg, cur_ptr, cur_end-cur_ptr, MAX_MATCH, pmatch)) { switch (exp->action) { case ACT_ALLOW: txn->flags |= TX_SVALLOW; last_hdr = 1; break; case ACT_DENY: txn->flags |= TX_SVDENY; last_hdr = 1; break; case ACT_REPLACE: trash.len = exp_replace(trash.str, trash.size, cur_ptr, exp->replace, pmatch); if (trash.len < 0) return -1; delta = buffer_replace2(rtr->buf, cur_ptr, cur_end, trash.str, trash.len); /* FIXME: if the user adds a newline in the replacement, the * index will not be recalculated for now, and the new line * will not be counted as a new header. */ cur_end += delta; cur_next += delta; cur_hdr->len += delta; http_msg_move_end(&txn->rsp, delta); break; case ACT_REMOVE: delta = buffer_replace2(rtr->buf, cur_ptr, cur_next, NULL, 0); cur_next += delta; http_msg_move_end(&txn->rsp, delta); txn->hdr_idx.v[old_idx].next = cur_hdr->next; txn->hdr_idx.used--; cur_hdr->len = 0; cur_end = NULL; /* null-term has been rewritten */ cur_idx = old_idx; break; } } /* keep the link from this header to next one in case of later * removal of next header. */ old_idx = cur_idx; } return 0; } /* Apply the filter to the status line in the response buffer <rtr>. * Returns 0 if nothing has been done, 1 if the filter has been applied, * or -1 if a replacement resulted in an invalid status line. */ int apply_filter_to_sts_line(struct session *s, struct channel *rtr, struct hdr_exp *exp) { char *cur_ptr, *cur_end; int done; struct http_txn *txn = &s->txn; int delta; if (unlikely(txn->flags & TX_SVDENY)) return 1; else if (unlikely(txn->flags & TX_SVALLOW) && (exp->action == ACT_ALLOW || exp->action == ACT_DENY)) return 0; else if (exp->action == ACT_REMOVE) return 0; done = 0; cur_ptr = rtr->buf->p; cur_end = cur_ptr + txn->rsp.sl.st.l; /* Now we have the status line between cur_ptr and cur_end */ if (regex_exec_match2(exp->preg, cur_ptr, cur_end-cur_ptr, MAX_MATCH, pmatch)) { switch (exp->action) { case ACT_ALLOW: txn->flags |= TX_SVALLOW; done = 1; break; case ACT_DENY: txn->flags |= TX_SVDENY; done = 1; break; case ACT_REPLACE: trash.len = exp_replace(trash.str, trash.size, cur_ptr, exp->replace, pmatch); if (trash.len < 0) return -1; delta = buffer_replace2(rtr->buf, cur_ptr, cur_end, trash.str, trash.len); /* FIXME: if the user adds a newline in the replacement, the * index will not be recalculated for now, and the new line * will not be counted as a new header. */ http_msg_move_end(&txn->rsp, delta); cur_end += delta; cur_end = (char *)http_parse_stsline(&txn->rsp, HTTP_MSG_RPVER, cur_ptr, cur_end + 1, NULL, NULL); if (unlikely(!cur_end)) return -1; /* we have a full respnse and we know that we have either a CR * or an LF at <ptr>. */ txn->status = strl2ui(rtr->buf->p + txn->rsp.sl.st.c, txn->rsp.sl.st.c_l); hdr_idx_set_start(&txn->hdr_idx, txn->rsp.sl.st.l, *cur_end == '\r'); /* there is no point trying this regex on headers */ return 1; } } return done; } /* * Apply all the resp filters of proxy <px> to all headers in buffer <rtr> of session <s>. * Returns 0 if everything is alright, or -1 in case a replacement lead to an * unparsable response. */ int apply_filters_to_response(struct session *s, struct channel *rtr, struct proxy *px) { struct http_txn *txn = &s->txn; struct hdr_exp *exp; for (exp = px->rsp_exp; exp; exp = exp->next) { int ret; /* * The interleaving of transformations and verdicts * makes it difficult to decide to continue or stop * the evaluation. */ if (txn->flags & TX_SVDENY) break; if ((txn->flags & TX_SVALLOW) && (exp->action == ACT_ALLOW || exp->action == ACT_DENY || exp->action == ACT_PASS)) { exp = exp->next; continue; } /* if this filter had a condition, evaluate it now and skip to * next filter if the condition does not match. */ if (exp->cond) { ret = acl_exec_cond(exp->cond, px, s, txn, SMP_OPT_DIR_RES|SMP_OPT_FINAL); ret = acl_pass(ret); if (((struct acl_cond *)exp->cond)->pol == ACL_COND_UNLESS) ret = !ret; if (!ret) continue; } /* Apply the filter to the status line. */ ret = apply_filter_to_sts_line(s, rtr, exp); if (unlikely(ret < 0)) return -1; if (likely(ret == 0)) { /* The filter did not match the response, it can be * iterated through all headers. */ if (unlikely(apply_filter_to_resp_headers(s, rtr, exp) < 0)) return -1; } } return 0; } /* * Manage server-side cookies. It can impact performance by about 2% so it is * desirable to call it only when needed. This function is also used when we * just need to know if there is a cookie (eg: for check-cache). */ void manage_server_side_cookies(struct session *s, struct channel *res) { struct http_txn *txn = &s->txn; struct server *srv; int is_cookie2; int cur_idx, old_idx, delta; char *hdr_beg, *hdr_end, *hdr_next; char *prev, *att_beg, *att_end, *equal, *val_beg, *val_end, *next; /* Iterate through the headers. * we start with the start line. */ old_idx = 0; hdr_next = res->buf->p + hdr_idx_first_pos(&txn->hdr_idx); while ((cur_idx = txn->hdr_idx.v[old_idx].next)) { struct hdr_idx_elem *cur_hdr; int val; cur_hdr = &txn->hdr_idx.v[cur_idx]; hdr_beg = hdr_next; hdr_end = hdr_beg + cur_hdr->len; hdr_next = hdr_end + cur_hdr->cr + 1; /* We have one full header between hdr_beg and hdr_end, and the * next header starts at hdr_next. We're only interested in * "Set-Cookie" and "Set-Cookie2" headers. */ is_cookie2 = 0; prev = hdr_beg + 10; val = http_header_match2(hdr_beg, hdr_end, "Set-Cookie", 10); if (!val) { val = http_header_match2(hdr_beg, hdr_end, "Set-Cookie2", 11); if (!val) { old_idx = cur_idx; continue; } is_cookie2 = 1; prev = hdr_beg + 11; } /* OK, right now we know we have a Set-Cookie* at hdr_beg, and * <prev> points to the colon. */ txn->flags |= TX_SCK_PRESENT; /* Maybe we only wanted to see if there was a Set-Cookie (eg: * check-cache is enabled) and we are not interested in checking * them. Warning, the cookie capture is declared in the frontend. */ if (s->be->cookie_name == NULL && s->be->appsession_name == NULL && s->fe->capture_name == NULL) return; /* OK so now we know we have to process this response cookie. * The format of the Set-Cookie header is slightly different * from the format of the Cookie header in that it does not * support the comma as a cookie delimiter (thus the header * cannot be folded) because the Expires attribute described in * the original Netscape's spec may contain an unquoted date * with a comma inside. We have to live with this because * many browsers don't support Max-Age and some browsers don't * support quoted strings. However the Set-Cookie2 header is * clean. * * We have to keep multiple pointers in order to support cookie * removal at the beginning, middle or end of header without * corrupting the header (in case of set-cookie2). A special * pointer, <scav> points to the beginning of the set-cookie-av * fields after the first semi-colon. The <next> pointer points * either to the end of line (set-cookie) or next unquoted comma * (set-cookie2). All of these headers are valid : * * Set-Cookie: NAME1 = VALUE 1 ; Secure; Path="/"\r\n * Set-Cookie:NAME=VALUE; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT\r\n * Set-Cookie: NAME = VALUE ; Secure; Expires=Thu, 01-Jan-1970 00:00:01 GMT\r\n * Set-Cookie2: NAME1 = VALUE 1 ; Max-Age=0, NAME2=VALUE2; Discard\r\n * | | | | | | | | | | * | | | | | | | | +-> next hdr_end <--+ * | | | | | | | +------------> scav * | | | | | | +--------------> val_end * | | | | | +--------------------> val_beg * | | | | +----------------------> equal * | | | +------------------------> att_end * | | +----------------------------> att_beg * | +------------------------------> prev * +-----------------------------------------> hdr_beg */ for (; prev < hdr_end; prev = next) { /* Iterate through all cookies on this line */ /* find att_beg */ att_beg = prev + 1; while (att_beg < hdr_end && http_is_spht[(unsigned char)*att_beg]) att_beg++; /* find att_end : this is the first character after the last non * space before the equal. It may be equal to hdr_end. */ equal = att_end = att_beg; while (equal < hdr_end) { if (*equal == '=' || *equal == ';' || (is_cookie2 && *equal == ',')) break; if (http_is_spht[(unsigned char)*equal++]) continue; att_end = equal; } /* here, <equal> points to '=', a delimitor or the end. <att_end> * is between <att_beg> and <equal>, both may be identical. */ /* look for end of cookie if there is an equal sign */ if (equal < hdr_end && *equal == '=') { /* look for the beginning of the value */ val_beg = equal + 1; while (val_beg < hdr_end && http_is_spht[(unsigned char)*val_beg]) val_beg++; /* find the end of the value, respecting quotes */ next = find_cookie_value_end(val_beg, hdr_end); /* make val_end point to the first white space or delimitor after the value */ val_end = next; while (val_end > val_beg && http_is_spht[(unsigned char)*(val_end - 1)]) val_end--; } else { /* <equal> points to next comma, semi-colon or EOL */ val_beg = val_end = next = equal; } if (next < hdr_end) { /* Set-Cookie2 supports multiple cookies, and <next> points to * a colon or semi-colon before the end. So skip all attr-value * pairs and look for the next comma. For Set-Cookie, since * commas are permitted in values, skip to the end. */ if (is_cookie2) next = find_hdr_value_end(next, hdr_end); else next = hdr_end; } /* Now everything is as on the diagram above */ /* Ignore cookies with no equal sign */ if (equal == val_end) continue; /* If there are spaces around the equal sign, we need to * strip them otherwise we'll get trouble for cookie captures, * or even for rewrites. Since this happens extremely rarely, * it does not hurt performance. */ if (unlikely(att_end != equal || val_beg > equal + 1)) { int stripped_before = 0; int stripped_after = 0; if (att_end != equal) { stripped_before = buffer_replace2(res->buf, att_end, equal, NULL, 0); equal += stripped_before; val_beg += stripped_before; } if (val_beg > equal + 1) { stripped_after = buffer_replace2(res->buf, equal + 1, val_beg, NULL, 0); val_beg += stripped_after; stripped_before += stripped_after; } val_end += stripped_before; next += stripped_before; hdr_end += stripped_before; hdr_next += stripped_before; cur_hdr->len += stripped_before; http_msg_move_end(&txn->rsp, stripped_before); } /* First, let's see if we want to capture this cookie. We check * that we don't already have a server side cookie, because we * can only capture one. Also as an optimisation, we ignore * cookies shorter than the declared name. */ if (s->fe->capture_name != NULL && txn->srv_cookie == NULL && (val_end - att_beg >= s->fe->capture_namelen) && memcmp(att_beg, s->fe->capture_name, s->fe->capture_namelen) == 0) { int log_len = val_end - att_beg; if ((txn->srv_cookie = pool_alloc2(pool2_capture)) == NULL) { Alert("HTTP logging : out of memory.\n"); } else { if (log_len > s->fe->capture_len) log_len = s->fe->capture_len; memcpy(txn->srv_cookie, att_beg, log_len); txn->srv_cookie[log_len] = 0; } } srv = objt_server(s->target); /* now check if we need to process it for persistence */ if (!(s->flags & SN_IGNORE_PRST) && (att_end - att_beg == s->be->cookie_len) && (s->be->cookie_name != NULL) && (memcmp(att_beg, s->be->cookie_name, att_end - att_beg) == 0)) { /* assume passive cookie by default */ txn->flags &= ~TX_SCK_MASK; txn->flags |= TX_SCK_FOUND; /* If the cookie is in insert mode on a known server, we'll delete * this occurrence because we'll insert another one later. * We'll delete it too if the "indirect" option is set and we're in * a direct access. */ if (s->be->ck_opts & PR_CK_PSV) { /* The "preserve" flag was set, we don't want to touch the * server's cookie. */ } else if ((srv && (s->be->ck_opts & PR_CK_INS)) || ((s->flags & SN_DIRECT) && (s->be->ck_opts & PR_CK_IND))) { /* this cookie must be deleted */ if (*prev == ':' && next == hdr_end) { /* whole header */ delta = buffer_replace2(res->buf, hdr_beg, hdr_next, NULL, 0); txn->hdr_idx.v[old_idx].next = cur_hdr->next; txn->hdr_idx.used--; cur_hdr->len = 0; cur_idx = old_idx; hdr_next += delta; http_msg_move_end(&txn->rsp, delta); /* note: while both invalid now, <next> and <hdr_end> * are still equal, so the for() will stop as expected. */ } else { /* just remove the value */ int delta = del_hdr_value(res->buf, &prev, next); next = prev; hdr_end += delta; hdr_next += delta; cur_hdr->len += delta; http_msg_move_end(&txn->rsp, delta); } txn->flags &= ~TX_SCK_MASK; txn->flags |= TX_SCK_DELETED; /* and go on with next cookie */ } else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_RW)) { /* replace bytes val_beg->val_end with the cookie name associated * with this server since we know it. */ delta = buffer_replace2(res->buf, val_beg, val_end, srv->cookie, srv->cklen); next += delta; hdr_end += delta; hdr_next += delta; cur_hdr->len += delta; http_msg_move_end(&txn->rsp, delta); txn->flags &= ~TX_SCK_MASK; txn->flags |= TX_SCK_REPLACED; } else if (srv && srv->cookie && (s->be->ck_opts & PR_CK_PFX)) { /* insert the cookie name associated with this server * before existing cookie, and insert a delimiter between them.. */ delta = buffer_replace2(res->buf, val_beg, val_beg, srv->cookie, srv->cklen + 1); next += delta; hdr_end += delta; hdr_next += delta; cur_hdr->len += delta; http_msg_move_end(&txn->rsp, delta); val_beg[srv->cklen] = COOKIE_DELIM; txn->flags &= ~TX_SCK_MASK; txn->flags |= TX_SCK_REPLACED; } } /* next, let's see if the cookie is our appcookie, unless persistence must be ignored */ else if (!(s->flags & SN_IGNORE_PRST) && (s->be->appsession_name != NULL)) { int cmp_len, value_len; char *value_begin; if (s->be->options2 & PR_O2_AS_PFX) { cmp_len = MIN(val_end - att_beg, s->be->appsession_name_len); value_begin = att_beg + s->be->appsession_name_len; value_len = MIN(s->be->appsession_len, val_end - att_beg - s->be->appsession_name_len); } else { cmp_len = att_end - att_beg; value_begin = val_beg; value_len = MIN(s->be->appsession_len, val_end - val_beg); } if ((cmp_len == s->be->appsession_name_len) && (memcmp(att_beg, s->be->appsession_name, s->be->appsession_name_len) == 0)) { /* free a possibly previously allocated memory */ pool_free2(apools.sessid, txn->sessid); /* Store the sessid in the session for future use */ if ((txn->sessid = pool_alloc2(apools.sessid)) == NULL) { Alert("Not enough Memory process_srv():asession->sessid:malloc().\n"); send_log(s->be, LOG_ALERT, "Not enough Memory process_srv():asession->sessid:malloc().\n"); return; } memcpy(txn->sessid, value_begin, value_len); txn->sessid[value_len] = 0; } } /* that's done for this cookie, check the next one on the same * line when next != hdr_end (only if is_cookie2). */ } /* check next header */ old_idx = cur_idx; } if (txn->sessid != NULL) { appsess *asession = NULL; /* only do insert, if lookup fails */ asession = appsession_hash_lookup(&(s->be->htbl_proxy), txn->sessid); if (asession == NULL) { size_t server_id_len; if ((asession = pool_alloc2(pool2_appsess)) == NULL) { Alert("Not enough Memory process_srv():asession:calloc().\n"); send_log(s->be, LOG_ALERT, "Not enough Memory process_srv():asession:calloc().\n"); return; } asession->serverid = NULL; /* to avoid a double free in case of allocation error */ if ((asession->sessid = pool_alloc2(apools.sessid)) == NULL) { Alert("Not enough Memory process_srv():asession->sessid:malloc().\n"); send_log(s->be, LOG_ALERT, "Not enough Memory process_srv():asession->sessid:malloc().\n"); s->be->htbl_proxy.destroy(asession); return; } memcpy(asession->sessid, txn->sessid, s->be->appsession_len); asession->sessid[s->be->appsession_len] = 0; server_id_len = strlen(objt_server(s->target)->id) + 1; if ((asession->serverid = pool_alloc2(apools.serverid)) == NULL) { Alert("Not enough Memory process_srv():asession->serverid:malloc().\n"); send_log(s->be, LOG_ALERT, "Not enough Memory process_srv():asession->sessid:malloc().\n"); s->be->htbl_proxy.destroy(asession); return; } asession->serverid[0] = '\0'; memcpy(asession->serverid, objt_server(s->target)->id, server_id_len); asession->request_count = 0; appsession_hash_insert(&(s->be->htbl_proxy), asession); } asession->expire = tick_add_ifset(now_ms, s->be->timeout.appsession); asession->request_count++; } } /* * Check if response is cacheable or not. Updates s->flags. */ void check_response_for_cacheability(struct session *s, struct channel *rtr) { struct http_txn *txn = &s->txn; char *p1, *p2; char *cur_ptr, *cur_end, *cur_next; int cur_idx; if (!(txn->flags & TX_CACHEABLE)) return; /* Iterate through the headers. * we start with the start line. */ cur_idx = 0; cur_next = rtr->buf->p + hdr_idx_first_pos(&txn->hdr_idx); while ((cur_idx = txn->hdr_idx.v[cur_idx].next)) { struct hdr_idx_elem *cur_hdr; int val; cur_hdr = &txn->hdr_idx.v[cur_idx]; cur_ptr = cur_next; cur_end = cur_ptr + cur_hdr->len; cur_next = cur_end + cur_hdr->cr + 1; /* We have one full header between cur_ptr and cur_end, and the * next header starts at cur_next. We're only interested in * "Cookie:" headers. */ val = http_header_match2(cur_ptr, cur_end, "Pragma", 6); if (val) { if ((cur_end - (cur_ptr + val) >= 8) && strncasecmp(cur_ptr + val, "no-cache", 8) == 0) { txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK; return; } } val = http_header_match2(cur_ptr, cur_end, "Cache-control", 13); if (!val) continue; /* OK, right now we know we have a cache-control header at cur_ptr */ p1 = cur_ptr + val; /* first non-space char after 'cache-control:' */ if (p1 >= cur_end) /* no more info */ continue; /* p1 is at the beginning of the value */ p2 = p1; while (p2 < cur_end && *p2 != '=' && *p2 != ',' && !isspace((unsigned char)*p2)) p2++; /* we have a complete value between p1 and p2 */ if (p2 < cur_end && *p2 == '=') { /* we have something of the form no-cache="set-cookie" */ if ((cur_end - p1 >= 21) && strncasecmp(p1, "no-cache=\"set-cookie", 20) == 0 && (p1[20] == '"' || p1[20] == ',')) txn->flags &= ~TX_CACHE_COOK; continue; } /* OK, so we know that either p2 points to the end of string or to a comma */ if (((p2 - p1 == 7) && strncasecmp(p1, "private", 7) == 0) || ((p2 - p1 == 8) && strncasecmp(p1, "no-cache", 8) == 0) || ((p2 - p1 == 8) && strncasecmp(p1, "no-store", 8) == 0) || ((p2 - p1 == 9) && strncasecmp(p1, "max-age=0", 9) == 0) || ((p2 - p1 == 10) && strncasecmp(p1, "s-maxage=0", 10) == 0)) { txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK; return; } if ((p2 - p1 == 6) && strncasecmp(p1, "public", 6) == 0) { txn->flags |= TX_CACHEABLE | TX_CACHE_COOK; continue; } } } /* * Try to retrieve a known appsession in the URI, then the associated server. * If the server is found, it's assigned to the session. */ void get_srv_from_appsession(struct session *s, const char *begin, int len) { char *end_params, *first_param, *cur_param, *next_param; char separator; int value_len; int mode = s->be->options2 & PR_O2_AS_M_ANY; if (s->be->appsession_name == NULL || (s->txn.meth != HTTP_METH_GET && s->txn.meth != HTTP_METH_POST && s->txn.meth != HTTP_METH_HEAD)) { return; } first_param = NULL; switch (mode) { case PR_O2_AS_M_PP: first_param = memchr(begin, ';', len); break; case PR_O2_AS_M_QS: first_param = memchr(begin, '?', len); break; } if (first_param == NULL) { return; } switch (mode) { case PR_O2_AS_M_PP: if ((end_params = memchr(first_param, '?', len - (begin - first_param))) == NULL) { end_params = (char *) begin + len; } separator = ';'; break; case PR_O2_AS_M_QS: end_params = (char *) begin + len; separator = '&'; break; default: /* unknown mode, shouldn't happen */ return; } cur_param = next_param = end_params; while (cur_param > first_param) { cur_param--; if ((cur_param[0] == separator) || (cur_param == first_param)) { /* let's see if this is the appsession parameter */ if ((cur_param + s->be->appsession_name_len + 1 < next_param) && ((s->be->options2 & PR_O2_AS_PFX) || cur_param[s->be->appsession_name_len + 1] == '=') && (strncasecmp(cur_param + 1, s->be->appsession_name, s->be->appsession_name_len) == 0)) { /* Cool... it's the right one */ cur_param += s->be->appsession_name_len + (s->be->options2 & PR_O2_AS_PFX ? 1 : 2); value_len = MIN(s->be->appsession_len, next_param - cur_param); if (value_len > 0) { manage_client_side_appsession(s, cur_param, value_len); } break; } next_param = cur_param; } } #if defined(DEBUG_HASH) Alert("get_srv_from_appsession\n"); appsession_hash_dump(&(s->be->htbl_proxy)); #endif } /* * In a GET, HEAD or POST request, check if the requested URI matches the stats uri * for the current backend. * * It is assumed that the request is either a HEAD, GET, or POST and that the * uri_auth field is valid. * * Returns 1 if stats should be provided, otherwise 0. */ int stats_check_uri(struct stream_interface *si, struct http_txn *txn, struct proxy *backend) { struct uri_auth *uri_auth = backend->uri_auth; struct http_msg *msg = &txn->req; const char *uri = msg->chn->buf->p+ msg->sl.rq.u; if (!uri_auth) return 0; if (txn->meth != HTTP_METH_GET && txn->meth != HTTP_METH_HEAD && txn->meth != HTTP_METH_POST) return 0; /* check URI size */ if (uri_auth->uri_len > msg->sl.rq.u_l) return 0; if (memcmp(uri, uri_auth->uri_prefix, uri_auth->uri_len) != 0) return 0; return 1; } /* * Capture a bad request or response and archive it in the proxy's structure. * By default it tries to report the error position as msg->err_pos. However if * this one is not set, it will then report msg->next, which is the last known * parsing point. The function is able to deal with wrapping buffers. It always * displays buffers as a contiguous area starting at buf->p. */ void http_capture_bad_message(struct error_snapshot *es, struct session *s, struct http_msg *msg, enum ht_state state, struct proxy *other_end) { struct channel *chn = msg->chn; int len1, len2; es->len = MIN(chn->buf->i, sizeof(es->buf)); len1 = chn->buf->data + chn->buf->size - chn->buf->p; len1 = MIN(len1, es->len); len2 = es->len - len1; /* remaining data if buffer wraps */ memcpy(es->buf, chn->buf->p, len1); if (len2) memcpy(es->buf + len1, chn->buf->data, len2); if (msg->err_pos >= 0) es->pos = msg->err_pos; else es->pos = msg->next; es->when = date; // user-visible date es->sid = s->uniq_id; es->srv = objt_server(s->target); es->oe = other_end; if (objt_conn(s->req->prod->end)) es->src = __objt_conn(s->req->prod->end)->addr.from; else memset(&es->src, 0, sizeof(es->src)); es->state = state; es->ev_id = error_snapshot_id++; es->b_flags = chn->flags; es->s_flags = s->flags; es->t_flags = s->txn.flags; es->m_flags = msg->flags; es->b_out = chn->buf->o; es->b_wrap = chn->buf->data + chn->buf->size - chn->buf->p; es->b_tot = chn->total; es->m_clen = msg->chunk_len; es->m_blen = msg->body_len; } /* Return in <vptr> and <vlen> the pointer and length of occurrence <occ> of * header whose name is <hname> of length <hlen>. If <ctx> is null, lookup is * performed over the whole headers. Otherwise it must contain a valid header * context, initialised with ctx->idx=0 for the first lookup in a series. If * <occ> is positive or null, occurrence #occ from the beginning (or last ctx) * is returned. Occ #0 and #1 are equivalent. If <occ> is negative (and no less * than -MAX_HDR_HISTORY), the occurrence is counted from the last one which is * -1. The value fetch stops at commas, so this function is suited for use with * list headers. * The return value is 0 if nothing was found, or non-zero otherwise. */ unsigned int http_get_hdr(const struct http_msg *msg, const char *hname, int hlen, struct hdr_idx *idx, int occ, struct hdr_ctx *ctx, char **vptr, int *vlen) { struct hdr_ctx local_ctx; char *ptr_hist[MAX_HDR_HISTORY]; int len_hist[MAX_HDR_HISTORY]; unsigned int hist_ptr; int found; if (!ctx) { local_ctx.idx = 0; ctx = &local_ctx; } if (occ >= 0) { /* search from the beginning */ while (http_find_header2(hname, hlen, msg->chn->buf->p, idx, ctx)) { occ--; if (occ <= 0) { *vptr = ctx->line + ctx->val; *vlen = ctx->vlen; return 1; } } return 0; } /* negative occurrence, we scan all the list then walk back */ if (-occ > MAX_HDR_HISTORY) return 0; found = hist_ptr = 0; while (http_find_header2(hname, hlen, msg->chn->buf->p, idx, ctx)) { ptr_hist[hist_ptr] = ctx->line + ctx->val; len_hist[hist_ptr] = ctx->vlen; if (++hist_ptr >= MAX_HDR_HISTORY) hist_ptr = 0; found++; } if (-occ > found) return 0; /* OK now we have the last occurrence in [hist_ptr-1], and we need to * find occurrence -occ. 0 <= hist_ptr < MAX_HDR_HISTORY, and we have * -10 <= occ <= -1. So we have to check [hist_ptr%MAX_HDR_HISTORY+occ] * to remain in the 0..9 range. */ hist_ptr += occ + MAX_HDR_HISTORY; if (hist_ptr >= MAX_HDR_HISTORY) hist_ptr -= MAX_HDR_HISTORY; *vptr = ptr_hist[hist_ptr]; *vlen = len_hist[hist_ptr]; return 1; } /* Return in <vptr> and <vlen> the pointer and length of occurrence <occ> of * header whose name is <hname> of length <hlen>. If <ctx> is null, lookup is * performed over the whole headers. Otherwise it must contain a valid header * context, initialised with ctx->idx=0 for the first lookup in a series. If * <occ> is positive or null, occurrence #occ from the beginning (or last ctx) * is returned. Occ #0 and #1 are equivalent. If <occ> is negative (and no less * than -MAX_HDR_HISTORY), the occurrence is counted from the last one which is * -1. This function differs from http_get_hdr() in that it only returns full * line header values and does not stop at commas. * The return value is 0 if nothing was found, or non-zero otherwise. */ unsigned int http_get_fhdr(const struct http_msg *msg, const char *hname, int hlen, struct hdr_idx *idx, int occ, struct hdr_ctx *ctx, char **vptr, int *vlen) { struct hdr_ctx local_ctx; char *ptr_hist[MAX_HDR_HISTORY]; int len_hist[MAX_HDR_HISTORY]; unsigned int hist_ptr; int found; if (!ctx) { local_ctx.idx = 0; ctx = &local_ctx; } if (occ >= 0) { /* search from the beginning */ while (http_find_full_header2(hname, hlen, msg->chn->buf->p, idx, ctx)) { occ--; if (occ <= 0) { *vptr = ctx->line + ctx->val; *vlen = ctx->vlen; return 1; } } return 0; } /* negative occurrence, we scan all the list then walk back */ if (-occ > MAX_HDR_HISTORY) return 0; found = hist_ptr = 0; while (http_find_full_header2(hname, hlen, msg->chn->buf->p, idx, ctx)) { ptr_hist[hist_ptr] = ctx->line + ctx->val; len_hist[hist_ptr] = ctx->vlen; if (++hist_ptr >= MAX_HDR_HISTORY) hist_ptr = 0; found++; } if (-occ > found) return 0; /* OK now we have the last occurrence in [hist_ptr-1], and we need to * find occurrence -occ, so we have to check [hist_ptr+occ]. */ hist_ptr += occ; if (hist_ptr >= MAX_HDR_HISTORY) hist_ptr -= MAX_HDR_HISTORY; *vptr = ptr_hist[hist_ptr]; *vlen = len_hist[hist_ptr]; return 1; } /* * Print a debug line with a header. Always stop at the first CR or LF char, * so it is safe to pass it a full buffer if needed. If <err> is not NULL, an * arrow is printed after the line which contains the pointer. */ void debug_hdr(const char *dir, struct session *s, const char *start, const char *end) { int max; chunk_printf(&trash, "%08x:%s.%s[%04x:%04x]: ", s->uniq_id, s->be->id, dir, objt_conn(s->req->prod->end) ? (unsigned short)objt_conn(s->req->prod->end)->t.sock.fd : -1, objt_conn(s->req->cons->end) ? (unsigned short)objt_conn(s->req->cons->end)->t.sock.fd : -1); for (max = 0; start + max < end; max++) if (start[max] == '\r' || start[max] == '\n') break; UBOUND(max, trash.size - trash.len - 3); trash.len += strlcpy2(trash.str + trash.len, start, max + 1); trash.str[trash.len++] = '\n'; shut_your_big_mouth_gcc(write(1, trash.str, trash.len)); } /* * Initialize a new HTTP transaction for session <s>. It is assumed that all * the required fields are properly allocated and that we only need to (re)init * them. This should be used before processing any new request. */ void http_init_txn(struct session *s) { struct http_txn *txn = &s->txn; struct proxy *fe = s->fe; txn->flags = 0; txn->status = -1; txn->cookie_first_date = 0; txn->cookie_last_date = 0; txn->req.flags = 0; txn->req.sol = txn->req.eol = txn->req.eoh = 0; /* relative to the buffer */ txn->req.next = 0; txn->rsp.flags = 0; txn->rsp.sol = txn->rsp.eol = txn->rsp.eoh = 0; /* relative to the buffer */ txn->rsp.next = 0; txn->req.chunk_len = 0LL; txn->req.body_len = 0LL; txn->rsp.chunk_len = 0LL; txn->rsp.body_len = 0LL; txn->req.msg_state = HTTP_MSG_RQBEFORE; /* at the very beginning of the request */ txn->rsp.msg_state = HTTP_MSG_RPBEFORE; /* at the very beginning of the response */ txn->req.chn = s->req; txn->rsp.chn = s->rep; txn->auth.method = HTTP_AUTH_UNKNOWN; txn->req.err_pos = txn->rsp.err_pos = -2; /* block buggy requests/responses */ if (fe->options2 & PR_O2_REQBUG_OK) txn->req.err_pos = -1; /* let buggy requests pass */ if (txn->req.cap) memset(txn->req.cap, 0, fe->nb_req_cap * sizeof(void *)); if (txn->rsp.cap) memset(txn->rsp.cap, 0, fe->nb_rsp_cap * sizeof(void *)); if (txn->hdr_idx.v) hdr_idx_init(&txn->hdr_idx); } /* to be used at the end of a transaction */ void http_end_txn(struct session *s) { struct http_txn *txn = &s->txn; /* release any possible compression context */ if (s->flags & SN_COMP_READY) s->comp_algo->end(&s->comp_ctx); s->comp_algo = NULL; s->flags &= ~SN_COMP_READY; /* these ones will have been dynamically allocated */ pool_free2(pool2_requri, txn->uri); pool_free2(pool2_capture, txn->cli_cookie); pool_free2(pool2_capture, txn->srv_cookie); pool_free2(apools.sessid, txn->sessid); pool_free2(pool2_uniqueid, s->unique_id); s->unique_id = NULL; txn->sessid = NULL; txn->uri = NULL; txn->srv_cookie = NULL; txn->cli_cookie = NULL; if (txn->req.cap) { struct cap_hdr *h; for (h = s->fe->req_cap; h; h = h->next) pool_free2(h->pool, txn->req.cap[h->index]); memset(txn->req.cap, 0, s->fe->nb_req_cap * sizeof(void *)); } if (txn->rsp.cap) { struct cap_hdr *h; for (h = s->fe->rsp_cap; h; h = h->next) pool_free2(h->pool, txn->rsp.cap[h->index]); memset(txn->rsp.cap, 0, s->fe->nb_rsp_cap * sizeof(void *)); } } /* to be used at the end of a transaction to prepare a new one */ void http_reset_txn(struct session *s) { http_end_txn(s); http_init_txn(s); s->be = s->fe; s->logs.logwait = s->fe->to_log; s->logs.level = 0; session_del_srv_conn(s); s->target = NULL; /* re-init store persistence */ s->store_count = 0; s->uniq_id = global.req_count++; s->pend_pos = NULL; s->req->flags |= CF_READ_DONTWAIT; /* one read is usually enough */ /* We must trim any excess data from the response buffer, because we * may have blocked an invalid response from a server that we don't * want to accidentely forward once we disable the analysers, nor do * we want those data to come along with next response. A typical * example of such data would be from a buggy server responding to * a HEAD with some data, or sending more than the advertised * content-length. */ if (unlikely(s->rep->buf->i)) s->rep->buf->i = 0; s->req->rto = s->fe->timeout.client; s->req->wto = TICK_ETERNITY; s->rep->rto = TICK_ETERNITY; s->rep->wto = s->fe->timeout.client; s->req->rex = TICK_ETERNITY; s->req->wex = TICK_ETERNITY; s->req->analyse_exp = TICK_ETERNITY; s->rep->rex = TICK_ETERNITY; s->rep->wex = TICK_ETERNITY; s->rep->analyse_exp = TICK_ETERNITY; } void free_http_res_rules(struct list *r) { struct http_res_rule *tr, *pr; list_for_each_entry_safe(pr, tr, r, list) { LIST_DEL(&pr->list); regex_free(&pr->arg.hdr_add.re); free(pr); } } void free_http_req_rules(struct list *r) { struct http_req_rule *tr, *pr; list_for_each_entry_safe(pr, tr, r, list) { LIST_DEL(&pr->list); if (pr->action == HTTP_REQ_ACT_AUTH) free(pr->arg.auth.realm); regex_free(&pr->arg.hdr_add.re); free(pr); } } /* parse an "http-request" rule */ struct http_req_rule *parse_http_req_cond(const char **args, const char *file, int linenum, struct proxy *proxy) { struct http_req_rule *rule; struct http_req_action_kw *custom = NULL; int cur_arg; char *error; rule = (struct http_req_rule*)calloc(1, sizeof(struct http_req_rule)); if (!rule) { Alert("parsing [%s:%d]: out of memory.\n", file, linenum); goto out_err; } if (!strcmp(args[0], "allow")) { rule->action = HTTP_REQ_ACT_ALLOW; cur_arg = 1; } else if (!strcmp(args[0], "deny") || !strcmp(args[0], "block")) { rule->action = HTTP_REQ_ACT_DENY; cur_arg = 1; } else if (!strcmp(args[0], "tarpit")) { rule->action = HTTP_REQ_ACT_TARPIT; cur_arg = 1; } else if (!strcmp(args[0], "auth")) { rule->action = HTTP_REQ_ACT_AUTH; cur_arg = 1; while(*args[cur_arg]) { if (!strcmp(args[cur_arg], "realm")) { rule->arg.auth.realm = strdup(args[cur_arg + 1]); cur_arg+=2; continue; } else break; } } else if (!strcmp(args[0], "set-nice")) { rule->action = HTTP_REQ_ACT_SET_NICE; cur_arg = 1; if (!*args[cur_arg] || (*args[cur_arg + 1] && strcmp(args[cur_arg + 1], "if") != 0 && strcmp(args[cur_arg + 1], "unless") != 0)) { Alert("parsing [%s:%d]: 'http-request %s' expects exactly 1 argument (integer value).\n", file, linenum, args[0]); goto out_err; } rule->arg.nice = atoi(args[cur_arg]); if (rule->arg.nice < -1024) rule->arg.nice = -1024; else if (rule->arg.nice > 1024) rule->arg.nice = 1024; cur_arg++; } else if (!strcmp(args[0], "set-tos")) { #ifdef IP_TOS char *err; rule->action = HTTP_REQ_ACT_SET_TOS; cur_arg = 1; if (!*args[cur_arg] || (*args[cur_arg + 1] && strcmp(args[cur_arg + 1], "if") != 0 && strcmp(args[cur_arg + 1], "unless") != 0)) { Alert("parsing [%s:%d]: 'http-request %s' expects exactly 1 argument (integer/hex value).\n", file, linenum, args[0]); goto out_err; } rule->arg.tos = strtol(args[cur_arg], &err, 0); if (err && *err != '\0') { Alert("parsing [%s:%d]: invalid character starting at '%s' in 'http-request %s' (integer/hex value expected).\n", file, linenum, err, args[0]); goto out_err; } cur_arg++; #else Alert("parsing [%s:%d]: 'http-request %s' is not supported on this platform (IP_TOS undefined).\n", file, linenum, args[0]); goto out_err; #endif } else if (!strcmp(args[0], "set-mark")) { #ifdef SO_MARK char *err; rule->action = HTTP_REQ_ACT_SET_MARK; cur_arg = 1; if (!*args[cur_arg] || (*args[cur_arg + 1] && strcmp(args[cur_arg + 1], "if") != 0 && strcmp(args[cur_arg + 1], "unless") != 0)) { Alert("parsing [%s:%d]: 'http-request %s' expects exactly 1 argument (integer/hex value).\n", file, linenum, args[0]); goto out_err; } rule->arg.mark = strtoul(args[cur_arg], &err, 0); if (err && *err != '\0') { Alert("parsing [%s:%d]: invalid character starting at '%s' in 'http-request %s' (integer/hex value expected).\n", file, linenum, err, args[0]); goto out_err; } cur_arg++; global.last_checks |= LSTCHK_NETADM; #else Alert("parsing [%s:%d]: 'http-request %s' is not supported on this platform (SO_MARK undefined).\n", file, linenum, args[0]); goto out_err; #endif } else if (!strcmp(args[0], "set-log-level")) { rule->action = HTTP_REQ_ACT_SET_LOGL; cur_arg = 1; if (!*args[cur_arg] || (*args[cur_arg + 1] && strcmp(args[cur_arg + 1], "if") != 0 && strcmp(args[cur_arg + 1], "unless") != 0)) { bad_log_level: Alert("parsing [%s:%d]: 'http-request %s' expects exactly 1 argument (log level name or 'silent').\n", file, linenum, args[0]); goto out_err; } if (strcmp(args[cur_arg], "silent") == 0) rule->arg.loglevel = -1; else if ((rule->arg.loglevel = get_log_level(args[cur_arg]) + 1) == 0) goto bad_log_level; cur_arg++; } else if (strcmp(args[0], "add-header") == 0 || strcmp(args[0], "set-header") == 0) { rule->action = *args[0] == 'a' ? HTTP_REQ_ACT_ADD_HDR : HTTP_REQ_ACT_SET_HDR; cur_arg = 1; if (!*args[cur_arg] || !*args[cur_arg+1] || (*args[cur_arg+2] && strcmp(args[cur_arg+2], "if") != 0 && strcmp(args[cur_arg+2], "unless") != 0)) { Alert("parsing [%s:%d]: 'http-request %s' expects exactly 2 arguments.\n", file, linenum, args[0]); goto out_err; } rule->arg.hdr_add.name = strdup(args[cur_arg]); rule->arg.hdr_add.name_len = strlen(rule->arg.hdr_add.name); LIST_INIT(&rule->arg.hdr_add.fmt); proxy->conf.args.ctx = ARGC_HRQ; parse_logformat_string(args[cur_arg + 1], proxy, &rule->arg.hdr_add.fmt, LOG_OPT_HTTP, (proxy->cap & PR_CAP_FE) ? SMP_VAL_FE_HRQ_HDR : SMP_VAL_BE_HRQ_HDR, file, linenum); free(proxy->conf.lfs_file); proxy->conf.lfs_file = strdup(proxy->conf.args.file); proxy->conf.lfs_line = proxy->conf.args.line; cur_arg += 2; } else if (strcmp(args[0], "replace-header") == 0 || strcmp(args[0], "replace-value") == 0) { rule->action = args[0][8] == 'h' ? HTTP_REQ_ACT_REPLACE_HDR : HTTP_REQ_ACT_REPLACE_VAL; cur_arg = 1; if (!*args[cur_arg] || !*args[cur_arg+1] || !*args[cur_arg+2] || (*args[cur_arg+3] && strcmp(args[cur_arg+3], "if") != 0 && strcmp(args[cur_arg+3], "unless") != 0)) { Alert("parsing [%s:%d]: 'http-request %s' expects exactly 3 arguments.\n", file, linenum, args[0]); goto out_err; } rule->arg.hdr_add.name = strdup(args[cur_arg]); rule->arg.hdr_add.name_len = strlen(rule->arg.hdr_add.name); LIST_INIT(&rule->arg.hdr_add.fmt); error = NULL; if (!regex_comp(args[cur_arg + 1], &rule->arg.hdr_add.re, 1, 1, &error)) { Alert("parsing [%s:%d] : '%s' : %s.\n", file, linenum, args[cur_arg + 1], error); free(error); goto out_err; } proxy->conf.args.ctx = ARGC_HRQ; parse_logformat_string(args[cur_arg + 2], proxy, &rule->arg.hdr_add.fmt, LOG_OPT_HTTP, (proxy->cap & PR_CAP_FE) ? SMP_VAL_FE_HRQ_HDR : SMP_VAL_BE_HRQ_HDR, file, linenum); free(proxy->conf.lfs_file); proxy->conf.lfs_file = strdup(proxy->conf.args.file); proxy->conf.lfs_line = proxy->conf.args.line; cur_arg += 3; } else if (strcmp(args[0], "del-header") == 0) { rule->action = HTTP_REQ_ACT_DEL_HDR; cur_arg = 1; if (!*args[cur_arg] || (*args[cur_arg+1] && strcmp(args[cur_arg+1], "if") != 0 && strcmp(args[cur_arg+1], "unless") != 0)) { Alert("parsing [%s:%d]: 'http-request %s' expects exactly 1 argument.\n", file, linenum, args[0]); goto out_err; } rule->arg.hdr_add.name = strdup(args[cur_arg]); rule->arg.hdr_add.name_len = strlen(rule->arg.hdr_add.name); proxy->conf.args.ctx = ARGC_HRQ; free(proxy->conf.lfs_file); proxy->conf.lfs_file = strdup(proxy->conf.args.file); proxy->conf.lfs_line = proxy->conf.args.line; cur_arg += 1; } else if (strcmp(args[0], "redirect") == 0) { struct redirect_rule *redir; char *errmsg = NULL; if ((redir = http_parse_redirect_rule(file, linenum, proxy, (const char **)args + 1, &errmsg, 1)) == NULL) { Alert("parsing [%s:%d] : error detected in %s '%s' while parsing 'http-request %s' rule : %s.\n", file, linenum, proxy_type_str(proxy), proxy->id, args[0], errmsg); goto out_err; } /* this redirect rule might already contain a parsed condition which * we'll pass to the http-request rule. */ rule->action = HTTP_REQ_ACT_REDIR; rule->arg.redir = redir; rule->cond = redir->cond; redir->cond = NULL; cur_arg = 2; return rule; } else if (strncmp(args[0], "add-acl", 7) == 0) { /* http-request add-acl(<reference (acl name)>) <key pattern> */ rule->action = HTTP_REQ_ACT_ADD_ACL; /* * '+ 8' for 'add-acl(' * '- 9' for 'add-acl(' + trailing ')' */ rule->arg.map.ref = my_strndup(args[0] + 8, strlen(args[0]) - 9); cur_arg = 1; if (!*args[cur_arg] || (*args[cur_arg+1] && strcmp(args[cur_arg+1], "if") != 0 && strcmp(args[cur_arg+1], "unless") != 0)) { Alert("parsing [%s:%d]: 'http-request %s' expects exactly 1 argument.\n", file, linenum, args[0]); goto out_err; } LIST_INIT(&rule->arg.map.key); proxy->conf.args.ctx = ARGC_HRQ; parse_logformat_string(args[cur_arg], proxy, &rule->arg.map.key, LOG_OPT_HTTP, (proxy->cap & PR_CAP_FE) ? SMP_VAL_FE_HRQ_HDR : SMP_VAL_BE_HRQ_HDR, file, linenum); free(proxy->conf.lfs_file); proxy->conf.lfs_file = strdup(proxy->conf.args.file); proxy->conf.lfs_line = proxy->conf.args.line; cur_arg += 1; } else if (strncmp(args[0], "del-acl", 7) == 0) { /* http-request del-acl(<reference (acl name)>) <key pattern> */ rule->action = HTTP_REQ_ACT_DEL_ACL; /* * '+ 8' for 'del-acl(' * '- 9' for 'del-acl(' + trailing ')' */ rule->arg.map.ref = my_strndup(args[0] + 8, strlen(args[0]) - 9); cur_arg = 1; if (!*args[cur_arg] || (*args[cur_arg+1] && strcmp(args[cur_arg+1], "if") != 0 && strcmp(args[cur_arg+1], "unless") != 0)) { Alert("parsing [%s:%d]: 'http-request %s' expects exactly 1 argument.\n", file, linenum, args[0]); goto out_err; } LIST_INIT(&rule->arg.map.key); proxy->conf.args.ctx = ARGC_HRQ; parse_logformat_string(args[cur_arg], proxy, &rule->arg.map.key, LOG_OPT_HTTP, (proxy->cap & PR_CAP_FE) ? SMP_VAL_FE_HRQ_HDR : SMP_VAL_BE_HRQ_HDR, file, linenum); free(proxy->conf.lfs_file); proxy->conf.lfs_file = strdup(proxy->conf.args.file); proxy->conf.lfs_line = proxy->conf.args.line; cur_arg += 1; } else if (strncmp(args[0], "del-map", 7) == 0) { /* http-request del-map(<reference (map name)>) <key pattern> */ rule->action = HTTP_REQ_ACT_DEL_MAP; /* * '+ 8' for 'del-map(' * '- 9' for 'del-map(' + trailing ')' */ rule->arg.map.ref = my_strndup(args[0] + 8, strlen(args[0]) - 9); cur_arg = 1; if (!*args[cur_arg] || (*args[cur_arg+1] && strcmp(args[cur_arg+1], "if") != 0 && strcmp(args[cur_arg+1], "unless") != 0)) { Alert("parsing [%s:%d]: 'http-request %s' expects exactly 1 argument.\n", file, linenum, args[0]); goto out_err; } LIST_INIT(&rule->arg.map.key); proxy->conf.args.ctx = ARGC_HRQ; parse_logformat_string(args[cur_arg], proxy, &rule->arg.map.key, LOG_OPT_HTTP, (proxy->cap & PR_CAP_FE) ? SMP_VAL_FE_HRQ_HDR : SMP_VAL_BE_HRQ_HDR, file, linenum); free(proxy->conf.lfs_file); proxy->conf.lfs_file = strdup(proxy->conf.args.file); proxy->conf.lfs_line = proxy->conf.args.line; cur_arg += 1; } else if (strncmp(args[0], "set-map", 7) == 0) { /* http-request set-map(<reference (map name)>) <key pattern> <value pattern> */ rule->action = HTTP_REQ_ACT_SET_MAP; /* * '+ 8' for 'set-map(' * '- 9' for 'set-map(' + trailing ')' */ rule->arg.map.ref = my_strndup(args[0] + 8, strlen(args[0]) - 9); cur_arg = 1; if (!*args[cur_arg] || !*args[cur_arg+1] || (*args[cur_arg+2] && strcmp(args[cur_arg+2], "if") != 0 && strcmp(args[cur_arg+2], "unless") != 0)) { Alert("parsing [%s:%d]: 'http-request %s' expects exactly 2 arguments.\n", file, linenum, args[0]); goto out_err; } LIST_INIT(&rule->arg.map.key); LIST_INIT(&rule->arg.map.value); proxy->conf.args.ctx = ARGC_HRQ; /* key pattern */ parse_logformat_string(args[cur_arg], proxy, &rule->arg.map.key, LOG_OPT_HTTP, (proxy->cap & PR_CAP_FE) ? SMP_VAL_FE_HRQ_HDR : SMP_VAL_BE_HRQ_HDR, file, linenum); /* value pattern */ parse_logformat_string(args[cur_arg + 1], proxy, &rule->arg.map.value, LOG_OPT_HTTP, (proxy->cap & PR_CAP_FE) ? SMP_VAL_FE_HRQ_HDR : SMP_VAL_BE_HRQ_HDR, file, linenum); free(proxy->conf.lfs_file); proxy->conf.lfs_file = strdup(proxy->conf.args.file); proxy->conf.lfs_line = proxy->conf.args.line; cur_arg += 2; } else if (((custom = action_http_req_custom(args[0])) != NULL)) { char *errmsg = NULL; cur_arg = 1; /* try in the module list */ if (custom->parse(args, &cur_arg, proxy, rule, &errmsg) < 0) { Alert("parsing [%s:%d] : error detected in %s '%s' while parsing 'http-request %s' rule : %s.\n", file, linenum, proxy_type_str(proxy), proxy->id, args[0], errmsg); free(errmsg); goto out_err; } } else { Alert("parsing [%s:%d]: 'http-request' expects 'allow', 'deny', 'auth', 'redirect', 'tarpit', 'add-header', 'set-header', 'replace-header', 'replace-value', 'set-nice', 'set-tos', 'set-mark', 'set-log-level', 'add-acl', 'del-acl', 'del-map', 'set-map', but got '%s'%s.\n", file, linenum, args[0], *args[0] ? "" : " (missing argument)"); goto out_err; } if (strcmp(args[cur_arg], "if") == 0 || strcmp(args[cur_arg], "unless") == 0) { struct acl_cond *cond; char *errmsg = NULL; if ((cond = build_acl_cond(file, linenum, proxy, args+cur_arg, &errmsg)) == NULL) { Alert("parsing [%s:%d] : error detected while parsing an 'http-request %s' condition : %s.\n", file, linenum, args[0], errmsg); free(errmsg); goto out_err; } rule->cond = cond; } else if (*args[cur_arg]) { Alert("parsing [%s:%d]: 'http-request %s' expects 'realm' for 'auth' or" " either 'if' or 'unless' followed by a condition but found '%s'.\n", file, linenum, args[0], args[cur_arg]); goto out_err; } return rule; out_err: free(rule); return NULL; } /* parse an "http-respose" rule */ struct http_res_rule *parse_http_res_cond(const char **args, const char *file, int linenum, struct proxy *proxy) { struct http_res_rule *rule; struct http_res_action_kw *custom = NULL; int cur_arg; char *error; rule = calloc(1, sizeof(*rule)); if (!rule) { Alert("parsing [%s:%d]: out of memory.\n", file, linenum); goto out_err; } if (!strcmp(args[0], "allow")) { rule->action = HTTP_RES_ACT_ALLOW; cur_arg = 1; } else if (!strcmp(args[0], "deny")) { rule->action = HTTP_RES_ACT_DENY; cur_arg = 1; } else if (!strcmp(args[0], "set-nice")) { rule->action = HTTP_RES_ACT_SET_NICE; cur_arg = 1; if (!*args[cur_arg] || (*args[cur_arg + 1] && strcmp(args[cur_arg + 1], "if") != 0 && strcmp(args[cur_arg + 1], "unless") != 0)) { Alert("parsing [%s:%d]: 'http-response %s' expects exactly 1 argument (integer value).\n", file, linenum, args[0]); goto out_err; } rule->arg.nice = atoi(args[cur_arg]); if (rule->arg.nice < -1024) rule->arg.nice = -1024; else if (rule->arg.nice > 1024) rule->arg.nice = 1024; cur_arg++; } else if (!strcmp(args[0], "set-tos")) { #ifdef IP_TOS char *err; rule->action = HTTP_RES_ACT_SET_TOS; cur_arg = 1; if (!*args[cur_arg] || (*args[cur_arg + 1] && strcmp(args[cur_arg + 1], "if") != 0 && strcmp(args[cur_arg + 1], "unless") != 0)) { Alert("parsing [%s:%d]: 'http-response %s' expects exactly 1 argument (integer/hex value).\n", file, linenum, args[0]); goto out_err; } rule->arg.tos = strtol(args[cur_arg], &err, 0); if (err && *err != '\0') { Alert("parsing [%s:%d]: invalid character starting at '%s' in 'http-response %s' (integer/hex value expected).\n", file, linenum, err, args[0]); goto out_err; } cur_arg++; #else Alert("parsing [%s:%d]: 'http-response %s' is not supported on this platform (IP_TOS undefined).\n", file, linenum, args[0]); goto out_err; #endif } else if (!strcmp(args[0], "set-mark")) { #ifdef SO_MARK char *err; rule->action = HTTP_RES_ACT_SET_MARK; cur_arg = 1; if (!*args[cur_arg] || (*args[cur_arg + 1] && strcmp(args[cur_arg + 1], "if") != 0 && strcmp(args[cur_arg + 1], "unless") != 0)) { Alert("parsing [%s:%d]: 'http-response %s' expects exactly 1 argument (integer/hex value).\n", file, linenum, args[0]); goto out_err; } rule->arg.mark = strtoul(args[cur_arg], &err, 0); if (err && *err != '\0') { Alert("parsing [%s:%d]: invalid character starting at '%s' in 'http-response %s' (integer/hex value expected).\n", file, linenum, err, args[0]); goto out_err; } cur_arg++; global.last_checks |= LSTCHK_NETADM; #else Alert("parsing [%s:%d]: 'http-response %s' is not supported on this platform (SO_MARK undefined).\n", file, linenum, args[0]); goto out_err; #endif } else if (!strcmp(args[0], "set-log-level")) { rule->action = HTTP_RES_ACT_SET_LOGL; cur_arg = 1; if (!*args[cur_arg] || (*args[cur_arg + 1] && strcmp(args[cur_arg + 1], "if") != 0 && strcmp(args[cur_arg + 1], "unless") != 0)) { bad_log_level: Alert("parsing [%s:%d]: 'http-response %s' expects exactly 1 argument (log level name or 'silent').\n", file, linenum, args[0]); goto out_err; } if (strcmp(args[cur_arg], "silent") == 0) rule->arg.loglevel = -1; else if ((rule->arg.loglevel = get_log_level(args[cur_arg] + 1)) == 0) goto bad_log_level; cur_arg++; } else if (strcmp(args[0], "add-header") == 0 || strcmp(args[0], "set-header") == 0) { rule->action = *args[0] == 'a' ? HTTP_RES_ACT_ADD_HDR : HTTP_RES_ACT_SET_HDR; cur_arg = 1; if (!*args[cur_arg] || !*args[cur_arg+1] || (*args[cur_arg+2] && strcmp(args[cur_arg+2], "if") != 0 && strcmp(args[cur_arg+2], "unless") != 0)) { Alert("parsing [%s:%d]: 'http-response %s' expects exactly 2 arguments.\n", file, linenum, args[0]); goto out_err; } rule->arg.hdr_add.name = strdup(args[cur_arg]); rule->arg.hdr_add.name_len = strlen(rule->arg.hdr_add.name); LIST_INIT(&rule->arg.hdr_add.fmt); proxy->conf.args.ctx = ARGC_HRS; parse_logformat_string(args[cur_arg + 1], proxy, &rule->arg.hdr_add.fmt, LOG_OPT_HTTP, (proxy->cap & PR_CAP_BE) ? SMP_VAL_BE_HRS_HDR : SMP_VAL_FE_HRS_HDR, file, linenum); free(proxy->conf.lfs_file); proxy->conf.lfs_file = strdup(proxy->conf.args.file); proxy->conf.lfs_line = proxy->conf.args.line; cur_arg += 2; } else if (strcmp(args[0], "replace-header") == 0 || strcmp(args[0], "replace-value") == 0) { rule->action = args[0][8] == 'h' ? HTTP_RES_ACT_REPLACE_HDR : HTTP_RES_ACT_REPLACE_VAL; cur_arg = 1; if (!*args[cur_arg] || !*args[cur_arg+1] || !*args[cur_arg+2] || (*args[cur_arg+3] && strcmp(args[cur_arg+3], "if") != 0 && strcmp(args[cur_arg+3], "unless") != 0)) { Alert("parsing [%s:%d]: 'http-response %s' expects exactly 3 arguments.\n", file, linenum, args[0]); goto out_err; } rule->arg.hdr_add.name = strdup(args[cur_arg]); rule->arg.hdr_add.name_len = strlen(rule->arg.hdr_add.name); LIST_INIT(&rule->arg.hdr_add.fmt); error = NULL; if (!regex_comp(args[cur_arg + 1], &rule->arg.hdr_add.re, 1, 1, &error)) { Alert("parsing [%s:%d] : '%s' : %s.\n", file, linenum, args[cur_arg + 1], error); free(error); goto out_err; } proxy->conf.args.ctx = ARGC_HRQ; parse_logformat_string(args[cur_arg + 2], proxy, &rule->arg.hdr_add.fmt, LOG_OPT_HTTP, (proxy->cap & PR_CAP_BE) ? SMP_VAL_BE_HRS_HDR : SMP_VAL_FE_HRS_HDR, file, linenum); free(proxy->conf.lfs_file); proxy->conf.lfs_file = strdup(proxy->conf.args.file); proxy->conf.lfs_line = proxy->conf.args.line; cur_arg += 3; } else if (strcmp(args[0], "del-header") == 0) { rule->action = HTTP_RES_ACT_DEL_HDR; cur_arg = 1; if (!*args[cur_arg] || (*args[cur_arg+1] && strcmp(args[cur_arg+1], "if") != 0 && strcmp(args[cur_arg+1], "unless") != 0)) { Alert("parsing [%s:%d]: 'http-response %s' expects exactly 1 argument.\n", file, linenum, args[0]); goto out_err; } rule->arg.hdr_add.name = strdup(args[cur_arg]); rule->arg.hdr_add.name_len = strlen(rule->arg.hdr_add.name); proxy->conf.args.ctx = ARGC_HRS; free(proxy->conf.lfs_file); proxy->conf.lfs_file = strdup(proxy->conf.args.file); proxy->conf.lfs_line = proxy->conf.args.line; cur_arg += 1; } else if (strncmp(args[0], "add-acl", 7) == 0) { /* http-request add-acl(<reference (acl name)>) <key pattern> */ rule->action = HTTP_RES_ACT_ADD_ACL; /* * '+ 8' for 'add-acl(' * '- 9' for 'add-acl(' + trailing ')' */ rule->arg.map.ref = my_strndup(args[0] + 8, strlen(args[0]) - 9); cur_arg = 1; if (!*args[cur_arg] || (*args[cur_arg+1] && strcmp(args[cur_arg+1], "if") != 0 && strcmp(args[cur_arg+1], "unless") != 0)) { Alert("parsing [%s:%d]: 'http-response %s' expects exactly 1 argument.\n", file, linenum, args[0]); goto out_err; } LIST_INIT(&rule->arg.map.key); proxy->conf.args.ctx = ARGC_HRS; parse_logformat_string(args[cur_arg], proxy, &rule->arg.map.key, LOG_OPT_HTTP, (proxy->cap & PR_CAP_BE) ? SMP_VAL_BE_HRS_HDR : SMP_VAL_FE_HRS_HDR, file, linenum); free(proxy->conf.lfs_file); proxy->conf.lfs_file = strdup(proxy->conf.args.file); proxy->conf.lfs_line = proxy->conf.args.line; cur_arg += 1; } else if (strncmp(args[0], "del-acl", 7) == 0) { /* http-response del-acl(<reference (acl name)>) <key pattern> */ rule->action = HTTP_RES_ACT_DEL_ACL; /* * '+ 8' for 'del-acl(' * '- 9' for 'del-acl(' + trailing ')' */ rule->arg.map.ref = my_strndup(args[0] + 8, strlen(args[0]) - 9); cur_arg = 1; if (!*args[cur_arg] || (*args[cur_arg+1] && strcmp(args[cur_arg+1], "if") != 0 && strcmp(args[cur_arg+1], "unless") != 0)) { Alert("parsing [%s:%d]: 'http-response %s' expects exactly 1 argument.\n", file, linenum, args[0]); goto out_err; } LIST_INIT(&rule->arg.map.key); proxy->conf.args.ctx = ARGC_HRS; parse_logformat_string(args[cur_arg], proxy, &rule->arg.map.key, LOG_OPT_HTTP, (proxy->cap & PR_CAP_BE) ? SMP_VAL_BE_HRS_HDR : SMP_VAL_FE_HRS_HDR, file, linenum); free(proxy->conf.lfs_file); proxy->conf.lfs_file = strdup(proxy->conf.args.file); proxy->conf.lfs_line = proxy->conf.args.line; cur_arg += 1; } else if (strncmp(args[0], "del-map", 7) == 0) { /* http-response del-map(<reference (map name)>) <key pattern> */ rule->action = HTTP_RES_ACT_DEL_MAP; /* * '+ 8' for 'del-map(' * '- 9' for 'del-map(' + trailing ')' */ rule->arg.map.ref = my_strndup(args[0] + 8, strlen(args[0]) - 9); cur_arg = 1; if (!*args[cur_arg] || (*args[cur_arg+1] && strcmp(args[cur_arg+1], "if") != 0 && strcmp(args[cur_arg+1], "unless") != 0)) { Alert("parsing [%s:%d]: 'http-response %s' expects exactly 1 argument.\n", file, linenum, args[0]); goto out_err; } LIST_INIT(&rule->arg.map.key); proxy->conf.args.ctx = ARGC_HRS; parse_logformat_string(args[cur_arg], proxy, &rule->arg.map.key, LOG_OPT_HTTP, (proxy->cap & PR_CAP_BE) ? SMP_VAL_BE_HRS_HDR : SMP_VAL_FE_HRS_HDR, file, linenum); free(proxy->conf.lfs_file); proxy->conf.lfs_file = strdup(proxy->conf.args.file); proxy->conf.lfs_line = proxy->conf.args.line; cur_arg += 1; } else if (strncmp(args[0], "set-map", 7) == 0) { /* http-response set-map(<reference (map name)>) <key pattern> <value pattern> */ rule->action = HTTP_RES_ACT_SET_MAP; /* * '+ 8' for 'set-map(' * '- 9' for 'set-map(' + trailing ')' */ rule->arg.map.ref = my_strndup(args[0] + 8, strlen(args[0]) - 9); cur_arg = 1; if (!*args[cur_arg] || !*args[cur_arg+1] || (*args[cur_arg+2] && strcmp(args[cur_arg+2], "if") != 0 && strcmp(args[cur_arg+2], "unless") != 0)) { Alert("parsing [%s:%d]: 'http-response %s' expects exactly 2 arguments.\n", file, linenum, args[0]); goto out_err; } LIST_INIT(&rule->arg.map.key); LIST_INIT(&rule->arg.map.value); proxy->conf.args.ctx = ARGC_HRS; /* key pattern */ parse_logformat_string(args[cur_arg], proxy, &rule->arg.map.key, LOG_OPT_HTTP, (proxy->cap & PR_CAP_BE) ? SMP_VAL_BE_HRS_HDR : SMP_VAL_FE_HRS_HDR, file, linenum); /* value pattern */ parse_logformat_string(args[cur_arg + 1], proxy, &rule->arg.map.value, LOG_OPT_HTTP, (proxy->cap & PR_CAP_BE) ? SMP_VAL_BE_HRS_HDR : SMP_VAL_FE_HRS_HDR, file, linenum); free(proxy->conf.lfs_file); proxy->conf.lfs_file = strdup(proxy->conf.args.file); proxy->conf.lfs_line = proxy->conf.args.line; cur_arg += 2; } else if (((custom = action_http_res_custom(args[0])) != NULL)) { char *errmsg = NULL; cur_arg = 1; /* try in the module list */ if (custom->parse(args, &cur_arg, proxy, rule, &errmsg) < 0) { Alert("parsing [%s:%d] : error detected in %s '%s' while parsing 'http-response %s' rule : %s.\n", file, linenum, proxy_type_str(proxy), proxy->id, args[0], errmsg); free(errmsg); goto out_err; } } else { Alert("parsing [%s:%d]: 'http-response' expects 'allow', 'deny', 'redirect', 'add-header', 'del-header', 'set-header', 'replace-header', 'replace-value', 'set-nice', 'set-tos', 'set-mark', 'set-log-level', 'del-acl', 'add-acl', 'del-map', 'set-map', but got '%s'%s.\n", file, linenum, args[0], *args[0] ? "" : " (missing argument)"); goto out_err; } if (strcmp(args[cur_arg], "if") == 0 || strcmp(args[cur_arg], "unless") == 0) { struct acl_cond *cond; char *errmsg = NULL; if ((cond = build_acl_cond(file, linenum, proxy, args+cur_arg, &errmsg)) == NULL) { Alert("parsing [%s:%d] : error detected while parsing an 'http-response %s' condition : %s.\n", file, linenum, args[0], errmsg); free(errmsg); goto out_err; } rule->cond = cond; } else if (*args[cur_arg]) { Alert("parsing [%s:%d]: 'http-response %s' expects" " either 'if' or 'unless' followed by a condition but found '%s'.\n", file, linenum, args[0], args[cur_arg]); goto out_err; } return rule; out_err: free(rule); return NULL; } /* Parses a redirect rule. Returns the redirect rule on success or NULL on error, * with <err> filled with the error message. If <use_fmt> is not null, builds a * dynamic log-format rule instead of a static string. */ struct redirect_rule *http_parse_redirect_rule(const char *file, int linenum, struct proxy *curproxy, const char **args, char **errmsg, int use_fmt) { struct redirect_rule *rule; int cur_arg; int type = REDIRECT_TYPE_NONE; int code = 302; const char *destination = NULL; const char *cookie = NULL; int cookie_set = 0; unsigned int flags = REDIRECT_FLAG_NONE; struct acl_cond *cond = NULL; cur_arg = 0; while (*(args[cur_arg])) { if (strcmp(args[cur_arg], "location") == 0) { if (!*args[cur_arg + 1]) goto missing_arg; type = REDIRECT_TYPE_LOCATION; cur_arg++; destination = args[cur_arg]; } else if (strcmp(args[cur_arg], "prefix") == 0) { if (!*args[cur_arg + 1]) goto missing_arg; type = REDIRECT_TYPE_PREFIX; cur_arg++; destination = args[cur_arg]; } else if (strcmp(args[cur_arg], "scheme") == 0) { if (!*args[cur_arg + 1]) goto missing_arg; type = REDIRECT_TYPE_SCHEME; cur_arg++; destination = args[cur_arg]; } else if (strcmp(args[cur_arg], "set-cookie") == 0) { if (!*args[cur_arg + 1]) goto missing_arg; cur_arg++; cookie = args[cur_arg]; cookie_set = 1; } else if (strcmp(args[cur_arg], "clear-cookie") == 0) { if (!*args[cur_arg + 1]) goto missing_arg; cur_arg++; cookie = args[cur_arg]; cookie_set = 0; } else if (strcmp(args[cur_arg], "code") == 0) { if (!*args[cur_arg + 1]) goto missing_arg; cur_arg++; code = atol(args[cur_arg]); if (code < 301 || code > 308 || (code > 303 && code < 307)) { memprintf(errmsg, "'%s': unsupported HTTP code '%s' (must be one of 301, 302, 303, 307 or 308)", args[cur_arg - 1], args[cur_arg]); return NULL; } } else if (!strcmp(args[cur_arg],"drop-query")) { flags |= REDIRECT_FLAG_DROP_QS; } else if (!strcmp(args[cur_arg],"append-slash")) { flags |= REDIRECT_FLAG_APPEND_SLASH; } else if (strcmp(args[cur_arg], "if") == 0 || strcmp(args[cur_arg], "unless") == 0) { cond = build_acl_cond(file, linenum, curproxy, (const char **)args + cur_arg, errmsg); if (!cond) { memprintf(errmsg, "error in condition: %s", *errmsg); return NULL; } break; } else { memprintf(errmsg, "expects 'code', 'prefix', 'location', 'scheme', 'set-cookie', 'clear-cookie', 'drop-query' or 'append-slash' (was '%s')", args[cur_arg]); return NULL; } cur_arg++; } if (type == REDIRECT_TYPE_NONE) { memprintf(errmsg, "redirection type expected ('prefix', 'location', or 'scheme')"); return NULL; } rule = (struct redirect_rule *)calloc(1, sizeof(*rule)); rule->cond = cond; LIST_INIT(&rule->rdr_fmt); if (!use_fmt) { /* old-style static redirect rule */ rule->rdr_str = strdup(destination); rule->rdr_len = strlen(destination); } else { /* log-format based redirect rule */ /* Parse destination. Note that in the REDIRECT_TYPE_PREFIX case, * if prefix == "/", we don't want to add anything, otherwise it * makes it hard for the user to configure a self-redirection. */ proxy->conf.args.ctx = ARGC_RDR; if (!(type == REDIRECT_TYPE_PREFIX && destination[0] == '/' && destination[1] == '\0')) { parse_logformat_string(destination, curproxy, &rule->rdr_fmt, LOG_OPT_HTTP, (curproxy->cap & PR_CAP_FE) ? SMP_VAL_FE_HRQ_HDR : SMP_VAL_BE_HRQ_HDR, file, linenum); free(curproxy->conf.lfs_file); curproxy->conf.lfs_file = strdup(curproxy->conf.args.file); curproxy->conf.lfs_line = curproxy->conf.args.line; } } if (cookie) { /* depending on cookie_set, either we want to set the cookie, or to clear it. * a clear consists in appending "; path=/; Max-Age=0;" at the end. */ rule->cookie_len = strlen(cookie); if (cookie_set) { rule->cookie_str = malloc(rule->cookie_len + 10); memcpy(rule->cookie_str, cookie, rule->cookie_len); memcpy(rule->cookie_str + rule->cookie_len, "; path=/;", 10); rule->cookie_len += 9; } else { rule->cookie_str = malloc(rule->cookie_len + 21); memcpy(rule->cookie_str, cookie, rule->cookie_len); memcpy(rule->cookie_str + rule->cookie_len, "; path=/; Max-Age=0;", 21); rule->cookie_len += 20; } } rule->type = type; rule->code = code; rule->flags = flags; LIST_INIT(&rule->list); return rule; missing_arg: memprintf(errmsg, "missing argument for '%s'", args[cur_arg]); return NULL; } /************************************************************************/ /* The code below is dedicated to ACL parsing and matching */ /************************************************************************/ /* This function ensures that the prerequisites for an L7 fetch are ready, * which means that a request or response is ready. If some data is missing, * a parsing attempt is made. This is useful in TCP-based ACLs which are able * to extract data from L7. If <req_vol> is non-null during a request prefetch, * another test is made to ensure the required information is not gone. * * The function returns : * 0 with SMP_F_MAY_CHANGE in the sample flags if some data is missing to * decide whether or not an HTTP message is present ; * 0 if the requested data cannot be fetched or if it is certain that * we'll never have any HTTP message there ; * 1 if an HTTP message is ready */ static int smp_prefetch_http(struct proxy *px, struct session *s, void *l7, unsigned int opt, const struct arg *args, struct sample *smp, int req_vol) { struct http_txn *txn = l7; struct http_msg *msg = &txn->req; /* Note: hdr_idx.v cannot be NULL in this ACL because the ACL is tagged * as a layer7 ACL, which involves automatic allocation of hdr_idx. */ if (unlikely(!s || !txn)) return 0; /* Check for a dependency on a request */ smp->type = SMP_T_BOOL; if ((opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ) { if (unlikely(!s->req)) return 0; /* If the buffer does not leave enough free space at the end, * we must first realign it. */ if (s->req->buf->p > s->req->buf->data && s->req->buf->i + s->req->buf->p > s->req->buf->data + s->req->buf->size - global.tune.maxrewrite) buffer_slow_realign(s->req->buf); if (unlikely(txn->req.msg_state < HTTP_MSG_BODY)) { if (msg->msg_state == HTTP_MSG_ERROR) return 0; /* Try to decode HTTP request */ if (likely(msg->next < s->req->buf->i)) http_msg_analyzer(msg, &txn->hdr_idx); /* Still no valid request ? */ if (unlikely(msg->msg_state < HTTP_MSG_BODY)) { if ((msg->msg_state == HTTP_MSG_ERROR) || buffer_full(s->req->buf, global.tune.maxrewrite)) { return 0; } /* wait for final state */ smp->flags |= SMP_F_MAY_CHANGE; return 0; } /* OK we just got a valid HTTP request. We have some minor * preparation to perform so that further checks can rely * on HTTP tests. */ /* If the request was parsed but was too large, we must absolutely * return an error so that it is not processed. At the moment this * cannot happen, but if the parsers are to change in the future, * we want this check to be maintained. */ if (unlikely(s->req->buf->i + s->req->buf->p > s->req->buf->data + s->req->buf->size - global.tune.maxrewrite)) { msg->msg_state = HTTP_MSG_ERROR; smp->data.uint = 1; return 1; } txn->meth = find_http_meth(msg->chn->buf->p, msg->sl.rq.m_l); if (txn->meth == HTTP_METH_GET || txn->meth == HTTP_METH_HEAD) s->flags |= SN_REDIRECTABLE; if (unlikely(msg->sl.rq.v_l == 0) && !http_upgrade_v09_to_v10(txn)) return 0; } if (req_vol && txn->rsp.msg_state != HTTP_MSG_RPBEFORE) { return 0; /* data might have moved and indexes changed */ } /* otherwise everything's ready for the request */ } else { /* Check for a dependency on a response */ if (txn->rsp.msg_state < HTTP_MSG_BODY) { smp->flags |= SMP_F_MAY_CHANGE; return 0; } } /* everything's OK */ smp->data.uint = 1; return 1; } /* Note: these functinos *do* modify the sample. Even in case of success, at * least the type and uint value are modified. */ #define CHECK_HTTP_MESSAGE_FIRST() \ do { int r = smp_prefetch_http(px, l4, l7, opt, args, smp, 1); if (r <= 0) return r; } while (0) #define CHECK_HTTP_MESSAGE_FIRST_PERM() \ do { int r = smp_prefetch_http(px, l4, l7, opt, args, smp, 0); if (r <= 0) return r; } while (0) /* 1. Check on METHOD * We use the pre-parsed method if it is known, and store its number as an * integer. If it is unknown, we use the pointer and the length. */ static int pat_parse_meth(const char *text, struct pattern *pattern, int mflags, char **err) { int len, meth; len = strlen(text); meth = find_http_meth(text, len); pattern->val.i = meth; if (meth == HTTP_METH_OTHER) { pattern->ptr.str = (char *)text; pattern->len = len; } else { pattern->ptr.str = NULL; pattern->len = 0; } return 1; } /* This function fetches the method of current HTTP request and stores * it in the global pattern struct as a chunk. There are two possibilities : * - if the method is known (not HTTP_METH_OTHER), its identifier is stored * in <len> and <ptr> is NULL ; * - if the method is unknown (HTTP_METH_OTHER), <ptr> points to the text and * <len> to its length. * This is intended to be used with pat_match_meth() only. */ static int smp_fetch_meth(struct proxy *px, struct session *l4, void *l7, unsigned int opt, const struct arg *args, struct sample *smp, const char *kw) { int meth; struct http_txn *txn = l7; CHECK_HTTP_MESSAGE_FIRST_PERM(); meth = txn->meth; smp->type = SMP_T_METH; smp->data.meth.meth = meth; if (meth == HTTP_METH_OTHER) { if (txn->rsp.msg_state != HTTP_MSG_RPBEFORE) /* ensure the indexes are not affected */ return 0; smp->flags |= SMP_F_CONST; smp->data.meth.str.len = txn->req.sl.rq.m_l; smp->data.meth.str.str = txn->req.chn->buf->p; } smp->flags |= SMP_F_VOL_1ST; return 1; } /* See above how the method is stored in the global pattern */ static struct pattern *pat_match_meth(struct sample *smp, struct pattern_expr *expr, int fill) { int icase; struct pattern_list *lst; struct pattern *pattern; list_for_each_entry(lst, &expr->patterns, list) { pattern = &lst->pat; /* well-known method */ if (pattern->val.i != HTTP_METH_OTHER) { if (smp->data.meth.meth == pattern->val.i) return pattern; else continue; } /* Other method, we must compare the strings */ if (pattern->len != smp->data.meth.str.len) continue; icase = expr->mflags & PAT_MF_IGNORE_CASE; if ((icase && strncasecmp(pattern->ptr.str, smp->data.meth.str.str, smp->data.meth.str.len) == 0) || (!icase && strncmp(pattern->ptr.str, smp->data.meth.str.str, smp->data.meth.str.len) == 0)) return pattern; } return NULL; } static int smp_fetch_rqver(struct proxy *px, struct session *l4, void *l7, unsigned int opt, const struct arg *args, struct sample *smp, const char *kw) { struct http_txn *txn = l7; char *ptr; int len; CHECK_HTTP_MESSAGE_FIRST(); len = txn->req.sl.rq.v_l; ptr = txn->req.chn->buf->p + txn->req.sl.rq.v; while ((len-- > 0) && (*ptr++ != '/')); if (len <= 0) return 0; smp->type = SMP_T_STR; smp->data.str.str = ptr; smp->data.str.len = len; smp->flags = SMP_F_VOL_1ST | SMP_F_CONST; return 1; } static int smp_fetch_stver(struct proxy *px, struct session *l4, void *l7, unsigned int opt, const struct arg *args, struct sample *smp, const char *kw) { struct http_txn *txn = l7; char *ptr; int len; CHECK_HTTP_MESSAGE_FIRST(); if (txn->rsp.msg_state < HTTP_MSG_BODY) return 0; len = txn->rsp.sl.st.v_l; ptr = txn->rsp.chn->buf->p; while ((len-- > 0) && (*ptr++ != '/')); if (len <= 0) return 0; smp->type = SMP_T_STR; smp->data.str.str = ptr; smp->data.str.len = len; smp->flags = SMP_F_VOL_1ST | SMP_F_CONST; return 1; } /* 3. Check on Status Code. We manipulate integers here. */ static int smp_fetch_stcode(struct proxy *px, struct session *l4, void *l7, unsigned int opt, const struct arg *args, struct sample *smp, const char *kw) { struct http_txn *txn = l7; char *ptr; int len; CHECK_HTTP_MESSAGE_FIRST(); if (txn->rsp.msg_state < HTTP_MSG_BODY) return 0; len = txn->rsp.sl.st.c_l; ptr = txn->rsp.chn->buf->p + txn->rsp.sl.st.c; smp->type = SMP_T_UINT; smp->data.uint = __strl2ui(ptr, len); smp->flags = SMP_F_VOL_1ST; return 1; } /* 4. Check on URL/URI. A pointer to the URI is stored. */ static int smp_fetch_url(struct proxy *px, struct session *l4, void *l7, unsigned int opt, const struct arg *args, struct sample *smp, const char *kw) { struct http_txn *txn = l7; CHECK_HTTP_MESSAGE_FIRST(); smp->type = SMP_T_STR; smp->data.str.len = txn->req.sl.rq.u_l; smp->data.str.str = txn->req.chn->buf->p + txn->req.sl.rq.u; smp->flags = SMP_F_VOL_1ST | SMP_F_CONST; return 1; } static int smp_fetch_url_ip(struct proxy *px, struct session *l4, void *l7, unsigned int opt, const struct arg *args, struct sample *smp, const char *kw) { struct http_txn *txn = l7; struct sockaddr_storage addr; CHECK_HTTP_MESSAGE_FIRST(); url2sa(txn->req.chn->buf->p + txn->req.sl.rq.u, txn->req.sl.rq.u_l, &addr, NULL); if (((struct sockaddr_in *)&addr)->sin_family != AF_INET) return 0; smp->type = SMP_T_IPV4; smp->data.ipv4 = ((struct sockaddr_in *)&addr)->sin_addr; smp->flags = 0; return 1; } static int smp_fetch_url_port(struct proxy *px, struct session *l4, void *l7, unsigned int opt, const struct arg *args, struct sample *smp, const char *kw) { struct http_txn *txn = l7; struct sockaddr_storage addr; CHECK_HTTP_MESSAGE_FIRST(); url2sa(txn->req.chn->buf->p + txn->req.sl.rq.u, txn->req.sl.rq.u_l, &addr, NULL); if (((struct sockaddr_in *)&addr)->sin_family != AF_INET) return 0; smp->type = SMP_T_UINT; smp->data.uint = ntohs(((struct sockaddr_in *)&addr)->sin_port); smp->flags = 0; return 1; } /* Fetch an HTTP header. A pointer to the beginning of the value is returned. * Accepts an optional argument of type string containing the header field name, * and an optional argument of type signed or unsigned integer to request an * explicit occurrence of the header. Note that in the event of a missing name, * headers are considered from the first one. It does not stop on commas and * returns full lines instead (useful for User-Agent or Date for example). */ static int smp_fetch_fhdr(struct proxy *px, struct session *l4, void *l7, unsigned int opt, const struct arg *args, struct sample *smp, const char *kw) { struct http_txn *txn = l7; struct hdr_idx *idx = &txn->hdr_idx; struct hdr_ctx *ctx = smp->ctx.a[0]; const struct http_msg *msg = ((opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ) ? &txn->req : &txn->rsp; int occ = 0; const char *name_str = NULL; int name_len = 0; if (!ctx) { /* first call */ ctx = &static_hdr_ctx; ctx->idx = 0; smp->ctx.a[0] = ctx; } if (args) { if (args[0].type != ARGT_STR) return 0; name_str = args[0].data.str.str; name_len = args[0].data.str.len; if (args[1].type == ARGT_UINT || args[1].type == ARGT_SINT) occ = args[1].data.uint; } CHECK_HTTP_MESSAGE_FIRST(); if (ctx && !(smp->flags & SMP_F_NOT_LAST)) /* search for header from the beginning */ ctx->idx = 0; if (!occ && !(opt & SMP_OPT_ITERATE)) /* no explicit occurrence and single fetch => last header by default */ occ = -1; if (!occ) /* prepare to report multiple occurrences for ACL fetches */ smp->flags |= SMP_F_NOT_LAST; smp->type = SMP_T_STR; smp->flags |= SMP_F_VOL_HDR | SMP_F_CONST; if (http_get_fhdr(msg, name_str, name_len, idx, occ, ctx, &smp->data.str.str, &smp->data.str.len)) return 1; smp->flags &= ~SMP_F_NOT_LAST; return 0; } /* 6. Check on HTTP header count. The number of occurrences is returned. * Accepts exactly 1 argument of type string. It does not stop on commas and * returns full lines instead (useful for User-Agent or Date for example). */ static int smp_fetch_fhdr_cnt(struct proxy *px, struct session *l4, void *l7, unsigned int opt, const struct arg *args, struct sample *smp, const char *kw) { struct http_txn *txn = l7; struct hdr_idx *idx = &txn->hdr_idx; struct hdr_ctx ctx; const struct http_msg *msg = ((opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ) ? &txn->req : &txn->rsp; int cnt; if (!args || args->type != ARGT_STR) return 0; CHECK_HTTP_MESSAGE_FIRST(); ctx.idx = 0; cnt = 0; while (http_find_full_header2(args->data.str.str, args->data.str.len, msg->chn->buf->p, idx, &ctx)) cnt++; smp->type = SMP_T_UINT; smp->data.uint = cnt; smp->flags = SMP_F_VOL_HDR; return 1; } /* Fetch an HTTP header. A pointer to the beginning of the value is returned. * Accepts an optional argument of type string containing the header field name, * and an optional argument of type signed or unsigned integer to request an * explicit occurrence of the header. Note that in the event of a missing name, * headers are considered from the first one. */ static int smp_fetch_hdr(struct proxy *px, struct session *l4, void *l7, unsigned int opt, const struct arg *args, struct sample *smp, const char *kw) { struct http_txn *txn = l7; struct hdr_idx *idx = &txn->hdr_idx; struct hdr_ctx *ctx = smp->ctx.a[0]; const struct http_msg *msg = ((opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ) ? &txn->req : &txn->rsp; int occ = 0; const char *name_str = NULL; int name_len = 0; if (!ctx) { /* first call */ ctx = &static_hdr_ctx; ctx->idx = 0; smp->ctx.a[0] = ctx; } if (args) { if (args[0].type != ARGT_STR) return 0; name_str = args[0].data.str.str; name_len = args[0].data.str.len; if (args[1].type == ARGT_UINT || args[1].type == ARGT_SINT) occ = args[1].data.uint; } CHECK_HTTP_MESSAGE_FIRST(); if (ctx && !(smp->flags & SMP_F_NOT_LAST)) /* search for header from the beginning */ ctx->idx = 0; if (!occ && !(opt & SMP_OPT_ITERATE)) /* no explicit occurrence and single fetch => last header by default */ occ = -1; if (!occ) /* prepare to report multiple occurrences for ACL fetches */ smp->flags |= SMP_F_NOT_LAST; smp->type = SMP_T_STR; smp->flags |= SMP_F_VOL_HDR | SMP_F_CONST; if (http_get_hdr(msg, name_str, name_len, idx, occ, ctx, &smp->data.str.str, &smp->data.str.len)) return 1; smp->flags &= ~SMP_F_NOT_LAST; return 0; } /* 6. Check on HTTP header count. The number of occurrences is returned. * Accepts exactly 1 argument of type string. */ static int smp_fetch_hdr_cnt(struct proxy *px, struct session *l4, void *l7, unsigned int opt, const struct arg *args, struct sample *smp, const char *kw) { struct http_txn *txn = l7; struct hdr_idx *idx = &txn->hdr_idx; struct hdr_ctx ctx; const struct http_msg *msg = ((opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ) ? &txn->req : &txn->rsp; int cnt; if (!args || args->type != ARGT_STR) return 0; CHECK_HTTP_MESSAGE_FIRST(); ctx.idx = 0; cnt = 0; while (http_find_header2(args->data.str.str, args->data.str.len, msg->chn->buf->p, idx, &ctx)) cnt++; smp->type = SMP_T_UINT; smp->data.uint = cnt; smp->flags = SMP_F_VOL_HDR; return 1; } /* Fetch an HTTP header's integer value. The integer value is returned. It * takes a mandatory argument of type string and an optional one of type int * to designate a specific occurrence. It returns an unsigned integer, which * may or may not be appropriate for everything. */ static int smp_fetch_hdr_val(struct proxy *px, struct session *l4, void *l7, unsigned int opt, const struct arg *args, struct sample *smp, const char *kw) { int ret = smp_fetch_hdr(px, l4, l7, opt, args, smp, kw); if (ret > 0) { smp->type = SMP_T_UINT; smp->data.uint = strl2ic(smp->data.str.str, smp->data.str.len); } return ret; } /* Fetch an HTTP header's IP value. takes a mandatory argument of type string * and an optional one of type int to designate a specific occurrence. * It returns an IPv4 or IPv6 address. */ static int smp_fetch_hdr_ip(struct proxy *px, struct session *l4, void *l7, unsigned int opt, const struct arg *args, struct sample *smp, const char *kw) { int ret; while ((ret = smp_fetch_hdr(px, l4, l7, opt, args, smp, kw)) > 0) { if (url2ipv4((char *)smp->data.str.str, &smp->data.ipv4)) { smp->type = SMP_T_IPV4; break; } else { struct chunk *temp = get_trash_chunk(); if (smp->data.str.len < temp->size - 1) { memcpy(temp->str, smp->data.str.str, smp->data.str.len); temp->str[smp->data.str.len] = '\0'; if (inet_pton(AF_INET6, temp->str, &smp->data.ipv6)) { smp->type = SMP_T_IPV6; break; } } } /* if the header doesn't match an IP address, fetch next one */ if (!(smp->flags & SMP_F_NOT_LAST)) return 0; } return ret; } /* 8. Check on URI PATH. A pointer to the PATH is stored. The path starts at * the first '/' after the possible hostname, and ends before the possible '?'. */ static int smp_fetch_path(struct proxy *px, struct session *l4, void *l7, unsigned int opt, const struct arg *args, struct sample *smp, const char *kw) { struct http_txn *txn = l7; char *ptr, *end; CHECK_HTTP_MESSAGE_FIRST(); end = txn->req.chn->buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l; ptr = http_get_path(txn); if (!ptr) return 0; /* OK, we got the '/' ! */ smp->type = SMP_T_STR; smp->data.str.str = ptr; while (ptr < end && *ptr != '?') ptr++; smp->data.str.len = ptr - smp->data.str.str; smp->flags = SMP_F_VOL_1ST | SMP_F_CONST; return 1; } /* This produces a concatenation of the first occurrence of the Host header * followed by the path component if it begins with a slash ('/'). This means * that '*' will not be added, resulting in exactly the first Host entry. * If no Host header is found, then the path is returned as-is. The returned * value is stored in the trash so it does not need to be marked constant. * The returned sample is of type string. */ static int smp_fetch_base(struct proxy *px, struct session *l4, void *l7, unsigned int opt, const struct arg *args, struct sample *smp, const char *kw) { struct http_txn *txn = l7; char *ptr, *end, *beg; struct hdr_ctx ctx; struct chunk *temp; CHECK_HTTP_MESSAGE_FIRST(); ctx.idx = 0; if (!http_find_header2("Host", 4, txn->req.chn->buf->p, &txn->hdr_idx, &ctx) || !ctx.vlen) return smp_fetch_path(px, l4, l7, opt, args, smp, kw); /* OK we have the header value in ctx.line+ctx.val for ctx.vlen bytes */ temp = get_trash_chunk(); memcpy(temp->str, ctx.line + ctx.val, ctx.vlen); smp->type = SMP_T_STR; smp->data.str.str = temp->str; smp->data.str.len = ctx.vlen; /* now retrieve the path */ end = txn->req.chn->buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l; beg = http_get_path(txn); if (!beg) beg = end; for (ptr = beg; ptr < end && *ptr != '?'; ptr++); if (beg < ptr && *beg == '/') { memcpy(smp->data.str.str + smp->data.str.len, beg, ptr - beg); smp->data.str.len += ptr - beg; } smp->flags = SMP_F_VOL_1ST; return 1; } /* This produces a 32-bit hash of the concatenation of the first occurrence of * the Host header followed by the path component if it begins with a slash ('/'). * This means that '*' will not be added, resulting in exactly the first Host * entry. If no Host header is found, then the path is used. The resulting value * is hashed using the path hash followed by a full avalanche hash and provides a * 32-bit integer value. This fetch is useful for tracking per-path activity on * high-traffic sites without having to store whole paths. */ static int smp_fetch_base32(struct proxy *px, struct session *l4, void *l7, unsigned int opt, const struct arg *args, struct sample *smp, const char *kw) { struct http_txn *txn = l7; struct hdr_ctx ctx; unsigned int hash = 0; char *ptr, *beg, *end; int len; CHECK_HTTP_MESSAGE_FIRST(); ctx.idx = 0; if (http_find_header2("Host", 4, txn->req.chn->buf->p, &txn->hdr_idx, &ctx)) { /* OK we have the header value in ctx.line+ctx.val for ctx.vlen bytes */ ptr = ctx.line + ctx.val; len = ctx.vlen; while (len--) hash = *(ptr++) + (hash << 6) + (hash << 16) - hash; } /* now retrieve the path */ end = txn->req.chn->buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l; beg = http_get_path(txn); if (!beg) beg = end; for (ptr = beg; ptr < end && *ptr != '?'; ptr++); if (beg < ptr && *beg == '/') { while (beg < ptr) hash = *(beg++) + (hash << 6) + (hash << 16) - hash; } hash = full_hash(hash); smp->type = SMP_T_UINT; smp->data.uint = hash; smp->flags = SMP_F_VOL_1ST; return 1; } /* This concatenates the source address with the 32-bit hash of the Host and * path as returned by smp_fetch_base32(). The idea is to have per-source and * per-path counters. The result is a binary block from 8 to 20 bytes depending * on the source address length. The path hash is stored before the address so * that in environments where IPv6 is insignificant, truncating the output to * 8 bytes would still work. */ static int smp_fetch_base32_src(struct proxy *px, struct session *l4, void *l7, unsigned int opt, const struct arg *args, struct sample *smp, const char *kw) { struct chunk *temp; struct connection *cli_conn = objt_conn(l4->si[0].end); if (!cli_conn) return 0; if (!smp_fetch_base32(px, l4, l7, opt, args, smp, kw)) return 0; temp = get_trash_chunk(); *(unsigned int *)temp->str = htonl(smp->data.uint); temp->len += sizeof(unsigned int); switch (cli_conn->addr.from.ss_family) { case AF_INET: memcpy(temp->str + temp->len, &((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr, 4); temp->len += 4; break; case AF_INET6: memcpy(temp->str + temp->len, &((struct sockaddr_in6 *)&cli_conn->addr.from)->sin6_addr, 16); temp->len += 16; break; default: return 0; } smp->data.str = *temp; smp->type = SMP_T_BIN; return 1; } static int smp_fetch_proto_http(struct proxy *px, struct session *l4, void *l7, unsigned int opt, const struct arg *args, struct sample *smp, const char *kw) { /* Note: hdr_idx.v cannot be NULL in this ACL because the ACL is tagged * as a layer7 ACL, which involves automatic allocation of hdr_idx. */ CHECK_HTTP_MESSAGE_FIRST_PERM(); smp->type = SMP_T_BOOL; smp->data.uint = 1; return 1; } /* return a valid test if the current request is the first one on the connection */ static int smp_fetch_http_first_req(struct proxy *px, struct session *s, void *l7, unsigned int opt, const struct arg *args, struct sample *smp, const char *kw) { if (!s) return 0; smp->type = SMP_T_BOOL; smp->data.uint = !(s->txn.flags & TX_NOT_FIRST); return 1; } /* Accepts exactly 1 argument of type userlist */ static int smp_fetch_http_auth(struct proxy *px, struct session *l4, void *l7, unsigned int opt, const struct arg *args, struct sample *smp, const char *kw) { if (!args || args->type != ARGT_USR) return 0; CHECK_HTTP_MESSAGE_FIRST(); if (!get_http_auth(l4)) return 0; smp->type = SMP_T_BOOL; smp->data.uint = check_user(args->data.usr, l4->txn.auth.user, l4->txn.auth.pass); return 1; } /* Accepts exactly 1 argument of type userlist */ static int smp_fetch_http_auth_grp(struct proxy *px, struct session *l4, void *l7, unsigned int opt, const struct arg *args, struct sample *smp, const char *kw) { if (!args || args->type != ARGT_USR) return 0; CHECK_HTTP_MESSAGE_FIRST(); if (!get_http_auth(l4)) return 0; /* if the user does not belong to the userlist or has a wrong password, * report that it unconditionally does not match. Otherwise we return * a string containing the username. */ if (!check_user(args->data.usr, l4->txn.auth.user, l4->txn.auth.pass)) return 0; /* pat_match_auth() will need the user list */ smp->ctx.a[0] = args->data.usr; smp->type = SMP_T_STR; smp->flags = SMP_F_CONST; smp->data.str.str = l4->txn.auth.user; smp->data.str.len = strlen(l4->txn.auth.user); return 1; } /* Try to find the next occurrence of a cookie name in a cookie header value. * The lookup begins at <hdr>. The pointer and size of the next occurrence of * the cookie value is returned into *value and *value_l, and the function * returns a pointer to the next pointer to search from if the value was found. * Otherwise if the cookie was not found, NULL is returned and neither value * nor value_l are touched. The input <hdr> string should first point to the * header's value, and the <hdr_end> pointer must point to the first character * not part of the value. <list> must be non-zero if value may represent a list * of values (cookie headers). This makes it faster to abort parsing when no * list is expected. */ static char * extract_cookie_value(char *hdr, const char *hdr_end, char *cookie_name, size_t cookie_name_l, int list, char **value, int *value_l) { char *equal, *att_end, *att_beg, *val_beg, *val_end; char *next; /* we search at least a cookie name followed by an equal, and more * generally something like this : * Cookie: NAME1 = VALUE 1 ; NAME2 = VALUE2 ; NAME3 = VALUE3\r\n */ for (att_beg = hdr; att_beg + cookie_name_l + 1 < hdr_end; att_beg = next + 1) { /* Iterate through all cookies on this line */ while (att_beg < hdr_end && http_is_spht[(unsigned char)*att_beg]) att_beg++; /* find att_end : this is the first character after the last non * space before the equal. It may be equal to hdr_end. */ equal = att_end = att_beg; while (equal < hdr_end) { if (*equal == '=' || *equal == ';' || (list && *equal == ',')) break; if (http_is_spht[(unsigned char)*equal++]) continue; att_end = equal; } /* here, <equal> points to '=', a delimitor or the end. <att_end> * is between <att_beg> and <equal>, both may be identical. */ /* look for end of cookie if there is an equal sign */ if (equal < hdr_end && *equal == '=') { /* look for the beginning of the value */ val_beg = equal + 1; while (val_beg < hdr_end && http_is_spht[(unsigned char)*val_beg]) val_beg++; /* find the end of the value, respecting quotes */ next = find_cookie_value_end(val_beg, hdr_end); /* make val_end point to the first white space or delimitor after the value */ val_end = next; while (val_end > val_beg && http_is_spht[(unsigned char)*(val_end - 1)]) val_end--; } else { val_beg = val_end = next = equal; } /* We have nothing to do with attributes beginning with '$'. However, * they will automatically be removed if a header before them is removed, * since they're supposed to be linked together. */ if (*att_beg == '$') continue; /* Ignore cookies with no equal sign */ if (equal == next) continue; /* Now we have the cookie name between att_beg and att_end, and * its value between val_beg and val_end. */ if (att_end - att_beg == cookie_name_l && memcmp(att_beg, cookie_name, cookie_name_l) == 0) { /* let's return this value and indicate where to go on from */ *value = val_beg; *value_l = val_end - val_beg; return next + 1; } /* Set-Cookie headers only have the name in the first attr=value part */ if (!list) break; } return NULL; } /* Fetch a captured HTTP request header. The index is the position of * the "capture" option in the configuration file */ static int smp_fetch_capture_header_req(struct proxy *px, struct session *l4, void *l7, unsigned int opt, const struct arg *args, struct sample *smp, const char *kw) { struct proxy *fe = l4->fe; struct http_txn *txn = l7; int idx; if (!args || args->type != ARGT_UINT) return 0; idx = args->data.uint; if (idx > (fe->nb_req_cap - 1) || txn->req.cap == NULL || txn->req.cap[idx] == NULL) return 0; smp->type = SMP_T_STR; smp->flags |= SMP_F_CONST; smp->data.str.str = txn->req.cap[idx]; smp->data.str.len = strlen(txn->req.cap[idx]); return 1; } /* Fetch a captured HTTP response header. The index is the position of * the "capture" option in the configuration file */ static int smp_fetch_capture_header_res(struct proxy *px, struct session *l4, void *l7, unsigned int opt, const struct arg *args, struct sample *smp, const char *kw) { struct proxy *fe = l4->fe; struct http_txn *txn = l7; int idx; if (!args || args->type != ARGT_UINT) return 0; idx = args->data.uint; if (idx > (fe->nb_rsp_cap - 1) || txn->rsp.cap == NULL || txn->rsp.cap[idx] == NULL) return 0; smp->type = SMP_T_STR; smp->flags |= SMP_F_CONST; smp->data.str.str = txn->rsp.cap[idx]; smp->data.str.len = strlen(txn->rsp.cap[idx]); return 1; } /* Extracts the METHOD in the HTTP request, the txn->uri should be filled before the call */ static int smp_fetch_capture_req_method(struct proxy *px, struct session *l4, void *l7, unsigned int opt, const struct arg *args, struct sample *smp, const char *kw) { struct chunk *temp; struct http_txn *txn = l7; char *ptr; if (!txn->uri) return 0; ptr = txn->uri; while (*ptr != ' ' && *ptr != '\0') /* find first space */ ptr++; temp = get_trash_chunk(); temp->str = txn->uri; temp->len = ptr - txn->uri; smp->data.str = *temp; smp->type = SMP_T_STR; smp->flags = SMP_F_CONST; return 1; } /* Extracts the path in the HTTP request, the txn->uri should be filled before the call */ static int smp_fetch_capture_req_uri(struct proxy *px, struct session *l4, void *l7, unsigned int opt, const struct arg *args, struct sample *smp, const char *kw) { struct chunk *temp; struct http_txn *txn = l7; char *ptr; if (!txn->uri) return 0; ptr = txn->uri; while (*ptr != ' ' && *ptr != '\0') /* find first space */ ptr++; if (!*ptr) return 0; ptr++; /* skip the space */ temp = get_trash_chunk(); ptr = temp->str = http_get_path_from_string(ptr); if (!ptr) return 0; while (*ptr != ' ' && *ptr != '\0') /* find space after URI */ ptr++; smp->data.str = *temp; smp->data.str.len = ptr - temp->str; smp->type = SMP_T_STR; smp->flags = SMP_F_CONST; return 1; } /* Retrieves the HTTP version from the request (either 1.0 or 1.1) and emits it * as a string (either "HTTP/1.0" or "HTTP/1.1"). */ static int smp_fetch_capture_req_ver(struct proxy *px, struct session *l4, void *l7, unsigned int opt, const struct arg *args, struct sample *smp, const char *kw) { struct http_txn *txn = l7; if (txn->req.msg_state < HTTP_MSG_HDR_FIRST) return 0; if (txn->req.flags & HTTP_MSGF_VER_11) smp->data.str.str = "HTTP/1.1"; else smp->data.str.str = "HTTP/1.0"; smp->data.str.len = 8; smp->type = SMP_T_STR; smp->flags = SMP_F_CONST; return 1; } /* Retrieves the HTTP version from the response (either 1.0 or 1.1) and emits it * as a string (either "HTTP/1.0" or "HTTP/1.1"). */ static int smp_fetch_capture_res_ver(struct proxy *px, struct session *l4, void *l7, unsigned int opt, const struct arg *args, struct sample *smp, const char *kw) { struct http_txn *txn = l7; if (txn->rsp.msg_state < HTTP_MSG_HDR_FIRST) return 0; if (txn->rsp.flags & HTTP_MSGF_VER_11) smp->data.str.str = "HTTP/1.1"; else smp->data.str.str = "HTTP/1.0"; smp->data.str.len = 8; smp->type = SMP_T_STR; smp->flags = SMP_F_CONST; return 1; } /* Iterate over all cookies present in a message. The context is stored in * smp->ctx.a[0] for the in-header position, smp->ctx.a[1] for the * end-of-header-value, and smp->ctx.a[2] for the hdr_ctx. Depending on * the direction, multiple cookies may be parsed on the same line or not. * The cookie name is in args and the name length in args->data.str.len. * Accepts exactly 1 argument of type string. If the input options indicate * that no iterating is desired, then only last value is fetched if any. * The returned sample is of type CSTR. Can be used to parse cookies in other * files. */ int smp_fetch_cookie(struct proxy *px, struct session *l4, void *l7, unsigned int opt, const struct arg *args, struct sample *smp, const char *kw) { struct http_txn *txn = l7; struct hdr_idx *idx = &txn->hdr_idx; struct hdr_ctx *ctx = smp->ctx.a[2]; const struct http_msg *msg; const char *hdr_name; int hdr_name_len; char *sol; int occ = 0; int found = 0; if (!args || args->type != ARGT_STR) return 0; if (!ctx) { /* first call */ ctx = &static_hdr_ctx; ctx->idx = 0; smp->ctx.a[2] = ctx; } CHECK_HTTP_MESSAGE_FIRST(); if ((opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ) { msg = &txn->req; hdr_name = "Cookie"; hdr_name_len = 6; } else { msg = &txn->rsp; hdr_name = "Set-Cookie"; hdr_name_len = 10; } if (!occ && !(opt & SMP_OPT_ITERATE)) /* no explicit occurrence and single fetch => last cookie by default */ occ = -1; /* OK so basically here, either we want only one value and it's the * last one, or we want to iterate over all of them and we fetch the * next one. */ sol = msg->chn->buf->p; if (!(smp->flags & SMP_F_NOT_LAST)) { /* search for the header from the beginning, we must first initialize * the search parameters. */ smp->ctx.a[0] = NULL; ctx->idx = 0; } smp->flags |= SMP_F_VOL_HDR; while (1) { /* Note: smp->ctx.a[0] == NULL every time we need to fetch a new header */ if (!smp->ctx.a[0]) { if (!http_find_header2(hdr_name, hdr_name_len, sol, idx, ctx)) goto out; if (ctx->vlen < args->data.str.len + 1) continue; smp->ctx.a[0] = ctx->line + ctx->val; smp->ctx.a[1] = smp->ctx.a[0] + ctx->vlen; } smp->type = SMP_T_STR; smp->flags |= SMP_F_CONST; smp->ctx.a[0] = extract_cookie_value(smp->ctx.a[0], smp->ctx.a[1], args->data.str.str, args->data.str.len, (opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ, &smp->data.str.str, &smp->data.str.len); if (smp->ctx.a[0]) { found = 1; if (occ >= 0) { /* one value was returned into smp->data.str.{str,len} */ smp->flags |= SMP_F_NOT_LAST; return 1; } } /* if we're looking for last occurrence, let's loop */ } /* all cookie headers and values were scanned. If we're looking for the * last occurrence, we may return it now. */ out: smp->flags &= ~SMP_F_NOT_LAST; return found; } /* Iterate over all cookies present in a request to count how many occurrences * match the name in args and args->data.str.len. If <multi> is non-null, then * multiple cookies may be parsed on the same line. The returned sample is of * type UINT. Accepts exactly 1 argument of type string. */ static int smp_fetch_cookie_cnt(struct proxy *px, struct session *l4, void *l7, unsigned int opt, const struct arg *args, struct sample *smp, const char *kw) { struct http_txn *txn = l7; struct hdr_idx *idx = &txn->hdr_idx; struct hdr_ctx ctx; const struct http_msg *msg; const char *hdr_name; int hdr_name_len; int cnt; char *val_beg, *val_end; char *sol; if (!args || args->type != ARGT_STR) return 0; CHECK_HTTP_MESSAGE_FIRST(); if ((opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ) { msg = &txn->req; hdr_name = "Cookie"; hdr_name_len = 6; } else { msg = &txn->rsp; hdr_name = "Set-Cookie"; hdr_name_len = 10; } sol = msg->chn->buf->p; val_end = val_beg = NULL; ctx.idx = 0; cnt = 0; while (1) { /* Note: val_beg == NULL every time we need to fetch a new header */ if (!val_beg) { if (!http_find_header2(hdr_name, hdr_name_len, sol, idx, &ctx)) break; if (ctx.vlen < args->data.str.len + 1) continue; val_beg = ctx.line + ctx.val; val_end = val_beg + ctx.vlen; } smp->type = SMP_T_STR; smp->flags |= SMP_F_CONST; while ((val_beg = extract_cookie_value(val_beg, val_end, args->data.str.str, args->data.str.len, (opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ, &smp->data.str.str, &smp->data.str.len))) { cnt++; } } smp->type = SMP_T_UINT; smp->data.uint = cnt; smp->flags |= SMP_F_VOL_HDR; return 1; } /* Fetch an cookie's integer value. The integer value is returned. It * takes a mandatory argument of type string. It relies on smp_fetch_cookie(). */ static int smp_fetch_cookie_val(struct proxy *px, struct session *l4, void *l7, unsigned int opt, const struct arg *args, struct sample *smp, const char *kw) { int ret = smp_fetch_cookie(px, l4, l7, opt, args, smp, kw); if (ret > 0) { smp->type = SMP_T_UINT; smp->data.uint = strl2ic(smp->data.str.str, smp->data.str.len); } return ret; } /************************************************************************/ /* The code below is dedicated to sample fetches */ /************************************************************************/ /* * Given a path string and its length, find the position of beginning of the * query string. Returns NULL if no query string is found in the path. * * Example: if path = "/foo/bar/fubar?yo=mama;ye=daddy", and n = 22: * * find_query_string(path, n) points to "yo=mama;ye=daddy" string. */ static inline char *find_param_list(char *path, size_t path_l, char delim) { char *p; p = memchr(path, delim, path_l); return p ? p + 1 : NULL; } static inline int is_param_delimiter(char c, char delim) { return c == '&' || c == ';' || c == delim; } /* * Given a url parameter, find the starting position of the first occurence, * or NULL if the parameter is not found. * * Example: if query_string is "yo=mama;ye=daddy" and url_param_name is "ye", * the function will return query_string+8. */ static char* find_url_param_pos(char* query_string, size_t query_string_l, char* url_param_name, size_t url_param_name_l, char delim) { char *pos, *last; pos = query_string; last = query_string + query_string_l - url_param_name_l - 1; while (pos <= last) { if (pos[url_param_name_l] == '=') { if (memcmp(pos, url_param_name, url_param_name_l) == 0) return pos; pos += url_param_name_l + 1; } while (pos <= last && !is_param_delimiter(*pos, delim)) pos++; pos++; } return NULL; } /* * Given a url parameter name, returns its value and size into *value and * *value_l respectively, and returns non-zero. If the parameter is not found, * zero is returned and value/value_l are not touched. */ static int find_url_param_value(char* path, size_t path_l, char* url_param_name, size_t url_param_name_l, char** value, int* value_l, char delim) { char *query_string, *qs_end; char *arg_start; char *value_start, *value_end; query_string = find_param_list(path, path_l, delim); if (!query_string) return 0; qs_end = path + path_l; arg_start = find_url_param_pos(query_string, qs_end - query_string, url_param_name, url_param_name_l, delim); if (!arg_start) return 0; value_start = arg_start + url_param_name_l + 1; value_end = value_start; while ((value_end < qs_end) && !is_param_delimiter(*value_end, delim)) value_end++; *value = value_start; *value_l = value_end - value_start; return value_end != value_start; } static int smp_fetch_url_param(struct proxy *px, struct session *l4, void *l7, unsigned int opt, const struct arg *args, struct sample *smp, const char *kw) { char delim = '?'; struct http_txn *txn = l7; struct http_msg *msg = &txn->req; if (!args || args[0].type != ARGT_STR || (args[1].type && args[1].type != ARGT_STR)) return 0; CHECK_HTTP_MESSAGE_FIRST(); if (args[1].type) delim = *args[1].data.str.str; if (!find_url_param_value(msg->chn->buf->p + msg->sl.rq.u, msg->sl.rq.u_l, args->data.str.str, args->data.str.len, &smp->data.str.str, &smp->data.str.len, delim)) return 0; smp->type = SMP_T_STR; smp->flags = SMP_F_VOL_1ST | SMP_F_CONST; return 1; } /* Return the signed integer value for the specified url parameter (see url_param * above). */ static int smp_fetch_url_param_val(struct proxy *px, struct session *l4, void *l7, unsigned int opt, const struct arg *args, struct sample *smp, const char *kw) { int ret = smp_fetch_url_param(px, l4, l7, opt, args, smp, kw); if (ret > 0) { smp->type = SMP_T_UINT; smp->data.uint = strl2ic(smp->data.str.str, smp->data.str.len); } return ret; } /* This produces a 32-bit hash of the concatenation of the first occurrence of * the Host header followed by the path component if it begins with a slash ('/'). * This means that '*' will not be added, resulting in exactly the first Host * entry. If no Host header is found, then the path is used. The resulting value * is hashed using the url hash followed by a full avalanche hash and provides a * 32-bit integer value. This fetch is useful for tracking per-URL activity on * high-traffic sites without having to store whole paths. * this differs from the base32 functions in that it includes the url parameters * as well as the path */ static int smp_fetch_url32(struct proxy *px, struct session *l4, void *l7, unsigned int opt, const struct arg *args, struct sample *smp, const char *kw) { struct http_txn *txn = l7; struct hdr_ctx ctx; unsigned int hash = 0; char *ptr, *beg, *end; int len; CHECK_HTTP_MESSAGE_FIRST(); ctx.idx = 0; if (http_find_header2("Host", 4, txn->req.chn->buf->p, &txn->hdr_idx, &ctx)) { /* OK we have the header value in ctx.line+ctx.val for ctx.vlen bytes */ ptr = ctx.line + ctx.val; len = ctx.vlen; while (len--) hash = *(ptr++) + (hash << 6) + (hash << 16) - hash; } /* now retrieve the path */ end = txn->req.chn->buf->p + txn->req.sl.rq.u + txn->req.sl.rq.u_l; beg = http_get_path(txn); if (!beg) beg = end; for (ptr = beg; ptr < end ; ptr++); if (beg < ptr && *beg == '/') { while (beg < ptr) hash = *(beg++) + (hash << 6) + (hash << 16) - hash; } hash = full_hash(hash); smp->type = SMP_T_UINT; smp->data.uint = hash; smp->flags = SMP_F_VOL_1ST; return 1; } /* This concatenates the source address with the 32-bit hash of the Host and * URL as returned by smp_fetch_base32(). The idea is to have per-source and * per-url counters. The result is a binary block from 8 to 20 bytes depending * on the source address length. The URL hash is stored before the address so * that in environments where IPv6 is insignificant, truncating the output to * 8 bytes would still work. */ static int smp_fetch_url32_src(struct proxy *px, struct session *l4, void *l7, unsigned int opt, const struct arg *args, struct sample *smp, const char *kw) { struct chunk *temp; struct connection *cli_conn = objt_conn(l4->si[0].end); if (!smp_fetch_url32(px, l4, l7, opt, args, smp, kw)) return 0; temp = get_trash_chunk(); memcpy(temp->str + temp->len, &smp->data.uint, sizeof(smp->data.uint)); temp->len += sizeof(smp->data.uint); switch (cli_conn->addr.from.ss_family) { case AF_INET: memcpy(temp->str + temp->len, &((struct sockaddr_in *)&cli_conn->addr.from)->sin_addr, 4); temp->len += 4; break; case AF_INET6: memcpy(temp->str + temp->len, &((struct sockaddr_in6 *)&cli_conn->addr.from)->sin6_addr, 16); temp->len += 16; break; default: return 0; } smp->data.str = *temp; smp->type = SMP_T_BIN; return 1; } /* This function is used to validate the arguments passed to any "hdr" fetch * keyword. These keywords support an optional positive or negative occurrence * number. We must ensure that the number is greater than -MAX_HDR_HISTORY. It * is assumed that the types are already the correct ones. Returns 0 on error, * non-zero if OK. If <err> is not NULL, it will be filled with a pointer to an * error message in case of error, that the caller is responsible for freeing. * The initial location must either be freeable or NULL. */ static int val_hdr(struct arg *arg, char **err_msg) { if (arg && arg[1].type == ARGT_SINT && arg[1].data.sint < -MAX_HDR_HISTORY) { memprintf(err_msg, "header occurrence must be >= %d", -MAX_HDR_HISTORY); return 0; } return 1; } /* takes an UINT value on input supposed to represent the time since EPOCH, * adds an optional offset found in args[0] and emits a string representing * the date in RFC-1123/5322 format. */ static int sample_conv_http_date(const struct arg *args, struct sample *smp) { const char day[7][4] = { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" }; const char mon[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; struct chunk *temp; struct tm *tm; time_t curr_date = smp->data.uint; /* add offset */ if (args && (args[0].type == ARGT_SINT || args[0].type == ARGT_UINT)) curr_date += args[0].data.sint; tm = gmtime(&curr_date); temp = get_trash_chunk(); temp->len = snprintf(temp->str, temp->size - temp->len, "%s, %02d %s %04d %02d:%02d:%02d GMT", day[tm->tm_wday], tm->tm_mday, mon[tm->tm_mon], 1900+tm->tm_year, tm->tm_hour, tm->tm_min, tm->tm_sec); smp->data.str = *temp; smp->type = SMP_T_STR; return 1; } /* Match language range with language tag. RFC2616 14.4: * * A language-range matches a language-tag if it exactly equals * the tag, or if it exactly equals a prefix of the tag such * that the first tag character following the prefix is "-". * * Return 1 if the strings match, else return 0. */ static inline int language_range_match(const char *range, int range_len, const char *tag, int tag_len) { const char *end = range + range_len; const char *tend = tag + tag_len; while (range < end) { if (*range == '-' && tag == tend) return 1; if (*range != *tag || tag == tend) return 0; range++; tag++; } /* Return true only if the last char of the tag is matched. */ return tag == tend; } /* Arguments: The list of expected value, the number of parts returned and the separator */ static int sample_conv_q_prefered(const struct arg *args, struct sample *smp) { const char *al = smp->data.str.str; const char *end = al + smp->data.str.len; const char *token; int toklen; int qvalue; const char *str; const char *w; int best_q = 0; /* Set the constant to the sample, because the output of the * function will be peek in the constant configuration string. */ smp->flags |= SMP_F_CONST; smp->data.str.size = 0; smp->data.str.str = ""; smp->data.str.len = 0; /* Parse the accept language */ while (1) { /* Jump spaces, quit if the end is detected. */ while (al < end && isspace((unsigned char)*al)) al++; if (al >= end) break; /* Start of the fisrt word. */ token = al; /* Look for separator: isspace(), ',' or ';'. Next value if 0 length word. */ while (al < end && *al != ';' && *al != ',' && !isspace((unsigned char)*al)) al++; if (al == token) goto expect_comma; /* Length of the token. */ toklen = al - token; qvalue = 1000; /* Check if the token exists in the list. If the token not exists, * jump to the next token. */ str = args[0].data.str.str; w = str; while (1) { if (*str == ';' || *str == '\0') { if (language_range_match(token, toklen, w, str-w)) goto look_for_q; if (*str == '\0') goto expect_comma; w = str + 1; } str++; } goto expect_comma; look_for_q: /* Jump spaces, quit if the end is detected. */ while (al < end && isspace((unsigned char)*al)) al++; if (al >= end) goto process_value; /* If ',' is found, process the result */ if (*al == ',') goto process_value; /* If the character is different from ';', look * for the end of the header part in best effort. */ if (*al != ';') goto expect_comma; /* Assumes that the char is ';', now expect "q=". */ al++; /* Jump spaces, process value if the end is detected. */ while (al < end && isspace((unsigned char)*al)) al++; if (al >= end) goto process_value; /* Expect 'q'. If no 'q', continue in best effort */ if (*al != 'q') goto process_value; al++; /* Jump spaces, process value if the end is detected. */ while (al < end && isspace((unsigned char)*al)) al++; if (al >= end) goto process_value; /* Expect '='. If no '=', continue in best effort */ if (*al != '=') goto process_value; al++; /* Jump spaces, process value if the end is detected. */ while (al < end && isspace((unsigned char)*al)) al++; if (al >= end) goto process_value; /* Parse the q value. */ qvalue = parse_qvalue(al, &al); process_value: /* If the new q value is the best q value, then store the associated * language in the response. If qvalue is the biggest value (1000), * break the process. */ if (qvalue > best_q) { smp->data.str.str = (char *)w; smp->data.str.len = str - w; if (qvalue >= 1000) break; best_q = qvalue; } expect_comma: /* Expect comma or end. If the end is detected, quit the loop. */ while (al < end && *al != ',') al++; if (al >= end) break; /* Comma is found, jump it and restart the analyzer. */ al++; } /* Set default value if required. */ if (smp->data.str.len == 0 && args[1].type == ARGT_STR) { smp->data.str.str = args[1].data.str.str; smp->data.str.len = args[1].data.str.len; } /* Return true only if a matching language was found. */ return smp->data.str.len != 0; } /* * Return the struct http_req_action_kw associated to a keyword. */ struct http_req_action_kw *action_http_req_custom(const char *kw) { if (!LIST_ISEMPTY(&http_req_keywords.list)) { struct http_req_action_kw_list *kw_list; int i; list_for_each_entry(kw_list, &http_req_keywords.list, list) { for (i = 0; kw_list->kw[i].kw != NULL; i++) { if (!strcmp(kw, kw_list->kw[i].kw)) return &kw_list->kw[i]; } } } return NULL; } /* * Return the struct http_res_action_kw associated to a keyword. */ struct http_res_action_kw *action_http_res_custom(const char *kw) { if (!LIST_ISEMPTY(&http_res_keywords.list)) { struct http_res_action_kw_list *kw_list; int i; list_for_each_entry(kw_list, &http_res_keywords.list, list) { for (i = 0; kw_list->kw[i].kw != NULL; i++) { if (!strcmp(kw, kw_list->kw[i].kw)) return &kw_list->kw[i]; } } } return NULL; } /************************************************************************/ /* All supported ACL keywords must be declared here. */ /************************************************************************/ /* Note: must not be declared <const> as its list will be overwritten. * Please take care of keeping this list alphabetically sorted. */ static struct acl_kw_list acl_kws = {ILH, { { "base", "base", PAT_MATCH_STR }, { "base_beg", "base", PAT_MATCH_BEG }, { "base_dir", "base", PAT_MATCH_DIR }, { "base_dom", "base", PAT_MATCH_DOM }, { "base_end", "base", PAT_MATCH_END }, { "base_len", "base", PAT_MATCH_LEN }, { "base_reg", "base", PAT_MATCH_REG }, { "base_sub", "base", PAT_MATCH_SUB }, { "cook", "req.cook", PAT_MATCH_STR }, { "cook_beg", "req.cook", PAT_MATCH_BEG }, { "cook_dir", "req.cook", PAT_MATCH_DIR }, { "cook_dom", "req.cook", PAT_MATCH_DOM }, { "cook_end", "req.cook", PAT_MATCH_END }, { "cook_len", "req.cook", PAT_MATCH_LEN }, { "cook_reg", "req.cook", PAT_MATCH_REG }, { "cook_sub", "req.cook", PAT_MATCH_SUB }, { "hdr", "req.hdr", PAT_MATCH_STR }, { "hdr_beg", "req.hdr", PAT_MATCH_BEG }, { "hdr_dir", "req.hdr", PAT_MATCH_DIR }, { "hdr_dom", "req.hdr", PAT_MATCH_DOM }, { "hdr_end", "req.hdr", PAT_MATCH_END }, { "hdr_len", "req.hdr", PAT_MATCH_LEN }, { "hdr_reg", "req.hdr", PAT_MATCH_REG }, { "hdr_sub", "req.hdr", PAT_MATCH_SUB }, /* these two declarations uses strings with list storage (in place * of tree storage). The basic match is PAT_MATCH_STR, but the indexation * and delete functions are relative to the list management. The parse * and match method are related to the corresponding fetch methods. This * is very particular ACL declaration mode. */ { "http_auth_group", NULL, PAT_MATCH_STR, NULL, pat_idx_list_str, pat_del_list_ptr, NULL, pat_match_auth }, { "method", NULL, PAT_MATCH_STR, pat_parse_meth, pat_idx_list_str, pat_del_list_ptr, NULL, pat_match_meth }, { "path", "path", PAT_MATCH_STR }, { "path_beg", "path", PAT_MATCH_BEG }, { "path_dir", "path", PAT_MATCH_DIR }, { "path_dom", "path", PAT_MATCH_DOM }, { "path_end", "path", PAT_MATCH_END }, { "path_len", "path", PAT_MATCH_LEN }, { "path_reg", "path", PAT_MATCH_REG }, { "path_sub", "path", PAT_MATCH_SUB }, { "req_ver", "req.ver", PAT_MATCH_STR }, { "resp_ver", "res.ver", PAT_MATCH_STR }, { "scook", "res.cook", PAT_MATCH_STR }, { "scook_beg", "res.cook", PAT_MATCH_BEG }, { "scook_dir", "res.cook", PAT_MATCH_DIR }, { "scook_dom", "res.cook", PAT_MATCH_DOM }, { "scook_end", "res.cook", PAT_MATCH_END }, { "scook_len", "res.cook", PAT_MATCH_LEN }, { "scook_reg", "res.cook", PAT_MATCH_REG }, { "scook_sub", "res.cook", PAT_MATCH_SUB }, { "shdr", "res.hdr", PAT_MATCH_STR }, { "shdr_beg", "res.hdr", PAT_MATCH_BEG }, { "shdr_dir", "res.hdr", PAT_MATCH_DIR }, { "shdr_dom", "res.hdr", PAT_MATCH_DOM }, { "shdr_end", "res.hdr", PAT_MATCH_END }, { "shdr_len", "res.hdr", PAT_MATCH_LEN }, { "shdr_reg", "res.hdr", PAT_MATCH_REG }, { "shdr_sub", "res.hdr", PAT_MATCH_SUB }, { "url", "url", PAT_MATCH_STR }, { "url_beg", "url", PAT_MATCH_BEG }, { "url_dir", "url", PAT_MATCH_DIR }, { "url_dom", "url", PAT_MATCH_DOM }, { "url_end", "url", PAT_MATCH_END }, { "url_len", "url", PAT_MATCH_LEN }, { "url_reg", "url", PAT_MATCH_REG }, { "url_sub", "url", PAT_MATCH_SUB }, { "urlp", "urlp", PAT_MATCH_STR }, { "urlp_beg", "urlp", PAT_MATCH_BEG }, { "urlp_dir", "urlp", PAT_MATCH_DIR }, { "urlp_dom", "urlp", PAT_MATCH_DOM }, { "urlp_end", "urlp", PAT_MATCH_END }, { "urlp_len", "urlp", PAT_MATCH_LEN }, { "urlp_reg", "urlp", PAT_MATCH_REG }, { "urlp_sub", "urlp", PAT_MATCH_SUB }, { /* END */ }, }}; /************************************************************************/ /* All supported pattern keywords must be declared here. */ /************************************************************************/ /* Note: must not be declared <const> as its list will be overwritten */ static struct sample_fetch_kw_list sample_fetch_keywords = {ILH, { { "base", smp_fetch_base, 0, NULL, SMP_T_STR, SMP_USE_HRQHV }, { "base32", smp_fetch_base32, 0, NULL, SMP_T_UINT, SMP_USE_HRQHV }, { "base32+src", smp_fetch_base32_src, 0, NULL, SMP_T_BIN, SMP_USE_HRQHV }, /* capture are allocated and are permanent in the session */ { "capture.req.hdr", smp_fetch_capture_header_req, ARG1(1, UINT), NULL, SMP_T_STR, SMP_USE_HRQHP }, /* retrieve these captures from the HTTP logs */ { "capture.req.method", smp_fetch_capture_req_method, 0, NULL, SMP_T_STR, SMP_USE_HRQHP }, { "capture.req.uri", smp_fetch_capture_req_uri, 0, NULL, SMP_T_STR, SMP_USE_HRQHP }, { "capture.req.ver", smp_fetch_capture_req_ver, 0, NULL, SMP_T_STR, SMP_USE_HRQHP }, { "capture.res.hdr", smp_fetch_capture_header_res, ARG1(1, UINT), NULL, SMP_T_STR, SMP_USE_HRSHP }, { "capture.res.ver", smp_fetch_capture_res_ver, 0, NULL, SMP_T_STR, SMP_USE_HRQHP }, /* cookie is valid in both directions (eg: for "stick ...") but cook* * are only here to match the ACL's name, are request-only and are used * for ACL compatibility only. */ { "cook", smp_fetch_cookie, ARG1(0,STR), NULL, SMP_T_STR, SMP_USE_HRQHV }, { "cookie", smp_fetch_cookie, ARG1(0,STR), NULL, SMP_T_STR, SMP_USE_HRQHV|SMP_USE_HRSHV }, { "cook_cnt", smp_fetch_cookie_cnt, ARG1(0,STR), NULL, SMP_T_UINT, SMP_USE_HRQHV }, { "cook_val", smp_fetch_cookie_val, ARG1(0,STR), NULL, SMP_T_UINT, SMP_USE_HRQHV }, /* hdr is valid in both directions (eg: for "stick ...") but hdr_* are * only here to match the ACL's name, are request-only and are used for * ACL compatibility only. */ { "hdr", smp_fetch_hdr, ARG2(0,STR,SINT), val_hdr, SMP_T_STR, SMP_USE_HRQHV|SMP_USE_HRSHV }, { "hdr_cnt", smp_fetch_hdr_cnt, ARG1(0,STR), NULL, SMP_T_UINT, SMP_USE_HRQHV }, { "hdr_ip", smp_fetch_hdr_ip, ARG2(0,STR,SINT), val_hdr, SMP_T_IPV4, SMP_USE_HRQHV }, { "hdr_val", smp_fetch_hdr_val, ARG2(0,STR,SINT), val_hdr, SMP_T_UINT, SMP_USE_HRQHV }, { "http_auth", smp_fetch_http_auth, ARG1(1,USR), NULL, SMP_T_BOOL, SMP_USE_HRQHV }, { "http_auth_group", smp_fetch_http_auth_grp, ARG1(1,USR), NULL, SMP_T_STR, SMP_USE_HRQHV }, { "http_first_req", smp_fetch_http_first_req, 0, NULL, SMP_T_BOOL, SMP_USE_HRQHP }, { "method", smp_fetch_meth, 0, NULL, SMP_T_METH, SMP_USE_HRQHP }, { "path", smp_fetch_path, 0, NULL, SMP_T_STR, SMP_USE_HRQHV }, /* HTTP protocol on the request path */ { "req.proto_http", smp_fetch_proto_http, 0, NULL, SMP_T_BOOL, SMP_USE_HRQHP }, { "req_proto_http", smp_fetch_proto_http, 0, NULL, SMP_T_BOOL, SMP_USE_HRQHP }, /* HTTP version on the request path */ { "req.ver", smp_fetch_rqver, 0, NULL, SMP_T_STR, SMP_USE_HRQHV }, { "req_ver", smp_fetch_rqver, 0, NULL, SMP_T_STR, SMP_USE_HRQHV }, /* HTTP version on the response path */ { "res.ver", smp_fetch_stver, 0, NULL, SMP_T_STR, SMP_USE_HRSHV }, { "resp_ver", smp_fetch_stver, 0, NULL, SMP_T_STR, SMP_USE_HRSHV }, /* explicit req.{cook,hdr} are used to force the fetch direction to be request-only */ { "req.cook", smp_fetch_cookie, ARG1(0,STR), NULL, SMP_T_STR, SMP_USE_HRQHV }, { "req.cook_cnt", smp_fetch_cookie_cnt, ARG1(0,STR), NULL, SMP_T_UINT, SMP_USE_HRQHV }, { "req.cook_val", smp_fetch_cookie_val, ARG1(0,STR), NULL, SMP_T_UINT, SMP_USE_HRQHV }, { "req.fhdr", smp_fetch_fhdr, ARG2(0,STR,SINT), val_hdr, SMP_T_STR, SMP_USE_HRQHV }, { "req.fhdr_cnt", smp_fetch_fhdr_cnt, ARG1(0,STR), NULL, SMP_T_UINT, SMP_USE_HRQHV }, { "req.hdr", smp_fetch_hdr, ARG2(0,STR,SINT), val_hdr, SMP_T_STR, SMP_USE_HRQHV }, { "req.hdr_cnt", smp_fetch_hdr_cnt, ARG1(0,STR), NULL, SMP_T_UINT, SMP_USE_HRQHV }, { "req.hdr_ip", smp_fetch_hdr_ip, ARG2(0,STR,SINT), val_hdr, SMP_T_IPV4, SMP_USE_HRQHV }, { "req.hdr_val", smp_fetch_hdr_val, ARG2(0,STR,SINT), val_hdr, SMP_T_UINT, SMP_USE_HRQHV }, /* explicit req.{cook,hdr} are used to force the fetch direction to be response-only */ { "res.cook", smp_fetch_cookie, ARG1(0,STR), NULL, SMP_T_STR, SMP_USE_HRSHV }, { "res.cook_cnt", smp_fetch_cookie_cnt, ARG1(0,STR), NULL, SMP_T_UINT, SMP_USE_HRSHV }, { "res.cook_val", smp_fetch_cookie_val, ARG1(0,STR), NULL, SMP_T_UINT, SMP_USE_HRSHV }, { "res.fhdr", smp_fetch_fhdr, ARG2(0,STR,SINT), val_hdr, SMP_T_STR, SMP_USE_HRSHV }, { "res.fhdr_cnt", smp_fetch_fhdr_cnt, ARG1(0,STR), NULL, SMP_T_UINT, SMP_USE_HRSHV }, { "res.hdr", smp_fetch_hdr, ARG2(0,STR,SINT), val_hdr, SMP_T_STR, SMP_USE_HRSHV }, { "res.hdr_cnt", smp_fetch_hdr_cnt, ARG1(0,STR), NULL, SMP_T_UINT, SMP_USE_HRSHV }, { "res.hdr_ip", smp_fetch_hdr_ip, ARG2(0,STR,SINT), val_hdr, SMP_T_IPV4, SMP_USE_HRSHV }, { "res.hdr_val", smp_fetch_hdr_val, ARG2(0,STR,SINT), val_hdr, SMP_T_UINT, SMP_USE_HRSHV }, /* scook is valid only on the response and is used for ACL compatibility */ { "scook", smp_fetch_cookie, ARG1(0,STR), NULL, SMP_T_STR, SMP_USE_HRSHV }, { "scook_cnt", smp_fetch_cookie_cnt, ARG1(0,STR), NULL, SMP_T_UINT, SMP_USE_HRSHV }, { "scook_val", smp_fetch_cookie_val, ARG1(0,STR), NULL, SMP_T_UINT, SMP_USE_HRSHV }, { "set-cookie", smp_fetch_cookie, ARG1(0,STR), NULL, SMP_T_STR, SMP_USE_HRSHV }, /* deprecated */ /* shdr is valid only on the response and is used for ACL compatibility */ { "shdr", smp_fetch_hdr, ARG2(0,STR,SINT), val_hdr, SMP_T_STR, SMP_USE_HRSHV }, { "shdr_cnt", smp_fetch_hdr_cnt, ARG1(0,STR), NULL, SMP_T_UINT, SMP_USE_HRSHV }, { "shdr_ip", smp_fetch_hdr_ip, ARG2(0,STR,SINT), val_hdr, SMP_T_IPV4, SMP_USE_HRSHV }, { "shdr_val", smp_fetch_hdr_val, ARG2(0,STR,SINT), val_hdr, SMP_T_UINT, SMP_USE_HRSHV }, { "status", smp_fetch_stcode, 0, NULL, SMP_T_UINT, SMP_USE_HRSHP }, { "url", smp_fetch_url, 0, NULL, SMP_T_STR, SMP_USE_HRQHV }, { "url32", smp_fetch_url32, 0, NULL, SMP_T_UINT, SMP_USE_HRQHV }, { "url32+src", smp_fetch_url32_src, 0, NULL, SMP_T_BIN, SMP_USE_HRQHV }, { "url_ip", smp_fetch_url_ip, 0, NULL, SMP_T_IPV4, SMP_USE_HRQHV }, { "url_port", smp_fetch_url_port, 0, NULL, SMP_T_UINT, SMP_USE_HRQHV }, { "url_param", smp_fetch_url_param, ARG2(1,STR,STR), NULL, SMP_T_STR, SMP_USE_HRQHV }, { "urlp" , smp_fetch_url_param, ARG2(1,STR,STR), NULL, SMP_T_STR, SMP_USE_HRQHV }, { "urlp_val", smp_fetch_url_param_val, ARG2(1,STR,STR), NULL, SMP_T_UINT, SMP_USE_HRQHV }, { /* END */ }, }}; /* Note: must not be declared <const> as its list will be overwritten */ static struct sample_conv_kw_list sample_conv_kws = {ILH, { { "http_date", sample_conv_http_date, ARG1(0,SINT), NULL, SMP_T_UINT, SMP_T_STR}, { "language", sample_conv_q_prefered, ARG2(1,STR,STR), NULL, SMP_T_STR, SMP_T_STR}, { NULL, NULL, 0, 0, 0 }, }}; __attribute__((constructor)) static void __http_protocol_init(void) { acl_register_keywords(&acl_kws); sample_register_fetches(&sample_fetch_keywords); sample_register_convs(&sample_conv_kws); } /* * Local variables: * c-indent-level: 8 * c-basic-offset: 8 * End: */
nicescale/haproxy
src/src/proto_http.c
C
gpl-2.0
373,580
<?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_Log * @subpackage Writer * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Syslog.php 23574 2010-12-23 22:58:44Z ramon $ */ /** Zend_Log */ require_once 'Zend/Log.php'; /** Zend_Log_Writer_Abstract */ require_once 'Zend/Log/Writer/Abstract.php'; /** * Writes log messages to syslog * * @category Zend * @package Zend_Log * @subpackage Writer * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Log_Writer_Syslog extends Zend_Log_Writer_Abstract { /** * Maps Zend_Log priorities to PHP's syslog priorities * * @var array */ protected $_priorities = array( Zend_Log::EMERG => LOG_EMERG, Zend_Log::ALERT => LOG_ALERT, Zend_Log::CRIT => LOG_CRIT, Zend_Log::ERR => LOG_ERR, Zend_Log::WARN => LOG_WARNING, Zend_Log::NOTICE => LOG_NOTICE, Zend_Log::INFO => LOG_INFO, Zend_Log::DEBUG => LOG_DEBUG, ); /** * The default log priority - for unmapped custom priorities * * @var string */ protected $_defaultPriority = LOG_NOTICE; /** * Last application name set by a syslog-writer instance * * @var string */ protected static $_lastApplication; /** * Last facility name set by a syslog-writer instance * * @var string */ protected static $_lastFacility; /** * Application name used by this syslog-writer instance * * @var string */ protected $_application = 'Zend_Log'; /** * Facility used by this syslog-writer instance * * @var int */ protected $_facility = LOG_USER; /** * Types of program available to logging of message * * @var array */ protected $_validFacilities = array(); /** * Class constructor * * @param array $params Array of options; may include "application" and "facility" keys * @return void */ public function __construct(array $params = array()) { if (isset($params['application'])) { $this->_application = $params['application']; } $runInitializeSyslog = true; if (isset($params['facility'])) { $this->setFacility($params['facility']); $runInitializeSyslog = false; } if ($runInitializeSyslog) { $this->_initializeSyslog(); } } /** * Create a new instance of Zend_Log_Writer_Syslog * * @param array|Zend_Config $config * @return Zend_Log_Writer_Syslog */ static public function factory($config) { return new self(self::_parseConfig($config)); } /** * Initialize values facilities * * @return void */ protected function _initializeValidFacilities() { $constants = array( 'LOG_AUTH', 'LOG_AUTHPRIV', 'LOG_CRON', 'LOG_DAEMON', 'LOG_KERN', 'LOG_LOCAL0', 'LOG_LOCAL1', 'LOG_LOCAL2', 'LOG_LOCAL3', 'LOG_LOCAL4', 'LOG_LOCAL5', 'LOG_LOCAL6', 'LOG_LOCAL7', 'LOG_LPR', 'LOG_MAIL', 'LOG_NEWS', 'LOG_SYSLOG', 'LOG_USER', 'LOG_UUCP' ); foreach ($constants as $constant) { if (defined($constant)) { $this->_validFacilities[] = constant($constant); } } } /** * Initialize syslog / set application name and facility * * @return void */ protected function _initializeSyslog() { self::$_lastApplication = $this->_application; self::$_lastFacility = $this->_facility; openlog($this->_application, LOG_PID, $this->_facility); } /** * Set syslog facility * * @param int $facility Syslog facility * @return Zend_Log_Writer_Syslog * @throws Zend_Log_Exception for invalid log facility */ public function setFacility($facility) { if ($this->_facility === $facility) { return $this; } if (!count($this->_validFacilities)) { $this->_initializeValidFacilities(); } if (!in_array($facility, $this->_validFacilities)) { require_once 'Zend/Log/Exception.php'; throw new Zend_Log_Exception('Invalid log facility provided; please see http://php.net/openlog for a list of valid facility values'); } if ('WIN' == strtoupper(substr(PHP_OS, 0, 3)) && ($facility !== LOG_USER) ) { require_once 'Zend/Log/Exception.php'; throw new Zend_Log_Exception('Only LOG_USER is a valid log facility on Windows'); } $this->_facility = $facility; $this->_initializeSyslog(); return $this; } /** * Set application name * * @param string $application Application name * @return Zend_Log_Writer_Syslog */ public function setApplicationName($application) { if ($this->_application === $application) { return $this; } $this->_application = $application; $this->_initializeSyslog(); return $this; } /** * Close syslog. * * @return void */ public function shutdown() { closelog(); } /** * Write a message to syslog. * * @param array $event event data * @return void */ protected function _write($event) { if (array_key_exists($event['priority'], $this->_priorities)) { $priority = $this->_priorities[$event['priority']]; } else { $priority = $this->_defaultPriority; } if ($this->_application !== self::$_lastApplication || $this->_facility !== self::$_lastFacility) { $this->_initializeSyslog(); } $message = $event['message']; if ($this->_formatter instanceof Zend_Log_Formatter_Interface) { $message = $this->_formatter->format($event); } syslog($priority, $message); } }
rakesh-sankar/PHP-Framework-Benchmark
zend-1.11.2/library/Zend/Log/Writer/Syslog.php
PHP
gpl-2.0
6,950
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; using SirenOfShame.Lib; using SirenOfShame.Lib.Watcher; using log4net; namespace GoServices { public class GoBuildStatus : BuildStatus { private readonly IEnumerable<XElement> _pipeline; private static readonly ILog _log = MyLogManager.GetLogger(typeof(GoBuildStatus)); public GoBuildStatus(IEnumerable<XElement> pipeline) { _pipeline = pipeline; Name = GetPipelineName(); BuildDefinitionId = GetPipelineName(); BuildStatusEnum = GetBuildStatus(); BuildId = GetBuildId(); LocalStartTime = GetLocalStartTime(); Url = GetUrl(); if (BuildStatusEnum == BuildStatusEnum.Broken) { RequestedBy = GetRequestedBy(); } } private string GetPipelineName() { return _pipeline.First().Attribute("name").Value.Split(' ').First(); } private BuildStatusEnum GetBuildStatus() { if (_pipeline.Select(x => x.Attribute("activity").Value).Any(a => a == "Building")) { return BuildStatusEnum.InProgress; } if (_pipeline.Select(x => x.Attribute("activity").Value).Any(a => a == "Sleeping") && _pipeline.Select(x => x.Attribute("lastBuildStatus").Value).All(s => s == "Success")) { return BuildStatusEnum.Working; } if (_pipeline.Select(x => x.Attribute("activity").Value).Any(a => a == "Sleeping") && _pipeline.Select(x => x.Attribute("lastBuildStatus").Value).Any(s => s == "Failure")) { return BuildStatusEnum.Broken; } return BuildStatusEnum.Unknown; } private string GetBuildId() { return _pipeline.First().Attribute("lastBuildLabel").Value; } private DateTime GetLocalStartTime() { return Convert.ToDateTime(_pipeline.First().Attribute("lastBuildTime").Value); } private string GetUrl() { return _pipeline.First().Attribute("webUrl").Value; } private string GetRequestedBy() { var failedStage = _pipeline.FirstOrDefault(x => x.Element("messages") != null && x.Element("messages").Element("message") != null); try { return failedStage != null ? failedStage.Element("messages").Element("message").Attribute("text").Value : string.Empty; } catch (Exception) { return string.Empty; } } } }
MikeMangialardi/SirenOfShame-WithGoPlugin
GoServices/GoBuildStatus.cs
C#
gpl-2.0
2,921
cmd_drivers/media/usb/dvb-usb/dvb-usb-dib0700.o := ../tools/arm-bcm2708/arm-bcm2708hardfp-linux-gnueabi/bin/arm-bcm2708hardfp-linux-gnueabi-ld -EL -r -o drivers/media/usb/dvb-usb/dvb-usb-dib0700.o drivers/media/usb/dvb-usb/dib0700_core.o drivers/media/usb/dvb-usb/dib0700_devices.o
avareldalton85/rpi2-linux-rt
drivers/media/usb/dvb-usb/.dvb-usb-dib0700.o.cmd
Batchfile
gpl-2.0
286
// // CategoryModel.h // healthfood // // Created by lanou on 15/6/22. // Copyright (c) 2015年 hastar. All rights reserved. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @interface CategoryModel : NSObject @property (nonatomic, retain)NSString *title; @property (nonatomic, retain)UIImage *image; @property (nonatomic, retain)NSArray *idArray; -(instancetype)initWithTitle:(NSString *)title andImageName:(NSString *)imageName andIdArray:(NSArray *)array; @end
hastar/healthFood
healthfood/Model/CategoryModel.h
C
gpl-2.0
486
<?PHP // $Id: dbperformance.php,v 1.12 2008/06/09 18:48:28 skodak Exp $ // dbperformance.php - shows latest ADOdb stats for the current server require_once('../config.php'); error('TODO: rewrite db perf code'); // TODO: rewrite // disable moodle specific debug messages that would be breaking the frames disable_debugging(); $topframe = optional_param('topframe', 0, PARAM_BOOL); $bottomframe = optional_param('bottomframe', 0, PARAM_BOOL); $do = optional_param('do', '', PARAM_ALPHA); require_login(); require_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM)); $strdatabaseperformance = get_string("databaseperformance"); $stradministration = get_string("administration"); $site = get_site(); $navigation = build_navigation(array( array('name'=>$stradministration, 'link'=>'index.php', 'type'=>'misc'), array('name'=>$strdatabaseperformance, 'link'=>null, 'type'=>'misc'))); if (!empty($topframe)) { print_header("$site->shortname: $strdatabaseperformance", "$site->fullname", $navigation); exit; }
nicolasconnault/moodle2.0
admin/dbperformance.php
PHP
gpl-2.0
1,137
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ch.quantasy.iot.mqtt.tinkerforge.device.deviceHandler.IMU.status; import ch.quantasy.iot.mqtt.base.AHandler; import ch.quantasy.iot.mqtt.base.message.AStatus; import ch.quantasy.iot.mqtt.tinkerforge.device.deviceHandler.IMU.IMU; import org.eclipse.paho.client.mqttv3.MqttAsyncClient; /** * * @author Reto E. Koenig <[email protected]> */ public class AllDataPeriodStatus extends AStatus { public AllDataPeriodStatus(AHandler deviceHandler, String statusTopic, MqttAsyncClient mqttClient) { super(deviceHandler, statusTopic, "allData", mqttClient); super.addDescription(IMU.PERIOD, Long.class, "JSON", "0", "..", "" + Long.MAX_VALUE); } }
knr1/ch.bfh.mobicomp
ch.quantasy.iot.gateway.tinkerforge/src/main/java/ch/quantasy/iot/mqtt/tinkerforge/device/deviceHandler/IMU/status/AllDataPeriodStatus.java
Java
gpl-2.0
848
#ifndef MUX_CLOCK_H #define MUX_CLOCK_H /** * Initializes main system clock. * @ms time between each tick in milliseconds * @tick function to run every tick */ void clock_init(int ms, void (*tick)()); /** * Starts main system clock. */ void clock_start(); /** * Stops main system clock. */ void clock_stop(); #endif
jodersky/mux
kernel/include/mux/clock.h
C
gpl-2.0
327
package com.karniyarik.common.util; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import org.apache.commons.lang.StringUtils; import com.karniyarik.common.KarniyarikRepository; import com.karniyarik.common.config.system.DeploymentConfig; import com.karniyarik.common.config.system.WebConfig; public class IndexMergeUtil { public static final String SITE_NAME_PARAMETER = "s"; public static final void callMergeSiteIndex(String siteName) throws Throwable { callMergeSiteIndex(siteName, false); } public static final void callMergeSiteIndex(String siteName, boolean reduceBoost) throws Throwable { WebConfig webConfig = KarniyarikRepository.getInstance().getConfig().getConfigurationBundle().getWebConfig(); DeploymentConfig config = KarniyarikRepository.getInstance().getConfig().getConfigurationBundle().getDeploymentConfig(); //String url = "http://www.karniyarik.com"; String url = config.getMasterWebUrl(); URL servletURL = null; URLConnection connection = null; InputStream is = null; String tail = webConfig.getMergeIndexServlet() + "?" + SITE_NAME_PARAMETER + "=" + siteName; if (StringUtils.isNotBlank(url)) { if(!tail.startsWith("/") && !url.endsWith("/")) { url += "/"; } url += tail; if(reduceBoost) { url += "&rb=true"; } servletURL = new URL(url); connection = servletURL.openConnection(); connection.connect(); is = connection.getInputStream(); is.close(); } servletURL = null; connection = null; is = null; tail = null; } public static void callReduceSiteIndex(String siteName) throws Throwable{ callMergeSiteIndex(siteName, true); } public static void main(String[] args) throws Throwable{ String[] sites = new String[]{ "hataystore", "damakzevki", "robertopirlanta", "bebekken", "elektrikmalzemem", "starsexshop", "altinsarrafi", "budatoys", "taffybaby", "medikalcim", "beyazdepo", "tasarimbookshop", "boviza", "evdepo", "bonnyfood", "beyazkutu", "koctas", "bizimmarket", "narbebe", "gonayakkabi", "tgrtpazarlama", "pasabahce", "vatanbilgisayar", "egerate-store", "dr", "hipernex", "ensarshop", "yesil", "dealextreme", "petsrus", "otoyedekparcaburada", "elektrikdeposu", "alisveris", "radikalteknoloji", "ekopasaj", "strawberrynet", "yenisayfa", "adresimegelsin", "juenpetmarket", "nadirkitap"}; for(String site: sites) { System.out.println(site); callMergeSiteIndex(site); Thread.sleep(10000); } } }
Karniyarik/karniyarik
karniyarik-common/src/main/java/com/karniyarik/common/util/IndexMergeUtil.java
Java
gpl-2.0
2,586
# bulk-media-downloader
rogueralsha/bulk-media-downloader
README.md
Markdown
gpl-2.0
23
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading; using Newtonsoft.Json; namespace lit { class HttpTransferModule : ITransferModule { public const string ConnectionRequest = "subscribe"; public const string StatusRequest = "getstatus"; public const string StatusReport = "status"; private List<string> connections = new List<string>(); private IDictionary<string, string> myRecord; private readonly HttpListener myListener = new HttpListener(); public List<string> Prefixes { get; set; } public HttpTransferModule(IConfiguration configuration) { if (!HttpListener.IsSupported) { throw new NotSupportedException("Needs Windows XP SP2, Server 2003 or later."); } // URI prefixes are required, for example // "http://localhost:8080/index/". if (string.IsNullOrEmpty(configuration.Transfer.Prefix)) { throw new ArgumentException("Prefix"); } Console.WriteLine("using prefix {0}", configuration.Transfer.Prefix); myListener.Prefixes.Add(configuration.Transfer.Prefix); } public void Start() { myListener.Start(); ThreadPool.QueueUserWorkItem((o) => { Console.WriteLine("Webserver is running..."); try { while (myListener.IsListening) { ThreadPool.QueueUserWorkItem((c) => { var ctx = c as HttpListenerContext; try { var simpleResponse = Response(ctx.Request); var buf = Encoding.UTF8.GetBytes(simpleResponse.Content); ctx.Response.ContentLength64 = buf.Length; ctx.Response.OutputStream.Write(buf, 0, buf.Length); ctx.Response.StatusCode = (int)simpleResponse.StatusCode; } catch { } // suppress any exceptions finally { // always close the stream ctx.Response.OutputStream.Close(); } }, myListener.GetContext()); } } catch { } // suppress any exceptions }); } public void ReceiveChanges(IDictionary<string, string> record) { myRecord = record; Console.WriteLine(string.Join(", ", new List<string>() { "TimeStamp", "Build", "Assembly", "TC", "Status" }.Select(f => record.ContainsKey(f) ? record[f] : ""))); } public void Stop() { myListener.Stop(); myListener.Close(); } public void Dispose() { Stop(); } private HttpSimpleResponse Response(HttpListenerRequest httpRequest) { if (null == httpRequest) { return new HttpSimpleResponse(HttpStatusCode.BadRequest, "null"); } var request = httpRequest.Url.LocalPath.Trim('/'); var client = httpRequest.RemoteEndPoint.Address.ToString(); Console.WriteLine("http {0} request received from {1}: {2}", httpRequest.HttpMethod, client, request); switch (request) { case ConnectionRequest: if (connections.All(c => c != client)) { connections.Add(client); Console.WriteLine("connection request accepted from {0}", client); } return new HttpSimpleResponse(HttpStatusCode.OK, RecordAsJson); case StatusRequest: return new HttpSimpleResponse(HttpStatusCode.OK, RecordAsJson); default: return new HttpSimpleResponse(HttpStatusCode.BadRequest, "he?!"); } } private string RecordAsJson { get { return JsonConvert.SerializeObject(myRecord, typeof(Dictionary<string, string>), Formatting.None, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore, }); } } } }
klapantius/lit
lit/Transfer/HttpTransferModule.cs
C#
gpl-2.0
4,828
// This file is part of par2cmdline (a PAR 2.0 compatible file verification and // repair tool). See http://parchive.sourceforge.net for details of PAR 2.0. // // Copyright (c) 2003 Peter Brian Clements // // par2cmdline 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. // // par2cmdline 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 // // 11/1/05 gmilow - Modified #include "stdafx.h" #include "par2cmdline.h" #ifdef _MSC_VER #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif #endif // Construct the creator packet. // The only external information required to complete construction is // the set_id_hash (which is normally computed from information in the // main packet). bool CreatorPacket::Create(const MD5Hash &setid) { string creator = "Created by PACKAGE version VERSION ."; // Allocate a packet just large enough for creator name CREATORPACKET *packet = (CREATORPACKET *)AllocatePacket(sizeof(*packet) + (~3 & (3+(u32)creator.size()))); // Fill in the details the we know packet->header.magic = packet_magic; packet->header.length = packetlength; //packet->header.hash; // Compute shortly packet->header.setid = setid; packet->header.type = creatorpacket_type; // Copy the creator description into the packet memcpy(packet->client, creator.c_str(), creator.size()); // Compute the packet hash MD5Context packetcontext; packetcontext.Update(&packet->header.setid, packetlength - offsetof(PACKET_HEADER, setid)); packetcontext.Final(packet->header.hash); return true; } // Load the packet from disk. bool CreatorPacket::Load(DiskFile *diskfile, u64 offset, PACKET_HEADER &header) { // Is the packet long enough if (header.length <= sizeof(CREATORPACKET)) { return false; } // Is the packet too large (what is the longest reasonable creator description) if (header.length - sizeof(CREATORPACKET) > 100000) { return false; } // Allocate the packet (with a little extra so we will have NULLs after the description) CREATORPACKET *packet = (CREATORPACKET *)AllocatePacket((size_t)header.length, 4); packet->header = header; // Load the rest of the packet from disk return diskfile->Read(offset + sizeof(PACKET_HEADER), packet->client, (size_t)packet->header.length - sizeof(PACKET_HEADER)); }
milowg/Par-N-Rar
par2-cmdline/creatorpacket.cpp
C++
gpl-2.0
2,972
<!DOCTYPE html> <html itemscope itemtype="http://schema.org/website" xmlns:fb="http://www.facebook.com/2008/fbml" xmlns:og="http://opengraphprotocol.org/schema/" lang="en"> <head> <title>2010 Vanderbilt Commodores Statistics | College Football at Sports-Reference.com</title> <script type="text/javascript">var sr_gzipEnabled = false;</script> <script type="text/javascript" src="http://d2ft4b0ve1aur1.cloudfront.net/js-237/sr.gzipcheck.js.jgz"></script> <noscript> <link type="text/css" rel="stylesheet" href="http://d2ft4b0ve1aur1.cloudfront.net/css-237/sr-cfb-min.css"> </noscript> <script type="text/javascript"> (function () { var sr_css_file = 'http://d2ft4b0ve1aur1.cloudfront.net/css-237/sr-cfb-min.css'; if (sr_gzipEnabled) { sr_css_file = 'http://d2ft4b0ve1aur1.cloudfront.net/css-237/sr-cfb-min-gz.css'; } var head = document.getElementsByTagName("head")[0]; if (head) { var scriptStyles = document.createElement("link"); scriptStyles.rel = "stylesheet"; scriptStyles.type = "text/css"; scriptStyles.href = sr_css_file; head.appendChild(scriptStyles); //alert('adding css to header:'+sr_css_file); } }()); </script> <meta charset="utf-8"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="keywords" content="college, ncaa, football, stats, statistics, history, Vanderbilt Commodores, 2010, stats"> <meta property="fb:admins" content="34208645" /> <meta property="fb:page_id" content="185855008121268" /> <meta property="og:site_name" content="College Football at Sports-Football-Reference.com"> <meta property="og:image" content="http://d2ft4b0ve1aur1.cloudfront.net/images-237/SR-College-Football.png"> <meta itemprop="image" content="http://d2ft4b0ve1aur1.cloudfront.net/images-237/SR-College-Football.png"> <meta property="og:description" content="Statistics, Game Logs, Splits, and much more"> <meta property="og:title" content="2010 Vanderbilt Commodores"> <meta property="og:url" content="http://www.sports-reference.com/cfb/schools/vanderbilt/2010.html"> <meta property="og:type" content="team"> <link rel="canonical" href="http://www.sports-reference.com/cfb/schools/vanderbilt/2010.html"/> <meta itemprop="name" content="2010 Vanderbilt Commodores"> <meta itemprop="description" content="Statistics, Game Logs, Splits, and much more"> <div></div><!-- to prevent hangs on some browsers --> <link rel="icon" type="image/vnd.microsoft.icon" href="http://d2ft4b0ve1aur1.cloudfront.net/images-237/favicon-cfb.ico"> <link rel="shortcut icon" type="image/vnd.microsoft.icon" href="http://d2ft4b0ve1aur1.cloudfront.net/images-237/favicon-cfb.ico"> <link rel="search" type="application/opensearchdescription+xml" href="http://d2ft4b0ve1aur1.cloudfront.net/os-237/opensearch-cfb.xml" title="CFB-Ref Search"> <!--[if lte IE 6]> <style type="text/css"> .hovermenu,.hovermenu_ajax,.sub_index,#quick_index {display:none!important} </style> <![endif]--> </head> <body> <div id="page_container"> <div id="top_nav"> <div id="site_header"> <div id="sr_header"> <div class="float_right"> <a href="http://www.sports-reference.com">S-R</a>: <a href="http://www.baseball-reference.com">MLB</a> | <a href="http://www.basketball-reference.com/">NBA</a> &#183; <a href="http://www.sports-reference.com/cbb/">CBB</a> | <a href="http://www.pro-football-reference.com">NFL</a> &#183; <span class="bold_text">CFB</span> | <a href="http://www.hockey-reference.com">NHL</a> | <a href="http://www.sports-reference.com/olympics/">Oly</a> | <a href="http://www.sports-reference.com/blog/">Blog</a> </div> <div class="clear_both clearfix float_right margin_left padding_top_half"> <a class="sprite-twitter" title="Follow us on Twitter" href="http://twitter.com/sports_ref"></a>&nbsp;<a class="sprite-facebook" title="Become a Fan on Facebook" href="http://www.facebook.com/SR.CollegeFootball"></a> </div> <div class="float_right"> <form method="get" id="f" name="f" action="/cfb/search.cgi"> <input x-webkit-speech type="search" placeholder="" id="search" name="search" class="search long"> <input type="submit" value="Search" class="submit"> </form> </div> </div> <div class="float_left padding_bottom_half"> <a href="/cfb/"><img src="http://d2ft4b0ve1aur1.cloudfront.net/images-237/SR-College-Football.png" width="464" height="49" class="border0" alt="College Football Statistics & History | College Football at Sports-Reference.com"></a> </div> </div> <div id="quick_index_container"> <div id="quick_index"> <ul class="hovermenu_ajax navbar"> <li class=""><a href="/cfb/play-index/">play index</a><ul class="li_margin" id="header_playindex"></ul></li> <li class=""><a href="/cfb/boxscores/">box scores</a><ul class="li_margin" id="header_boxscores"></ul></li> <li class=""><a href="/cfb/players/">players</a><ul class="li_margin" id="header_players"></ul></li> <li class="active"><a href="/cfb/schools/">schools</a><ul class="li_margin" id="header_schools"></ul></li> <li class=""><a href="/cfb/years/">seasons</a><ul class="li_margin" id="header_years"></ul></li> <li class=""><a href="/cfb/conferences/">conferences</a><ul class="li_margin" id="header_conferences"></ul></li> <li class=""><a href="/cfb/coaches/">coaches</a><ul class="li_margin" id="header_coaches"></ul></li> <li class=""><a href="/cfb/leaders/">leaders</a><ul class="li_margin" id="header_leaders"></ul></li> <li class=""><a href="/cfb/awards/">awards</a><ul class="li_margin" id="header_awards"></ul></li> <li class=""><a href="/cfb/bowls/">bowls</a><ul class="li_margin" id="header_bowls"></ul></li> <li class=""><a href="">more [+]</a> <ul class="li_margin" id="header_more_links"> <li> <a class="bold_text" href="/cfb/about/">About</a>: <a href="/cfb/about/what-is-major.html">What is Major?</a>, <a href="/cfb/about/glossary.html#srs">Simple Rating System</a>, <a href="/cfb/about/glossary.html">Glossary</a>, <a href="/cfb/about/sources.html">Sources</a>, <a href="/cfb/about/contact.html">Contacts</a>, <a href="/cfb/about/philosophy.html">Philosophy</a> </li> <li><a class="bold_text" href="http://www.sports-reference.com/blog/category/cfb-at-sports-reference/">Blog</a>: News and notes about CFB at Sports-Reference.com</li> <li> <a class="bold_text" href="/cfb/friv/">Frivolities</a>: <a href="/cfb/friv/elo.cgi">Elo School Rater</a> </li> </ul> </li> </ul> </div> </div> <div id="you_are_here"> <p><strong>You Are Here</strong>&nbsp;&gt;&nbsp;<a href="/cfb/">SR/CFB</a>&nbsp;&gt;&nbsp;<a href="/cfb/schools/">Schools</a>&nbsp;&gt;&nbsp;<a href="/cfb/schools/vanderbilt/">Vanderbilt Commodores</a>&nbsp;&gt;&nbsp;<strong>2010</strong></p> </div> <style> .site_news { color:#fff!important; background-color:#747678; border-top:1px solid #000; border-bottom: 1px solid #000; clear:both; font-size:.875em; width:100%; } .site_news p { margin:0; padding:.35em .7em; } .site_news a { color:#fff; } </style> <div class="site_news"><p><span class="bold_text">News:</span> <span class="poptip" tip="Just a friendly reminder to check out our Olympics site, which is being updated daily throughout the London games.">s-r blog:<a onClick="try { pageTracker._trackEvent('blog','click','area-yah'); } catch (err) {};" href="http://www.sports-reference.com/blog/2012/07/olympics-at-sports-reference/">Olympics at Sports-Reference</a> <span class="small_text"></span></span></p></div> </div> <div id="info_box"> <div class="advert300x250"> <script type="text/deferscript"> var _ad_d = Math.floor(Math.random()*9999999999+1); document.write('<scr' + 'ipt src=http://ad.doubleclick.net/adj/collegefootballreference.fsv/ros;sect=ros;fantasy=no;game=no;tile=3;sz=300x250;ord=' + _ad_d + '?></scr' + 'ipt>'); </script> <noscript> <a href="http://ad.doubleclick.net/jump/collegefootballreference.fsv/ros;sect=ros;fantasy=no;game=no;tile=3;sz=300x250;ord=?" ><img alt="" SRC="http://ad.doubleclick.net/ad/collegefootballreference.fsv/ros;sect=ros;fantasy=no;game=no;tile=3;sz=300x250;ord=?" border="0" width="300" height="250" ></a> </noscript> </div> <h1>2010 Vanderbilt Commodores Statistics</h1> <div class="social_media"> <div class="float_left"><span id="fb-root"></span><fb:like width="200" show_faces="0" height="35" ref="team_like"></fb:like></div> <div class="float_left"><div class="g-plusone" data-size="medium" data-annotation="inline" data-width="150"></div></div> </div> <p><a href="/cfb/schools/vanderbilt/">School Index:</a>&nbsp;<a href="/cfb/schools/vanderbilt/2009.html">Previous Year</a>&nbsp;&#9642;&nbsp;<a href="/cfb/schools/vanderbilt/2011.html">Next Year</a></p> <form class="sr_standard inline" name="pages" action=""> <strong>Navigation:</strong> <select name="cfb_pages" onchange="sr_goto_page('cfb_pages','',this.form);"> <option value="" disabled >Select Page <option value="/cfb/schools/vanderbilt/2010.html" selected>Statistics <option value="/cfb/schools/vanderbilt/2010-schedule.html">Schedule and Results <option value="/cfb/schools/vanderbilt/2010-roster.html">Roster <option value="/cfb/schools/vanderbilt/2010/gamelog/">Game Log <option value="/cfb/schools/vanderbilt/2010/splits/">Splits </select> </form> <p class="margin_top"><strong>Conference:</strong> <a href="/cfb/conferences/sec/2010.html">SEC</a> (East Division) <br><strong>Record:</strong> 2-10, .167 W-L% (109th of 120) (<a href="/cfb/schools/vanderbilt/2010-schedule.html">Schedule and Results</a>) <br><strong>Coach:</strong> <a href="/cfb/coaches/robbie-caldwell-1.html">Robbie Caldwell</a> (2-10) <p><strong>PTS/G:</strong> 16.9 (112th of 120)&nbsp;&#9642;&nbsp;<strong>Opp PTS/G:</strong> 31.2 (94th of 120) <br><strong><a href="/cfb/about/glossary.html#srs" onmouseover="Tip('Simple Rating System; a rating that takes into account average point differential and strength of schedule. The rating is denominated in points above/below average, where zero is average.')">SRS</a>:</strong> -9.59 (99th of 120)&nbsp;&#9642;&nbsp;<strong><a href="/cfb/about/glossary.html#sos" onmouseover="Tip('Strength of Schedule; a rating of strength of schedule. The rating is denominated in points above/below average, where zero is average.')">SOS</a>:</strong> 4.09 (30th of 120) </div> <div class="advert728x90"> <script type="text/deferscript"> var _ad_c = Math.floor(Math.random()*9999999999+1); document.write('<scr' + 'ipt src=http://ad.doubleclick.net/adj/collegefootballreference.fsv/ros;sect=ros;fantasy=no;game=no;tile=1;dcopt=ist;sz=728x90;ord=' + _ad_c + '?></scr' + 'ipt>'); </script> <noscript> <a href="http://ad.doubleclick.net/jump/collegefootballreference.fsv/ros;sect=ros;fantasy=no;game=no;tile=1;sz=728x90;ord='+_ad_c+'?" ><img src="http://ad.doubleclick.net/ad/collegefootballreference.fsv/ros;sect=ros;fantasy=no;game=no;tile=1;sz=728x90;ord='+_ad_c+'?" border="0" height="90" width="728"></a> </noscript> </div><div class="clear_both margin0 padding0"></div> <div id="page_content"> <div class="table_heading"> <h2 style="">Team Statistics</h2> <div class="table_heading_text">Most values are per game averages</div> </div> <div class="table_container" id="div_team"> <table class=" show_controls stats_table" id="team"> <colgroup><col><col><col><col><col><col><col><col><col><col><col><col><col><col><col><col><col><col><col><col><col><col><col></colgroup> <thead> <tr class=" over_header"> <th></th> <th></th> <th align="center" colspan=5 class="bold_text over_header" >Passing</th> <th align="center" colspan=4 class="bold_text over_header" >Rushing</th> <th align="center" colspan=3 class="bold_text over_header" >Total Offense</th> <th align="center" colspan=4 class="bold_text over_header" >First Downs</th> <th align="center" colspan=2 class="bold_text over_header" >Penalties</th> <th align="center" colspan=3 class="bold_text over_header" >Turnovers</th> </tr> <tr class=""> <th align="left" class=" sort_default_asc" >Split</th> <th align="right" class="" tip="Games">G</th> <th align="right" class="" tip="Pass Completions">Cmp</th> <th align="right" class="" tip="Pass Attempts">Att</th> <th align="right" class="" tip="Pass Completion Percentage">Pct</th> <th align="right" class="" tip="Passing Yards">Yds</th> <th align="right" class="" tip="Passing Touchdowns">TD</th> <th align="right" class="" tip="Rush Attempts">Att</th> <th align="right" class="" tip="Rushing Yards">Yds</th> <th align="right" class="" tip="Rushing Yards Per Attempt">Avg</th> <th align="right" class="" tip="Rushing Touchdowns">TD</th> <th align="right" class="" tip="Plays (Pass Attempts plus Rush Attempts)">Plays</th> <th align="right" class="" tip="Total Yards (Passing Yards plus Rushing Yards)">Yds</th> <th align="right" class="" tip="Total Yards Per Play">Avg</th> <th align="right" class="" tip="First Downs by Pass">Pass</th> <th align="right" class="" tip="First Downs by Rush">Rush</th> <th align="right" class="" tip="First Downs by Penalty">Pen</th> <th align="right" class="" tip="First Downs">Tot</th> <th align="right" class="" tip="Penalties">No.</th> <th align="right" class="" tip="Penalty Yards">Yds</th> <th align="right" class="" tip="Fumbles Lost">Fum</th> <th align="right" class="" tip="Passing Interceptions">Int</th> <th align="right" class="" tip="Turnovers">Tot</th> </tr> </thead> <tbody> <tr class=""> <td align="left" >Offense</td> <td align="right" >12</td> <td align="right" >14.1</td> <td align="right" >30.0</td> <td align="right" >46.9</td> <td align="right" >159.4</td> <td align="right" >0.9</td> <td align="right" >35.1</td> <td align="right" >138.8</td> <td align="right" >4.0</td> <td align="right" >1.1</td> <td align="right" >65.1</td> <td align="right" >298.3</td> <td align="right" >4.6</td> <td align="right" >6.8</td> <td align="right" >7.3</td> <td align="right" >0.9</td> <td align="right" >15.0</td> <td align="right" >5.6</td> <td align="right" >44.7</td> <td align="right" >0.7</td> <td align="right" >0.9</td> <td align="right" >1.6</td> </tr> <tr class=""> <td align="left" >Defense</td> <td align="right" >12</td> <td align="right" >18.4</td> <td align="right" >29.1</td> <td align="right" >63.3</td> <td align="right" >226.3</td> <td align="right" >1.5</td> <td align="right" >43.3</td> <td align="right" >193.0</td> <td align="right" >4.5</td> <td align="right" >2.1</td> <td align="right" >72.3</td> <td align="right" >419.3</td> <td align="right" >5.8</td> <td align="right" >9.0</td> <td align="right" >10.1</td> <td align="right" >0.8</td> <td align="right" >19.9</td> <td align="right" >6.0</td> <td align="right" >50.6</td> <td align="right" >0.5</td> <td align="right" >0.8</td> <td align="right" >1.3</td> </tr> <tr class=""> <td align="left" >Difference</td> <td align="right" ></td> <td align="right" >-4.3</td> <td align="right" >+0.9</td> <td align="right" >-16.4</td> <td align="right" >-66.9</td> <td align="right" >-0.6</td> <td align="right" >-8.2</td> <td align="right" >-54.2</td> <td align="right" >-0.5</td> <td align="right" >-1.0</td> <td align="right" >-7.2</td> <td align="right" >-121.0</td> <td align="right" >-1.2</td> <td align="right" >-2.2</td> <td align="right" >-2.8</td> <td align="right" >+0.1</td> <td align="right" >-4.9</td> <td align="right" >-0.4</td> <td align="right" >-5.9</td> <td align="right" >+0.2</td> <td align="right" >+0.1</td> <td align="right" >+0.3</td> </tr> </tbody> </table> </div> <div class="table_heading"> <h2 style="">Passing</h2> <div class="table_heading_text"></div> </div> <div class="table_container" id="div_passing"> <table class="sortable stats_table" id="passing"> <colgroup><col><col><col><col><col><col><col><col><col><col><col></colgroup> <thead> <tr class=" over_header"> <th align="CENTER" colspan=2 class="tooltip over_header" ></th> <th align="center" colspan=9 class="bold_text over_header" >Passing</th> </tr> <tr class=""> <th align="right" class="ranker sort_default_asc" tip="Rank">Rk</th> <th align="left" class="tooltip sort_default_asc" >Player</th> <th align="right" class="tooltip" tip="Pass Completions">Cmp</th> <th align="right" class="tooltip" tip="Pass Attempts">Att</th> <th align="right" class="tooltip" tip="Pass Completion Percentage">Pct</th> <th align="right" class="tooltip" tip="Passing Yards">Yds</th> <th align="right" class="tooltip" tip="Passing Yards Per Attempt">Y/A</th> <th align="right" class="tooltip" tip="Adjusted Passing Yards Per Attempt; the formula is (Yds + 20 * TD - 45 * Int) / Att">AY/A</th> <th align="right" class="tooltip" tip="Passing Touchdowns">TD</th> <th align="right" class="tooltip" tip="Passing Interceptions">Int</th> <th align="right" class="tooltip" tip="Passing Efficiency Rating; the formula is (8.4 * Yds + 330 * TD - 200 * Int + 100 * Cmp) / Att">Rate</th> </tr> </thead> <tbody> <tr class=""> <td align="right" csk="1">1</td> <td align="left" csk="Smith,Larry"><a href="/cfb/players/larry-smith-1.html">Larry Smith</a></td> <td align="right" >117</td> <td align="right" >247</td> <td align="right" >47.4</td> <td align="right" >1262</td> <td align="right" >5.1</td> <td align="right" >4.7</td> <td align="right" >6</td> <td align="right" >5</td> <td align="right" >94.3</td> </tr> <tr class=""> <td align="right" csk="2">2</td> <td align="left" csk="Funk,Jared"><a href="/cfb/players/jared-funk-1.html">Jared Funk</a></td> <td align="right" >52</td> <td align="right" >109</td> <td align="right" >47.7</td> <td align="right" >651</td> <td align="right" >6.0</td> <td align="right" >4.4</td> <td align="right" >5</td> <td align="right" >6</td> <td align="right" >102.0</td> </tr> <tr class=""> <td align="right" csk="3">3</td> <td align="left" csk="Barden,Brandon"><a href="/cfb/players/brandon-barden-1.html">Brandon Barden</a></td> <td align="right" >0</td> <td align="right" >1</td> <td align="right" >0.0</td> <td align="right" >0</td> <td align="right" >0.0</td> <td align="right" >0.0</td> <td align="right" >0</td> <td align="right" >0</td> <td align="right" >0.0</td> </tr> <tr class=""> <td align="right" csk="4">4</td> <td align="left" csk="Cole,John"><a href="/cfb/players/john-cole-1.html">John Cole</a></td> <td align="right" >0</td> <td align="right" >1</td> <td align="right" >0.0</td> <td align="right" >0</td> <td align="right" >0.0</td> <td align="right" >0.0</td> <td align="right" >0</td> <td align="right" >0</td> <td align="right" >0.0</td> </tr> <tr class=""> <td align="right" csk="5">5</td> <td align="left" csk="Fowler,Ryan"><a href="/cfb/players/ryan-fowler-2.html">Ryan Fowler</a></td> <td align="right" >0</td> <td align="right" >1</td> <td align="right" >0.0</td> <td align="right" >0</td> <td align="right" >0.0</td> <td align="right" >0.0</td> <td align="right" >0</td> <td align="right" >0</td> <td align="right" >0.0</td> </tr> <tr class=""> <td align="right" csk="6">6</td> <td align="left" csk="Wimberly,Turner"><a href="/cfb/players/turner-wimberly-1.html">Turner Wimberly</a></td> <td align="right" >0</td> <td align="right" >1</td> <td align="right" >0.0</td> <td align="right" >0</td> <td align="right" >0.0</td> <td align="right" >0.0</td> <td align="right" >0</td> <td align="right" >0</td> <td align="right" >0.0</td> </tr> </tbody> </table> </div> <div class="table_heading"> <h2 style="">Rushing &amp; Receiving</h2> <div class="table_heading_text"></div> </div> <div class="table_container" id="div_rushing_and_receiving"> <table class="sortable stats_table" id="rushing_and_receiving"> <colgroup><col><col><col><col><col><col><col><col><col><col><col><col><col><col></colgroup> <thead> <tr class=" over_header"> <th align="CENTER" colspan=2 class="tooltip over_header" ></th> <th align="center" colspan=4 class="bold_text over_header" >Rushing</th> <th align="center" colspan=4 class="bold_text over_header" >Receiving</th> <th align="center" colspan=4 class="bold_text over_header" >Scrimmage</th> </tr> <tr class=""> <th align="right" class="ranker sort_default_asc" tip="Rank">Rk</th> <th align="left" class="tooltip sort_default_asc" >Player</th> <th align="right" class="tooltip" tip="Rush Attempts">Att</th> <th align="right" class="tooltip" tip="Rushing Yards">Yds</th> <th align="right" class="tooltip" tip="Rushing Yards Per Attempt">Avg</th> <th align="right" class="tooltip" tip="Rushing Touchdowns">TD</th> <th align="right" class="tooltip" tip="Receptions">Rec</th> <th align="right" class="tooltip" tip="Receiving Yards">Yds</th> <th align="right" class="tooltip" tip="Receiving Yards Per Reception">Avg</th> <th align="right" class="tooltip" tip="Receiving Touchdowns">TD</th> <th align="right" class="tooltip" tip="Plays From Scrimmage (Rush Attempts plus Receptions)">Plays</th> <th align="right" class="tooltip" tip="Yards From Scrimmage (Rushing Yards plus Receiving Yards)">Yds</th> <th align="right" class="tooltip" tip="Yards From Scrimmage Per Play">Avg</th> <th align="right" class="tooltip" tip="Touchdowns From Scrimmage (Rushing Touchdowns plus Receiving Touchdowns)">TD</th> </tr> </thead> <tbody> <tr class=""> <td align="right" csk="1">1</td> <td align="left" csk="Smith,Larry"><a href="/cfb/players/larry-smith-1.html">Larry Smith</a></td> <td align="right" >105</td> <td align="right" >248</td> <td align="right" >2.4</td> <td align="right" >4</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >105</td> <td align="right" >248</td> <td align="right" >2.4</td> <td align="right" >4</td> </tr> <tr class=""> <td align="right" csk="2">2</td> <td align="left" csk="Norman,Warren"><a href="/cfb/players/warren-norman-1.html">Warren Norman</a></td> <td align="right" >77</td> <td align="right" >459</td> <td align="right" >6.0</td> <td align="right" >4</td> <td align="right" >11</td> <td align="right" >110</td> <td align="right" >10.0</td> <td align="right" >0</td> <td align="right" >88</td> <td align="right" >569</td> <td align="right" >6.5</td> <td align="right" >4</td> </tr> <tr class=""> <td align="right" csk="3">3</td> <td align="left" csk="Reeves,Kennard"><a href="/cfb/players/kennard-reeves-1.html">Kennard Reeves</a></td> <td align="right" >76</td> <td align="right" >306</td> <td align="right" >4.0</td> <td align="right" >0</td> <td align="right" >4</td> <td align="right" >35</td> <td align="right" >8.8</td> <td align="right" >0</td> <td align="right" >80</td> <td align="right" >341</td> <td align="right" >4.3</td> <td align="right" >0</td> </tr> <tr class=""> <td align="right" csk="4">4</td> <td align="left" csk="Stacy,Zac"><a href="/cfb/players/zac-stacy-1.html">Zac Stacy</a></td> <td align="right" >66</td> <td align="right" >331</td> <td align="right" >5.0</td> <td align="right" >3</td> <td align="right" >9</td> <td align="right" >32</td> <td align="right" >3.6</td> <td align="right" >0</td> <td align="right" >75</td> <td align="right" >363</td> <td align="right" >4.8</td> <td align="right" >3</td> </tr> <tr class=""> <td align="right" csk="5">5</td> <td align="left" csk="Tate,Wesley"><a href="/cfb/players/wesley-tate-1.html">Wesley Tate</a></td> <td align="right" >40</td> <td align="right" >140</td> <td align="right" >3.5</td> <td align="right" >0</td> <td align="right" >5</td> <td align="right" >25</td> <td align="right" >5.0</td> <td align="right" >0</td> <td align="right" >45</td> <td align="right" >165</td> <td align="right" >3.7</td> <td align="right" >0</td> </tr> <tr class=""> <td align="right" csk="6">6</td> <td align="left" csk="Funk,Jared"><a href="/cfb/players/jared-funk-1.html">Jared Funk</a></td> <td align="right" >24</td> <td align="right" >67</td> <td align="right" >2.8</td> <td align="right" >0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >24</td> <td align="right" >67</td> <td align="right" >2.8</td> <td align="right" >0</td> </tr> <tr class=""> <td align="right" csk="7">7</td> <td align="left" csk="Samuels,Eric"><a href="/cfb/players/eric-samuels-1.html">Eric Samuels</a></td> <td align="right" >10</td> <td align="right" >43</td> <td align="right" >4.3</td> <td align="right" >0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >10</td> <td align="right" >43</td> <td align="right" >4.3</td> <td align="right" >0</td> </tr> <tr class=""> <td align="right" csk="8">8</td> <td align="left" csk="Krause,Jonathan"><a href="/cfb/players/jonathan-krause-1.html">Jonathan Krause</a></td> <td align="right" >6</td> <td align="right" >121</td> <td align="right" >20.2</td> <td align="right" >2</td> <td align="right" >24</td> <td align="right" >243</td> <td align="right" >10.1</td> <td align="right" >0</td> <td align="right" >30</td> <td align="right" >364</td> <td align="right" >12.1</td> <td align="right" >2</td> </tr> <tr class=""> <td align="right" csk="9">9</td> <td align="left" csk="Jelesky,Josh"><a href="/cfb/players/josh-jelesky-1.html">Josh Jelesky</a></td> <td align="right" >1</td> <td align="right" >4</td> <td align="right" >4.0</td> <td align="right" >0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >1</td> <td align="right" >4</td> <td align="right" >4.0</td> <td align="right" >0</td> </tr> <tr class=""> <td align="right" csk="10">10</td> <td align="left" csk="Kent,Richard"><a href="/cfb/players/richard-kent-1.html">Richard Kent</a></td> <td align="right" >1</td> <td align="right" >0</td> <td align="right" >0.0</td> <td align="right" >0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >1</td> <td align="right" >0</td> <td align="right" >0.0</td> <td align="right" >0</td> </tr> <tr class=""> <td align="right" csk="11">11</td> <td align="left" csk="Cole,John"><a href="/cfb/players/john-cole-1.html">John Cole</a></td> <td align="right" >1</td> <td align="right" >-1</td> <td align="right" >-1.0</td> <td align="right" >0</td> <td align="right" >25</td> <td align="right" >317</td> <td align="right" >12.7</td> <td align="right" >1</td> <td align="right" >26</td> <td align="right" >316</td> <td align="right" >12.2</td> <td align="right" >1</td> </tr> <tr class=""> <td align="right" csk="12">12</td> <td align="left" csk="Barden,Brandon"><a href="/cfb/players/brandon-barden-1.html">Brandon Barden</a></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >34</td> <td align="right" >425</td> <td align="right" >12.5</td> <td align="right" >3</td> <td align="right" >34</td> <td align="right" >425</td> <td align="right" >12.5</td> <td align="right" >3</td> </tr> <tr class=""> <td align="right" csk="13">13</td> <td align="left" csk="Matthews,Jordan"><a href="/cfb/players/jordan-matthews-1.html">Jordan Matthews</a></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >15</td> <td align="right" >181</td> <td align="right" >12.1</td> <td align="right" >4</td> <td align="right" >15</td> <td align="right" >181</td> <td align="right" >12.1</td> <td align="right" >4</td> </tr> <tr class=""> <td align="right" csk="14">14</td> <td align="left" csk="Herndon,Tray"><a href="/cfb/players/tray-herndon-1.html">Tray Herndon</a></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >13</td> <td align="right" >122</td> <td align="right" >9.4</td> <td align="right" >0</td> <td align="right" >13</td> <td align="right" >122</td> <td align="right" >9.4</td> <td align="right" >0</td> </tr> <tr class=""> <td align="right" csk="15">15</td> <td align="left" csk="Umoh,Udom"><a href="/cfb/players/udom-umoh-1.html">Udom Umoh</a></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >12</td> <td align="right" >194</td> <td align="right" >16.2</td> <td align="right" >2</td> <td align="right" >12</td> <td align="right" >194</td> <td align="right" >16.2</td> <td align="right" >2</td> </tr> <tr class=""> <td align="right" csk="16">16</td> <td align="left" csk="Wimberly,Turner"><a href="/cfb/players/turner-wimberly-1.html">Turner Wimberly</a></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >10</td> <td align="right" >170</td> <td align="right" >17.0</td> <td align="right" >0</td> <td align="right" >10</td> <td align="right" >170</td> <td align="right" >17.0</td> <td align="right" >0</td> </tr> <tr class=""> <td align="right" csk="17">17</td> <td align="left" csk="Johnston,Mason"><a href="/cfb/players/mason-johnston-1.html">Mason Johnston</a></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >6</td> <td align="right" >56</td> <td align="right" >9.3</td> <td align="right" >1</td> <td align="right" >6</td> <td align="right" >56</td> <td align="right" >9.3</td> <td align="right" >1</td> </tr> <tr class=""> <td align="right" csk="18">18</td> <td align="left" csk="Lassing,Fitz"><a href="/cfb/players/fitz-lassing-1.html">Fitz Lassing</a></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >1</td> <td align="right" >3</td> <td align="right" >3.0</td> <td align="right" >0</td> <td align="right" >1</td> <td align="right" >3</td> <td align="right" >3.0</td> <td align="right" >0</td> </tr> </tbody> </table> </div> <div class="table_heading"> <h2 style="">Defense &amp; Fumbles</h2> <div class="table_heading_text"></div> </div> <div class="table_container" id="div_defense_and_fumbles"> <table class="sortable stats_table" id="defense_and_fumbles"> <colgroup><col><col><col><col><col><col><col><col><col><col><col><col><col><col><col><col></colgroup> <thead> <tr class=" over_header"> <th align="CENTER" colspan=2 class="tooltip over_header" ></th> <th align="center" colspan=5 class="bold_text over_header" >Tackles</th> <th align="center" colspan=5 class="bold_text over_header" >Def Int</th> <th align="center" colspan=4 class="bold_text over_header" >Fumbles</th> </tr> <tr class=""> <th align="right" class="ranker sort_default_asc" tip="Rank">Rk</th> <th align="left" class="tooltip sort_default_asc" >Player</th> <th align="right" class="tooltip" tip="Solo Tackles">Solo</th> <th align="right" class="tooltip" tip="Assisted Tackles">Ast</th> <th align="right" class="tooltip" tip="Total Tackles">Tot</th> <th align="right" class="tooltip" tip="Tackles for Loss">Loss</th> <th align="right" class="tooltip" tip="Sacks">Sk</th> <th align="right" class="tooltip" tip="Interceptions">Int</th> <th align="right" class="tooltip" tip="Interception Return Yards">Yds</th> <th align="right" class="tooltip" tip="Interception Return Yards Per Interception">Avg</th> <th align="right" class="tooltip" tip="Interception Return Touchdowns">TD</th> <th align="right" class="tooltip" tip="Passes Defended">PD</th> <th align="right" class="tooltip" tip="Fumbles Recovered">FR</th> <th align="right" class="tooltip" tip="Fumble Recovery Return Yards">Yds</th> <th align="right" class="tooltip" tip="Fumble Recovery Return Touchdowns">TD</th> <th align="right" class="tooltip" tip="Fumbles Forced">FF</th> </tr> </thead> <tbody> <tr class=""> <td align="right" csk="1">1</td> <td align="left" csk="Richardson,Sean"><a href="/cfb/players/sean-richardson-1.html">Sean Richardson</a></td> <td align="right" >62</td> <td align="right" >37</td> <td align="right" >99</td> <td align="right" >7.0</td> <td align="right" >1.5</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >5</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="2">2</td> <td align="left" csk="Marve,Chris"><a href="/cfb/players/chris-marve-1.html">Chris Marve</a></td> <td align="right" >45</td> <td align="right" >35</td> <td align="right" >80</td> <td align="right" >8.0</td> <td align="right" >2.5</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >2</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="3">3</td> <td align="left" csk="Stokes,John"><a href="/cfb/players/john-stokes-2.html">John Stokes</a></td> <td align="right" >44</td> <td align="right" >34</td> <td align="right" >78</td> <td align="right" >6.5</td> <td align="right" >0.5</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >3</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >1</td> </tr> <tr class=""> <td align="right" csk="4">4</td> <td align="left" csk="Hayward,Casey"><a href="/cfb/players/casey-hayward-1.html">Casey Hayward</a></td> <td align="right" >56</td> <td align="right" >14</td> <td align="right" >70</td> <td align="right" >2.0</td> <td align="right" >0.0</td> <td align="right" >6</td> <td align="right" >13</td> <td align="right" >2.2</td> <td align="right" >0</td> <td align="right" >17</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >1</td> </tr> <tr class=""> <td align="right" csk="5">5</td> <td align="left" csk="Ladler,Kenny"><a href="/cfb/players/kenny-ladler-1.html">Kenny Ladler</a></td> <td align="right" >40</td> <td align="right" >17</td> <td align="right" >57</td> <td align="right" >5.5</td> <td align="right" >0.0</td> <td align="right" >1</td> <td align="right" >0</td> <td align="right" >0.0</td> <td align="right" >0</td> <td align="right" >3</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >1</td> </tr> <tr class=""> <td align="right" csk="6">6</td> <td align="left" csk="Foster,Eddie"><a href="/cfb/players/eddie-foster-1.html">Eddie Foster</a></td> <td align="right" >36</td> <td align="right" >17</td> <td align="right" >53</td> <td align="right" >6.0</td> <td align="right" >0.0</td> <td align="right" >1</td> <td align="right" >21</td> <td align="right" >21.0</td> <td align="right" >1</td> <td align="right" >4</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >1</td> </tr> <tr class=""> <td align="right" csk="7">7</td> <td align="left" csk="Lohr,Rob"><a href="/cfb/players/rob-lohr-1.html">Rob Lohr</a></td> <td align="right" >24</td> <td align="right" >11</td> <td align="right" >35</td> <td align="right" >7.5</td> <td align="right" >3.5</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="8">8</td> <td align="left" csk="Nichter,Colt"><a href="/cfb/players/colt-nichter-1.html">Colt Nichter</a></td> <td align="right" >16</td> <td align="right" >16</td> <td align="right" >32</td> <td align="right" >5.5</td> <td align="right" >3.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="9">9</td> <td align="left" csk="Fullam,Jay"><a href="/cfb/players/jay-fullam-1.html">Jay Fullam</a></td> <td align="right" >19</td> <td align="right" >11</td> <td align="right" >30</td> <td align="right" >1.5</td> <td align="right" >0.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >2</td> </tr> <tr class=""> <td align="right" csk="10">10</td> <td align="left" csk="May,Walker"><a href="/cfb/players/walker-may-1.html">Walker May</a></td> <td align="right" >16</td> <td align="right" >13</td> <td align="right" >29</td> <td align="right" >6.0</td> <td align="right" >1.5</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="11">11</td> <td align="left" csk="Greenstone,T.J."><a href="/cfb/players/tj-greenstone-1.html">T.J. Greenstone</a></td> <td align="right" >13</td> <td align="right" >15</td> <td align="right" >28</td> <td align="right" >4.5</td> <td align="right" >1.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="12">12</td> <td align="left" csk="Campbell,Nate"><a href="/cfb/players/nate-campbell-1.html">Nate Campbell</a></td> <td align="right" >21</td> <td align="right" >6</td> <td align="right" >27</td> <td align="right" >4.5</td> <td align="right" >0.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >1</td> </tr> <tr class=""> <td align="right" csk="13">13</td> <td align="left" csk="Samuels,Eric"><a href="/cfb/players/eric-samuels-1.html">Eric Samuels</a></td> <td align="right" >14</td> <td align="right" >13</td> <td align="right" >27</td> <td align="right" >1.5</td> <td align="right" >0.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >3</td> <td align="right" ></td> <td align="right" >2</td> <td align="right" ></td> <td align="right" >1</td> </tr> <tr class=""> <td align="right" csk="14">14</td> <td align="left" csk="Kadri,Theron"><a href="/cfb/players/theron-kadri-1.html">Theron Kadri</a></td> <td align="right" >13</td> <td align="right" >14</td> <td align="right" >27</td> <td align="right" >2.0</td> <td align="right" >0.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="15">15</td> <td align="left" csk="Fugger,Tim"><a href="/cfb/players/tim-fugger-1.html">Tim Fugger</a></td> <td align="right" >13</td> <td align="right" >9</td> <td align="right" >22</td> <td align="right" >5.0</td> <td align="right" >3.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >1</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >4</td> </tr> <tr class=""> <td align="right" csk="16">16</td> <td align="left" csk="Thomas,Johnell"><a href="/cfb/players/johnell-thomas-1.html">Johnell Thomas</a></td> <td align="right" >11</td> <td align="right" >11</td> <td align="right" >22</td> <td align="right" >3.5</td> <td align="right" >1.5</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >1</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="17">17</td> <td align="left" csk="Clarke,Steven"><a href="/cfb/players/steven-clarke-1.html">Steven Clarke</a></td> <td align="right" >10</td> <td align="right" >6</td> <td align="right" >16</td> <td align="right" >1.0</td> <td align="right" >1.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="18">18</td> <td align="left" csk="Hal,Andre"><a href="/cfb/players/andre-hal-1.html">Andre Hal</a></td> <td align="right" >10</td> <td align="right" >5</td> <td align="right" >15</td> <td align="right" >0.0</td> <td align="right" >0.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >1</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="19">19</td> <td align="left" csk="Jelesky,Josh"><a href="/cfb/players/josh-jelesky-1.html">Josh Jelesky</a></td> <td align="right" >5</td> <td align="right" >10</td> <td align="right" >15</td> <td align="right" >2.0</td> <td align="right" >0.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="20">20</td> <td align="left" csk="Jones,Deandre"><a href="/cfb/players/deandre-jones-1.html">Deandre Jones</a></td> <td align="right" >9</td> <td align="right" >4</td> <td align="right" >13</td> <td align="right" >2.5</td> <td align="right" >0.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="21">21</td> <td align="left" csk="Barnes,Archibald"><a href="/cfb/players/archibald-barnes-1.html">Archibald Barnes</a></td> <td align="right" >7</td> <td align="right" >4</td> <td align="right" >11</td> <td align="right" >1.0</td> <td align="right" >0.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >1</td> </tr> <tr class=""> <td align="right" csk="22">22</td> <td align="left" csk="Wilson,Trey"><a href="/cfb/players/trey-wilson-1.html">Trey Wilson</a></td> <td align="right" >8</td> <td align="right" >3</td> <td align="right" >11</td> <td align="right" >0.0</td> <td align="right" >0.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="23">23</td> <td align="left" csk="Brannon,Teriall"><a href="/cfb/players/teriall-brannon-1.html">Teriall Brannon</a></td> <td align="right" >5</td> <td align="right" >4</td> <td align="right" >9</td> <td align="right" >2.5</td> <td align="right" >1.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="24">24</td> <td align="left" csk="Graham,Jamie"><a href="/cfb/players/jamie-graham-1.html">Jamie Graham</a></td> <td align="right" >8</td> <td align="right" >1</td> <td align="right" >9</td> <td align="right" >1.0</td> <td align="right" >0.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >1</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="25">25</td> <td align="left" csk="Garnham,Chase"><a href="/cfb/players/chase-garnham-1.html">Chase Garnham</a></td> <td align="right" >3</td> <td align="right" >5</td> <td align="right" >8</td> <td align="right" >0.5</td> <td align="right" >0.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="26">26</td> <td align="left" csk="Loftley,Taylor"><a href="/cfb/players/taylor-loftley-1.html">Taylor Loftley</a></td> <td align="right" >4</td> <td align="right" >3</td> <td align="right" >7</td> <td align="right" >0.0</td> <td align="right" >0.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="27">27</td> <td align="left" csk="Morse,Jared"><a href="/cfb/players/jared-morse-1.html">Jared Morse</a></td> <td align="right" >5</td> <td align="right" >2</td> <td align="right" >7</td> <td align="right" >1.0</td> <td align="right" >0.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >1</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="28">28</td> <td align="left" csk="Daniels,Dexter"><a href="/cfb/players/dexter-daniels-2.html">Dexter Daniels</a></td> <td align="right" >6</td> <td align="right" >0</td> <td align="right" >6</td> <td align="right" >0.0</td> <td align="right" >0.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="29">29</td> <td align="left" csk="Umoh,Udom"><a href="/cfb/players/udom-umoh-1.html">Udom Umoh</a></td> <td align="right" >5</td> <td align="right" >1</td> <td align="right" >6</td> <td align="right" >0.0</td> <td align="right" >0.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="30">30</td> <td align="left" csk="Marshall,Javon"><a href="/cfb/players/javon-marshall-1.html">Javon Marshall</a></td> <td align="right" >1</td> <td align="right" >3</td> <td align="right" >4</td> <td align="right" >0.0</td> <td align="right" >0.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >1</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >1</td> </tr> <tr class=""> <td align="right" csk="31">31</td> <td align="left" csk="Matthews,Jordan"><a href="/cfb/players/jordan-matthews-1.html">Jordan Matthews</a></td> <td align="right" >3</td> <td align="right" >1</td> <td align="right" >4</td> <td align="right" >0.0</td> <td align="right" >0.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="32">32</td> <td align="left" csk="Simmons,Andre"><a href="/cfb/players/andre-simmons-2.html">Andre Simmons</a></td> <td align="right" >4</td> <td align="right" >0</td> <td align="right" >4</td> <td align="right" >0.0</td> <td align="right" >0.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="33">33</td> <td align="left" csk="Butler,Karl"><a href="/cfb/players/karl-butler-1.html">Karl Butler</a></td> <td align="right" >1</td> <td align="right" >2</td> <td align="right" >3</td> <td align="right" >0.0</td> <td align="right" >0.0</td> <td align="right" >1</td> <td align="right" >33</td> <td align="right" >33.0</td> <td align="right" >0</td> <td align="right" >1</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="34">34</td> <td align="left" csk="Krause,Jonathan"><a href="/cfb/players/jonathan-krause-1.html">Jonathan Krause</a></td> <td align="right" >3</td> <td align="right" >0</td> <td align="right" >3</td> <td align="right" >0.0</td> <td align="right" >0.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="35">35</td> <td align="left" csk="Strong,Tristan"><a href="/cfb/players/tristan-strong-1.html">Tristan Strong</a></td> <td align="right" >2</td> <td align="right" >1</td> <td align="right" >3</td> <td align="right" >0.5</td> <td align="right" >0.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="36">36</td> <td align="left" csk="Van Rensburg,Ryan"><a href="/cfb/players/ryan-van-rensburg-1.html">Ryan Van Rensburg</a></td> <td align="right" >2</td> <td align="right" >1</td> <td align="right" >3</td> <td align="right" >0.0</td> <td align="right" >0.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="37">37</td> <td align="left" csk="Fischer,Kyle"><a href="/cfb/players/kyle-fischer-1.html">Kyle Fischer</a></td> <td align="right" >2</td> <td align="right" >0</td> <td align="right" >2</td> <td align="right" >0.0</td> <td align="right" >0.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="38">38</td> <td align="left" csk="Powell,Micah"><a href="/cfb/players/micah-powell-1.html">Micah Powell</a></td> <td align="right" >2</td> <td align="right" >0</td> <td align="right" >2</td> <td align="right" >0.0</td> <td align="right" >0.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="39">39</td> <td align="left" csk="Smotherman,Adam"><a href="/cfb/players/adam-smotherman-1.html">Adam Smotherman</a></td> <td align="right" >2</td> <td align="right" >0</td> <td align="right" >2</td> <td align="right" >0.0</td> <td align="right" >0.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="40">40</td> <td align="left" csk="Spear,Carey"><a href="/cfb/players/carey-spear-1.html">Carey Spear</a></td> <td align="right" >2</td> <td align="right" >0</td> <td align="right" >2</td> <td align="right" >0.0</td> <td align="right" >0.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="41">41</td> <td align="left" csk="Cole,John"><a href="/cfb/players/john-cole-1.html">John Cole</a></td> <td align="right" >0</td> <td align="right" >1</td> <td align="right" >1</td> <td align="right" >0.0</td> <td align="right" >0.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="42">42</td> <td align="left" csk="Funk,Jared"><a href="/cfb/players/jared-funk-1.html">Jared Funk</a></td> <td align="right" >1</td> <td align="right" >0</td> <td align="right" >1</td> <td align="right" >0.0</td> <td align="right" >0.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="43">43</td> <td align="left" csk="Giller,David"><a href="/cfb/players/david-giller-1.html">David Giller</a></td> <td align="right" >0</td> <td align="right" >1</td> <td align="right" >1</td> <td align="right" >0.0</td> <td align="right" >0.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="44">44</td> <td align="left" csk="Kent,Richard"><a href="/cfb/players/richard-kent-1.html">Richard Kent</a></td> <td align="right" >1</td> <td align="right" >0</td> <td align="right" >1</td> <td align="right" >0.0</td> <td align="right" >0.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="45">45</td> <td align="left" csk="McHaney,Thad"><a href="/cfb/players/thad-mchaney-1.html">Thad McHaney</a></td> <td align="right" >0</td> <td align="right" >1</td> <td align="right" >1</td> <td align="right" >0.5</td> <td align="right" >0.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="46">46</td> <td align="left" csk="Panu,Marc"><a href="/cfb/players/marc-panu-1.html">Marc Panu</a></td> <td align="right" >0</td> <td align="right" >1</td> <td align="right" >1</td> <td align="right" >0.0</td> <td align="right" >0.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="47">47</td> <td align="left" csk="Stacy,Zac"><a href="/cfb/players/zac-stacy-1.html">Zac Stacy</a></td> <td align="right" >1</td> <td align="right" >0</td> <td align="right" >1</td> <td align="right" >0.0</td> <td align="right" >0.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="48">48</td> <td align="left" csk="Vaughn,Duane"><a href="/cfb/players/duane-vaughn-1.html">Duane Vaughn</a></td> <td align="right" >0</td> <td align="right" >1</td> <td align="right" >1</td> <td align="right" >0.0</td> <td align="right" >0.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="49">49</td> <td align="left" csk="Wimberly,Turner"><a href="/cfb/players/turner-wimberly-1.html">Turner Wimberly</a></td> <td align="right" >1</td> <td align="right" >0</td> <td align="right" >1</td> <td align="right" >0.0</td> <td align="right" >0.0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> </tbody> </table> </div> <div class="table_heading"> <h2 style="">Kick &amp; Punt Returns</h2> <div class="table_heading_text"></div> </div> <div class="table_container" id="div_returns"> <table class="sortable stats_table" id="returns"> <colgroup><col><col><col><col><col><col><col><col><col><col></colgroup> <thead> <tr class=" over_header"> <th align="CENTER" colspan=2 class="tooltip over_header" ></th> <th align="center" colspan=4 class="bold_text over_header" >Kick Ret</th> <th align="center" colspan=4 class="bold_text over_header" >Punt Ret</th> </tr> <tr class=""> <th align="right" class="ranker sort_default_asc" tip="Rank">Rk</th> <th align="left" class="tooltip sort_default_asc" >Player</th> <th align="right" class="tooltip" tip="Kickoff Returns">Ret</th> <th align="right" class="tooltip" tip="Kickoff Return Yards">Yds</th> <th align="right" class="tooltip" tip="Kickoff Return Yards Per Return">Avg</th> <th align="right" class="tooltip" tip="Kickoff Return Touchdowns">TD</th> <th align="right" class="tooltip" tip="Punt Returns">Ret</th> <th align="right" class="tooltip" tip="Punt Return Yards">Yds</th> <th align="right" class="tooltip" tip="Punt Return Yards Per Return">Avg</th> <th align="right" class="tooltip" tip="Punt Return Touchdowns">TD</th> </tr> </thead> <tbody> <tr class=""> <td align="right" csk="1">1</td> <td align="left" csk="Samuels,Eric"><a href="/cfb/players/eric-samuels-1.html">Eric Samuels</a></td> <td align="right" >27</td> <td align="right" >549</td> <td align="right" >20.3</td> <td align="right" >0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="2">2</td> <td align="left" csk="Norman,Warren"><a href="/cfb/players/warren-norman-1.html">Warren Norman</a></td> <td align="right" >22</td> <td align="right" >558</td> <td align="right" >25.4</td> <td align="right" >0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="3">3</td> <td align="left" csk="Hal,Andre"><a href="/cfb/players/andre-hal-1.html">Andre Hal</a></td> <td align="right" >11</td> <td align="right" >260</td> <td align="right" >23.6</td> <td align="right" >0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="4">4</td> <td align="left" csk="Wilson,Trey"><a href="/cfb/players/trey-wilson-1.html">Trey Wilson</a></td> <td align="right" >1</td> <td align="right" >2</td> <td align="right" >2.0</td> <td align="right" >0</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="5">5</td> <td align="left" csk="Cole,John"><a href="/cfb/players/john-cole-1.html">John Cole</a></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >18</td> <td align="right" >143</td> <td align="right" >7.9</td> <td align="right" >0</td> </tr> <tr class=""> <td align="right" csk="6">6</td> <td align="left" csk="Stacy,Zac"><a href="/cfb/players/zac-stacy-1.html">Zac Stacy</a></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >5</td> <td align="right" >12</td> <td align="right" >2.4</td> <td align="right" >0</td> </tr> <tr class=""> <td align="right" csk="7">7</td> <td align="left" csk="Van Rensburg,Ryan"><a href="/cfb/players/ryan-van-rensburg-1.html">Ryan Van Rensburg</a></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >1</td> <td align="right" >18</td> <td align="right" >18.0</td> <td align="right" >0</td> </tr> <tr class=""> <td align="right" csk="8">8</td> <td align="left" csk="Krause,Jonathan"><a href="/cfb/players/jonathan-krause-1.html">Jonathan Krause</a></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >1</td> <td align="right" >4</td> <td align="right" >4.0</td> <td align="right" >0</td> </tr> </tbody> </table> </div> <div class="table_heading"> <h2 style="">Kicking &amp; Punting</h2> <div class="table_heading_text"></div> </div> <div class="table_container" id="div_kicking_and_punting"> <table class="sortable stats_table" id="kicking_and_punting"> <colgroup><col><col><col><col><col><col><col><col><col><col><col><col></colgroup> <thead> <tr class=" over_header"> <th align="CENTER" colspan=2 class="tooltip over_header" ></th> <th align="center" colspan=7 class="bold_text over_header" >Kicking</th> <th align="center" colspan=3 class="bold_text over_header" >Punting</th> </tr> <tr class=""> <th align="right" class="ranker sort_default_asc" tip="Rank">Rk</th> <th align="left" class="tooltip sort_default_asc" >Player</th> <th align="right" class="tooltip" tip="Extra Points Made">XPM</th> <th align="right" class="tooltip" tip="Extra Point Attempts">XPA</th> <th align="right" class="tooltip" tip="Extra Point Percentage">XP%</th> <th align="right" class="tooltip" tip="Field Goals Made">FGM</th> <th align="right" class="tooltip" tip="Field Goal Attempts">FGA</th> <th align="right" class="tooltip" tip="Field Goal Percentage">FG%</th> <th align="right" class="tooltip" tip="Points Kicking">Pts</th> <th align="right" class="tooltip" tip="Punts">Punts</th> <th align="right" class="tooltip" tip="Punting Yards">Yds</th> <th align="right" class="tooltip" tip="Punting Yards Per Punt">Avg</th> </tr> </thead> <tbody> <tr class=""> <td align="right" csk="1">1</td> <td align="left" csk="Fowler,Ryan"><a href="/cfb/players/ryan-fowler-2.html">Ryan Fowler</a></td> <td align="right" >23</td> <td align="right" >24</td> <td align="right" >95.8</td> <td align="right" >8</td> <td align="right" >13</td> <td align="right" >61.5</td> <td align="right" >47</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> </tr> <tr class=""> <td align="right" csk="2">2</td> <td align="left" csk="Kent,Richard"><a href="/cfb/players/richard-kent-1.html">Richard Kent</a></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >84</td> <td align="right" >3511</td> <td align="right" >41.8</td> </tr> </tbody> </table> </div> <div class="table_heading"> <h2 style="">Scoring</h2> <div class="table_heading_text"></div> </div> <div class="table_container" id="div_scoring"> <table class="sortable stats_table" id="scoring"> <colgroup><col><col><col><col><col><col><col><col><col><col><col><col><col><col><col></colgroup> <thead> <tr class=" over_header"> <th align="CENTER" colspan=2 class="tooltip over_header" ></th> <th align="center" colspan=8 class="bold_text over_header" >Touchdowns</th> <th align="center" colspan=2 class="bold_text over_header" >Kicking</th> <th align="CENTER" colspan=2 class="tooltip over_header" ></th> <th></th> </tr> <tr class=""> <th align="right" class="ranker sort_default_asc" tip="Rank">Rk</th> <th align="left" class="tooltip sort_default_asc" >Player</th> <th align="right" class="tooltip" tip="Rushing Touchdowns">Rush</th> <th align="right" class="tooltip" tip="Receiving Touchdowns">Rec</th> <th align="right" class="tooltip" tip="Interception Return Touchdowns">Int</th> <th align="right" class="tooltip" tip="Fumble Recovery Return Touchdowns">FR</th> <th align="right" class="tooltip" tip="Punt Return Touchdowns">PR</th> <th align="right" class="tooltip" tip="Kick Return Touchdowns">KR</th> <th align="right" class="tooltip" tip="Other Touchdowns">Oth</th> <th align="right" class="tooltip" tip="Total Touchdowns">Tot</th> <th align="right" class="tooltip" tip="Extra Points Made">XPM</th> <th align="right" class="tooltip" tip="Field Goals Made">FGM</th> <th align="right" class="tooltip" tip="Two-Point Conversions Made">2PM</th> <th align="right" class="tooltip" tip="Safeties">Sfty</th> <th align="right" class="tooltip" tip="Points">Pts</th> </tr> </thead> <tbody> <tr class=""> <td align="right" csk="1">1</td> <td align="left" csk="Fowler,Ryan"><a href="/cfb/players/ryan-fowler-2.html">Ryan Fowler</a></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >23</td> <td align="right" >8</td> <td align="right" ></td> <td align="right" ></td> <td align="right" >47</td> </tr> <tr class=""> <td align="right" csk="2">2</td> <td align="left" csk="Smith,Larry"><a href="/cfb/players/larry-smith-1.html">Larry Smith</a></td> <td align="right" >4</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >4</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >24</td> </tr> <tr class=""> <td align="right" csk="3">3</td> <td align="left" csk="Norman,Warren"><a href="/cfb/players/warren-norman-1.html">Warren Norman</a></td> <td align="right" >4</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >4</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >24</td> </tr> <tr class=""> <td align="right" csk="4">4</td> <td align="left" csk="Matthews,Jordan"><a href="/cfb/players/jordan-matthews-1.html">Jordan Matthews</a></td> <td align="right" ></td> <td align="right" >4</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >4</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >24</td> </tr> <tr class=""> <td align="right" csk="5">5</td> <td align="left" csk="Barden,Brandon"><a href="/cfb/players/brandon-barden-1.html">Brandon Barden</a></td> <td align="right" ></td> <td align="right" >3</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >3</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >18</td> </tr> <tr class=""> <td align="right" csk="6">6</td> <td align="left" csk="Stacy,Zac"><a href="/cfb/players/zac-stacy-1.html">Zac Stacy</a></td> <td align="right" >3</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >3</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >18</td> </tr> <tr class=""> <td align="right" csk="7">7</td> <td align="left" csk="Krause,Jonathan"><a href="/cfb/players/jonathan-krause-1.html">Jonathan Krause</a></td> <td align="right" >2</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >2</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >12</td> </tr> <tr class=""> <td align="right" csk="8">8</td> <td align="left" csk="Umoh,Udom"><a href="/cfb/players/udom-umoh-1.html">Udom Umoh</a></td> <td align="right" ></td> <td align="right" >2</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >2</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >12</td> </tr> <tr class=""> <td align="right" csk="9">9</td> <td align="left" csk="Cole,John"><a href="/cfb/players/john-cole-1.html">John Cole</a></td> <td align="right" ></td> <td align="right" >1</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >1</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >6</td> </tr> <tr class=""> <td align="right" csk="10">10</td> <td align="left" csk="Johnston,Mason"><a href="/cfb/players/mason-johnston-1.html">Mason Johnston</a></td> <td align="right" ></td> <td align="right" >1</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >1</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >6</td> </tr> <tr class=""> <td align="right" csk="11">11</td> <td align="left" csk="Marshall,Javon"><a href="/cfb/players/javon-marshall-1.html">Javon Marshall</a></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >1</td> <td align="right" ></td> <td align="right" ></td> <td align="right" >1</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >6</td> </tr> <tr class=""> <td align="right" csk="12">12</td> <td align="left" csk="Foster,Eddie"><a href="/cfb/players/eddie-foster-1.html">Eddie Foster</a></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >1</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >1</td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" ></td> <td align="right" >6</td> </tr> </tbody> </table> </div> </div> <div id="sr_js"></div> <script type="text/javascript"> (function () { var sr_js_file = 'http://d2ft4b0ve1aur1.cloudfront.net/js-237/sr-cfb-min.js'; if (sr_gzipEnabled) { sr_js_file = 'http://d2ft4b0ve1aur1.cloudfront.net/js-237/sr-cfb-min.js.jgz'; } var sr_script_tag = document.getElementById("sr_js"); if (sr_script_tag) { var scriptStyles = document.createElement("script"); scriptStyles.type = "text/javascript"; scriptStyles.src = sr_js_file; sr_script_tag.appendChild(scriptStyles); //alert('adding js to footer:'+sr_js_file); } }()); </script> <div id="site_footer"> <div class="margin border"> <script type="text/javascript"> //<!-- google_ad_client = "ca-pub-5319453360923253"; /* Page Bottom - CFB */ google_ad_slot = "6637784901"; google_ad_width = 728; google_ad_height = 90; //--> </script> <script type="text/deferscript" defersrc="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script> </div> <div id="sr_footer"> Copyright &copy; 2000-2012 <a href="http://www.sports-reference.com">Sports Reference LLC</a>. All rights reserved. <form class="inline margin_left" method="get" name="f_footer" action="/cfb/search.cgi"> <input x-webkit-speech type="text" id="search_footer" name="search" class="search long"> <input type="submit" value="Search" class="submit"> </form> <div class="blockquote clear_both margin_top"> <a href="http://www.sports-reference.com/">A Sports Reference Site</a>: <a href="/cfb/about/">About SR/CFB</a>&nbsp;| <a href="/cfb/feedback/">Found a bug or have a suggestion?</a><br> <a href="http://www.sports-reference.com/privacy.shtml">Privacy Statement</a>&nbsp;| <a href="http://www.sports-reference.com/termsofuse.shtml">Conditions &amp; Terms of Service</a> | <a href="http://www.sports-reference.com/data_use.shtml">Use of Data</a> </div> <div class="blockquote italic_text clear_both margin_top"> Some school's results have been altered by retroactive NCAA penalties. As a matter of policy, Sports Reference only report the results of games as played on the field. See our list of <a href="/cfb/friv/forfeits.cgi">forfeits and vacated games</a> for more details. </div> <div class="blockquote clear_both margin_top margin_bottom"> Part of the <a target="_blank" title="USA TODAY Sports" href="http://Sports.USATODAY.com/">USA TODAY Sports Media Group</a>. </div> </div><!-- div#sr_footer --> </div><!-- div#site_footer --> <!-- google +1 code --> <script type="text/deferscript"> (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })(); </script> <!-- google analytics code --> <script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script> <script type="text/javascript"> try { var pageTracker = _gat._createTracker("UA-1890630-11"); pageTracker._setCookiePath("/cfb/"); pageTracker._trackPageview(); pageTracker._trackPageLoadTime(); var sr_tracker = _gat._createTracker("UA-1890630-9"); sr_tracker._setDomainName('none'); sr_tracker._setAllowLinker(true); sr_tracker._setAllowHash(false); sr_tracker._setCustomVar(1,"site","cfb",3); sr_tracker._trackPageview(); } catch(err) {}</script> <!-- End Google Analytics Tag --> <!-- Begin comScore Tag --> <script type="text/deferscript"> document.write(unescape("%3Cscript src='" + (document.location.protocol == "https:" ? "https://sb" : "http://b") + ".scorecardresearch.com/beacon.js' %3E%3C/script%3E")); </script> <script type="text/deferscript"> COMSCORE.beacon({ c1:2, c2:"6035210", c3:"", c4:"www.sports-reference.com/cfb", c5:"", c6:"", c15:"" }); </script> <noscript> <img src="http://b.scorecardresearch.com/b?c1=2&amp;c2=6035210&amp;c3=&amp;c4=www.sports-reference.com/cfb&amp;c5=&amp;c6=&amp;c15=&amp;cv=1.3&amp;cj=1" width="0" height="0" alt="" /> </noscript> <!-- End comScore Tag --> <script type="text/deferscript"> (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=220051088022369"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); </script> <!-- google +1 code --> <script type="text/deferscript"> (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })(); </script> </div> </body> </html>
vrivellino/cfs
source_data/2010/stats/Vanderbilt.html
HTML
gpl-2.0
81,049
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Search &mdash; ORMPY 0.1 documentation</title> <link rel="stylesheet" href="_static/default.css" type="text/css" /> <link rel="stylesheet" href="_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: './', VERSION: '0.1', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="_static/jquery.js"></script> <script type="text/javascript" src="_static/underscore.js"></script> <script type="text/javascript" src="_static/doctools.js"></script> <script type="text/javascript" src="_static/searchtools.js"></script> <link rel="top" title="ORMPY 0.1 documentation" href="index.html" /> <script type="text/javascript"> jQuery(function() { Search.loadIndex("searchindex.js"); }); </script> <script type="text/javascript" id="searchindexloader"></script> </head> <body> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="py-modindex.html" title="Python Module Index" >modules</a> |</li> <li><a href="index.html">ORMPY 0.1 documentation</a> &raquo;</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body"> <h1 id="search-documentation">Search</h1> <div id="fallback" class="admonition warning"> <script type="text/javascript">$('#fallback').hide();</script> <p> Please activate JavaScript to enable the search functionality. </p> </div> <p> From here you can search these documents. Enter your search words into the box below and click "search". Note that the search function will automatically search for all of the words. Pages containing fewer words won't appear in the result list. </p> <form action="" method="get"> <input type="text" name="q" value="" /> <input type="submit" value="search" /> <span id="search-progress" style="padding-left: 10px"></span> </form> <div id="search-results"> </div> </div> </div> </div> <div class="sphinxsidebar"> <div class="sphinxsidebarwrapper"> </div> </div> <div class="clearer"></div> </div> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="py-modindex.html" title="Python Module Index" >modules</a> |</li> <li><a href="index.html">ORMPY 0.1 documentation</a> &raquo;</li> </ul> </div> <div class="footer"> &copy; Copyright 2014, Matthew Nizol. Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.2.2. </div> </body> </html>
mnizol/ormpy
doc/_build/html/search.html
HTML
gpl-2.0
3,409
/* * Copyright (C) 2005-2011 MaNGOS <http://getmangos.com/> * * 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 "Common.h" #include "Log.h" #include "ObjectMgr.h" #include "SpellMgr.h" #include "Player.h" #include "Unit.h" #include "Spell.h" #include "SpellAuras.h" #include "Totem.h" #include "Creature.h" #include "Formulas.h" #include "CreatureAI.h" #include "Util.h" pAuraProcHandler AuraProcHandler[TOTAL_AURAS]= { &Unit::HandleNULLProc, // 0 SPELL_AURA_NONE &Unit::HandleNULLProc, // 1 SPELL_AURA_BIND_SIGHT &Unit::HandleNULLProc, // 2 SPELL_AURA_MOD_POSSESS &Unit::HandleNULLProc, // 3 SPELL_AURA_PERIODIC_DAMAGE &Unit::HandleDummyAuraProc, // 4 SPELL_AURA_DUMMY &Unit::HandleRemoveByDamageProc, // 5 SPELL_AURA_MOD_CONFUSE &Unit::HandleNULLProc, // 6 SPELL_AURA_MOD_CHARM &Unit::HandleRemoveByDamageChanceProc, // 7 SPELL_AURA_MOD_FEAR &Unit::HandleNULLProc, // 8 SPELL_AURA_PERIODIC_HEAL &Unit::HandleNULLProc, // 9 SPELL_AURA_MOD_ATTACKSPEED &Unit::HandleNULLProc, // 10 SPELL_AURA_MOD_THREAT &Unit::HandleNULLProc, // 11 SPELL_AURA_MOD_TAUNT &Unit::HandleNULLProc, // 12 SPELL_AURA_MOD_STUN &Unit::HandleNULLProc, // 13 SPELL_AURA_MOD_DAMAGE_DONE &Unit::HandleNULLProc, // 14 SPELL_AURA_MOD_DAMAGE_TAKEN &Unit::HandleNULLProc, // 15 SPELL_AURA_DAMAGE_SHIELD &Unit::HandleRemoveByDamageProc, // 16 SPELL_AURA_MOD_STEALTH &Unit::HandleNULLProc, // 17 SPELL_AURA_MOD_STEALTH_DETECT &Unit::HandleRemoveByDamageProc, // 18 SPELL_AURA_MOD_INVISIBILITY &Unit::HandleNULLProc, // 19 SPELL_AURA_MOD_INVISIBILITY_DETECTION &Unit::HandleNULLProc, // 20 SPELL_AURA_OBS_MOD_HEALTH &Unit::HandleNULLProc, // 21 SPELL_AURA_OBS_MOD_MANA &Unit::HandleNULLProc, // 22 SPELL_AURA_MOD_RESISTANCE &Unit::HandleNULLProc, // 23 SPELL_AURA_PERIODIC_TRIGGER_SPELL &Unit::HandleNULLProc, // 24 SPELL_AURA_PERIODIC_ENERGIZE &Unit::HandleNULLProc, // 25 SPELL_AURA_MOD_PACIFY &Unit::HandleRemoveByDamageChanceProc, // 26 SPELL_AURA_MOD_ROOT &Unit::HandleNULLProc, // 27 SPELL_AURA_MOD_SILENCE &Unit::HandleNULLProc, // 28 SPELL_AURA_REFLECT_SPELLS &Unit::HandleNULLProc, // 29 SPELL_AURA_MOD_STAT &Unit::HandleNULLProc, // 30 SPELL_AURA_MOD_SKILL &Unit::HandleNULLProc, // 31 SPELL_AURA_MOD_INCREASE_SPEED &Unit::HandleNULLProc, // 32 SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED &Unit::HandleNULLProc, // 33 SPELL_AURA_MOD_DECREASE_SPEED &Unit::HandleNULLProc, // 34 SPELL_AURA_MOD_INCREASE_HEALTH &Unit::HandleNULLProc, // 35 SPELL_AURA_MOD_INCREASE_ENERGY &Unit::HandleNULLProc, // 36 SPELL_AURA_MOD_SHAPESHIFT &Unit::HandleNULLProc, // 37 SPELL_AURA_EFFECT_IMMUNITY &Unit::HandleNULLProc, // 38 SPELL_AURA_STATE_IMMUNITY &Unit::HandleNULLProc, // 39 SPELL_AURA_SCHOOL_IMMUNITY &Unit::HandleNULLProc, // 40 SPELL_AURA_DAMAGE_IMMUNITY &Unit::HandleNULLProc, // 41 SPELL_AURA_DISPEL_IMMUNITY &Unit::HandleProcTriggerSpellAuraProc, // 42 SPELL_AURA_PROC_TRIGGER_SPELL &Unit::HandleProcTriggerDamageAuraProc, // 43 SPELL_AURA_PROC_TRIGGER_DAMAGE &Unit::HandleNULLProc, // 44 SPELL_AURA_TRACK_CREATURES &Unit::HandleNULLProc, // 45 SPELL_AURA_TRACK_RESOURCES &Unit::HandleNULLProc, // 46 SPELL_AURA_46 (used in test spells 54054 and 54058, and spell 48050) (3.0.8a-3.2.2a) &Unit::HandleNULLProc, // 47 SPELL_AURA_MOD_PARRY_PERCENT &Unit::HandleNULLProc, // 48 SPELL_AURA_48 spell Napalm (area damage spell with additional delayed damage effect) &Unit::HandleNULLProc, // 49 SPELL_AURA_MOD_DODGE_PERCENT &Unit::HandleNULLProc, // 50 SPELL_AURA_MOD_CRITICAL_HEALING_AMOUNT &Unit::HandleNULLProc, // 51 SPELL_AURA_MOD_BLOCK_PERCENT &Unit::HandleNULLProc, // 52 SPELL_AURA_MOD_CRIT_PERCENT &Unit::HandleNULLProc, // 53 SPELL_AURA_PERIODIC_LEECH &Unit::HandleNULLProc, // 54 SPELL_AURA_MOD_HIT_CHANCE &Unit::HandleNULLProc, // 55 SPELL_AURA_MOD_SPELL_HIT_CHANCE &Unit::HandleNULLProc, // 56 SPELL_AURA_TRANSFORM &Unit::HandleSpellCritChanceAuraProc, // 57 SPELL_AURA_MOD_SPELL_CRIT_CHANCE &Unit::HandleNULLProc, // 58 SPELL_AURA_MOD_INCREASE_SWIM_SPEED &Unit::HandleNULLProc, // 59 SPELL_AURA_MOD_DAMAGE_DONE_CREATURE &Unit::HandleRemoveByDamageChanceProc, // 60 SPELL_AURA_MOD_PACIFY_SILENCE &Unit::HandleNULLProc, // 61 SPELL_AURA_MOD_SCALE &Unit::HandleNULLProc, // 62 SPELL_AURA_PERIODIC_HEALTH_FUNNEL &Unit::HandleNULLProc, // 63 unused (3.0.8a-3.2.2a) old SPELL_AURA_PERIODIC_MANA_FUNNEL &Unit::HandleNULLProc, // 64 SPELL_AURA_PERIODIC_MANA_LEECH &Unit::HandleModCastingSpeedNotStackAuraProc, // 65 SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK &Unit::HandleNULLProc, // 66 SPELL_AURA_FEIGN_DEATH &Unit::HandleNULLProc, // 67 SPELL_AURA_MOD_DISARM &Unit::HandleNULLProc, // 68 SPELL_AURA_MOD_STALKED &Unit::HandleNULLProc, // 69 SPELL_AURA_SCHOOL_ABSORB &Unit::HandleNULLProc, // 70 SPELL_AURA_EXTRA_ATTACKS Useless, used by only one spell 41560 that has only visual effect (3.2.2a) &Unit::HandleNULLProc, // 71 SPELL_AURA_MOD_SPELL_CRIT_CHANCE_SCHOOL &Unit::HandleModPowerCostSchoolAuraProc, // 72 SPELL_AURA_MOD_POWER_COST_SCHOOL_PCT &Unit::HandleModPowerCostSchoolAuraProc, // 73 SPELL_AURA_MOD_POWER_COST_SCHOOL &Unit::HandleReflectSpellsSchoolAuraProc, // 74 SPELL_AURA_REFLECT_SPELLS_SCHOOL &Unit::HandleNULLProc, // 75 SPELL_AURA_MOD_LANGUAGE &Unit::HandleNULLProc, // 76 SPELL_AURA_FAR_SIGHT &Unit::HandleMechanicImmuneResistanceAuraProc, // 77 SPELL_AURA_MECHANIC_IMMUNITY &Unit::HandleNULLProc, // 78 SPELL_AURA_MOUNTED &Unit::HandleModDamagePercentDoneAuraProc, // 79 SPELL_AURA_MOD_DAMAGE_PERCENT_DONE &Unit::HandleNULLProc, // 80 SPELL_AURA_MOD_PERCENT_STAT &Unit::HandleNULLProc, // 81 SPELL_AURA_SPLIT_DAMAGE_PCT &Unit::HandleNULLProc, // 82 SPELL_AURA_WATER_BREATHING &Unit::HandleNULLProc, // 83 SPELL_AURA_MOD_BASE_RESISTANCE &Unit::HandleNULLProc, // 84 SPELL_AURA_MOD_REGEN &Unit::HandleCantTrigger, // 85 SPELL_AURA_MOD_POWER_REGEN &Unit::HandleNULLProc, // 86 SPELL_AURA_CHANNEL_DEATH_ITEM &Unit::HandleNULLProc, // 87 SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN &Unit::HandleNULLProc, // 88 SPELL_AURA_MOD_HEALTH_REGEN_PERCENT &Unit::HandleNULLProc, // 89 SPELL_AURA_PERIODIC_DAMAGE_PERCENT &Unit::HandleNULLProc, // 90 unused (3.0.8a-3.2.2a) old SPELL_AURA_MOD_RESIST_CHANCE &Unit::HandleNULLProc, // 91 SPELL_AURA_MOD_DETECT_RANGE &Unit::HandleNULLProc, // 92 SPELL_AURA_PREVENTS_FLEEING &Unit::HandleNULLProc, // 93 SPELL_AURA_MOD_UNATTACKABLE &Unit::HandleNULLProc, // 94 SPELL_AURA_INTERRUPT_REGEN &Unit::HandleNULLProc, // 95 SPELL_AURA_GHOST &Unit::HandleNULLProc, // 96 SPELL_AURA_SPELL_MAGNET &Unit::HandleNULLProc, // 97 SPELL_AURA_MANA_SHIELD &Unit::HandleNULLProc, // 98 SPELL_AURA_MOD_SKILL_TALENT &Unit::HandleNULLProc, // 99 SPELL_AURA_MOD_ATTACK_POWER &Unit::HandleNULLProc, //100 SPELL_AURA_AURAS_VISIBLE obsolete 3.x? all player can see all auras now, but still have 2 spells including GM-spell (1852,2855) &Unit::HandleNULLProc, //101 SPELL_AURA_MOD_RESISTANCE_PCT &Unit::HandleNULLProc, //102 SPELL_AURA_MOD_MELEE_ATTACK_POWER_VERSUS &Unit::HandleNULLProc, //103 SPELL_AURA_MOD_TOTAL_THREAT &Unit::HandleNULLProc, //104 SPELL_AURA_WATER_WALK &Unit::HandleNULLProc, //105 SPELL_AURA_FEATHER_FALL &Unit::HandleNULLProc, //106 SPELL_AURA_HOVER &Unit::HandleAddFlatModifierAuraProc, //107 SPELL_AURA_ADD_FLAT_MODIFIER &Unit::HandleAddPctModifierAuraProc, //108 SPELL_AURA_ADD_PCT_MODIFIER &Unit::HandleNULLProc, //109 SPELL_AURA_ADD_TARGET_TRIGGER &Unit::HandleNULLProc, //110 SPELL_AURA_MOD_POWER_REGEN_PERCENT &Unit::HandleNULLProc, //111 SPELL_AURA_ADD_CASTER_HIT_TRIGGER &Unit::HandleOverrideClassScriptAuraProc, //112 SPELL_AURA_OVERRIDE_CLASS_SCRIPTS &Unit::HandleNULLProc, //113 SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN &Unit::HandleNULLProc, //114 SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN_PCT &Unit::HandleNULLProc, //115 SPELL_AURA_MOD_HEALING &Unit::HandleNULLProc, //116 SPELL_AURA_MOD_REGEN_DURING_COMBAT &Unit::HandleMechanicImmuneResistanceAuraProc, //117 SPELL_AURA_MOD_MECHANIC_RESISTANCE &Unit::HandleNULLProc, //118 SPELL_AURA_MOD_HEALING_PCT &Unit::HandleNULLProc, //119 unused (3.0.8a-3.2.2a) old SPELL_AURA_SHARE_PET_TRACKING &Unit::HandleNULLProc, //120 SPELL_AURA_UNTRACKABLE &Unit::HandleNULLProc, //121 SPELL_AURA_EMPATHY &Unit::HandleNULLProc, //122 SPELL_AURA_MOD_OFFHAND_DAMAGE_PCT &Unit::HandleNULLProc, //123 SPELL_AURA_MOD_TARGET_RESISTANCE &Unit::HandleNULLProc, //124 SPELL_AURA_MOD_RANGED_ATTACK_POWER &Unit::HandleNULLProc, //125 SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN &Unit::HandleNULLProc, //126 SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN_PCT &Unit::HandleNULLProc, //127 SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS &Unit::HandleNULLProc, //128 SPELL_AURA_MOD_POSSESS_PET &Unit::HandleNULLProc, //129 SPELL_AURA_MOD_SPEED_ALWAYS &Unit::HandleNULLProc, //130 SPELL_AURA_MOD_MOUNTED_SPEED_ALWAYS &Unit::HandleNULLProc, //131 SPELL_AURA_MOD_RANGED_ATTACK_POWER_VERSUS &Unit::HandleNULLProc, //132 SPELL_AURA_MOD_INCREASE_ENERGY_PERCENT &Unit::HandleNULLProc, //133 SPELL_AURA_MOD_INCREASE_HEALTH_PERCENT &Unit::HandleNULLProc, //134 SPELL_AURA_MOD_MANA_REGEN_INTERRUPT &Unit::HandleNULLProc, //135 SPELL_AURA_MOD_HEALING_DONE &Unit::HandleNULLProc, //136 SPELL_AURA_MOD_HEALING_DONE_PERCENT &Unit::HandleNULLProc, //137 SPELL_AURA_MOD_TOTAL_STAT_PERCENTAGE &Unit::HandleHasteAuraProc, //138 SPELL_AURA_MOD_MELEE_HASTE &Unit::HandleNULLProc, //139 SPELL_AURA_FORCE_REACTION &Unit::HandleNULLProc, //140 SPELL_AURA_MOD_RANGED_HASTE &Unit::HandleNULLProc, //141 SPELL_AURA_MOD_RANGED_AMMO_HASTE &Unit::HandleNULLProc, //142 SPELL_AURA_MOD_BASE_RESISTANCE_PCT &Unit::HandleNULLProc, //143 SPELL_AURA_MOD_RESISTANCE_EXCLUSIVE &Unit::HandleNULLProc, //144 SPELL_AURA_SAFE_FALL &Unit::HandleNULLProc, //145 SPELL_AURA_MOD_PET_TALENT_POINTS &Unit::HandleNULLProc, //146 SPELL_AURA_ALLOW_TAME_PET_TYPE &Unit::HandleNULLProc, //147 SPELL_AURA_MECHANIC_IMMUNITY_MASK &Unit::HandleNULLProc, //148 SPELL_AURA_RETAIN_COMBO_POINTS &Unit::HandleCantTrigger, //149 SPELL_AURA_REDUCE_PUSHBACK &Unit::HandleNULLProc, //150 SPELL_AURA_MOD_SHIELD_BLOCKVALUE_PCT &Unit::HandleNULLProc, //151 SPELL_AURA_TRACK_STEALTHED &Unit::HandleNULLProc, //152 SPELL_AURA_MOD_DETECTED_RANGE &Unit::HandleNULLProc, //153 SPELL_AURA_SPLIT_DAMAGE_FLAT &Unit::HandleNULLProc, //154 SPELL_AURA_MOD_STEALTH_LEVEL &Unit::HandleNULLProc, //155 SPELL_AURA_MOD_WATER_BREATHING &Unit::HandleNULLProc, //156 SPELL_AURA_MOD_REPUTATION_GAIN &Unit::HandleNULLProc, //157 SPELL_AURA_PET_DAMAGE_MULTI (single test like spell 20782, also single for 214 aura) &Unit::HandleNULLProc, //158 SPELL_AURA_MOD_SHIELD_BLOCKVALUE &Unit::HandleNULLProc, //159 SPELL_AURA_NO_PVP_CREDIT &Unit::HandleNULLProc, //160 SPELL_AURA_MOD_AOE_AVOIDANCE &Unit::HandleNULLProc, //161 SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT &Unit::HandleNULLProc, //162 SPELL_AURA_POWER_BURN_MANA &Unit::HandleNULLProc, //163 SPELL_AURA_MOD_CRIT_DAMAGE_BONUS &Unit::HandleNULLProc, //164 unused (3.0.8a-3.2.2a), only one test spell 10654 &Unit::HandleNULLProc, //165 SPELL_AURA_MELEE_ATTACK_POWER_ATTACKER_BONUS &Unit::HandleNULLProc, //166 SPELL_AURA_MOD_ATTACK_POWER_PCT &Unit::HandleNULLProc, //167 SPELL_AURA_MOD_RANGED_ATTACK_POWER_PCT &Unit::HandleNULLProc, //168 SPELL_AURA_MOD_DAMAGE_DONE_VERSUS &Unit::HandleNULLProc, //169 SPELL_AURA_MOD_CRIT_PERCENT_VERSUS &Unit::HandleNULLProc, //170 SPELL_AURA_DETECT_AMORE different spells that ignore transformation effects &Unit::HandleNULLProc, //171 SPELL_AURA_MOD_SPEED_NOT_STACK &Unit::HandleNULLProc, //172 SPELL_AURA_MOD_MOUNTED_SPEED_NOT_STACK &Unit::HandleNULLProc, //173 unused (3.0.8a-3.2.2a) no spells, old SPELL_AURA_ALLOW_CHAMPION_SPELLS only for Proclaim Champion spell &Unit::HandleNULLProc, //174 SPELL_AURA_MOD_SPELL_DAMAGE_OF_STAT_PERCENT &Unit::HandleNULLProc, //175 SPELL_AURA_MOD_SPELL_HEALING_OF_STAT_PERCENT &Unit::HandleNULLProc, //176 SPELL_AURA_SPIRIT_OF_REDEMPTION only for Spirit of Redemption spell, die at aura end &Unit::HandleNULLProc, //177 SPELL_AURA_AOE_CHARM (22 spells) &Unit::HandleNULLProc, //178 SPELL_AURA_MOD_DEBUFF_RESISTANCE &Unit::HandleNULLProc, //179 SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_CHANCE &Unit::HandleNULLProc, //180 SPELL_AURA_MOD_FLAT_SPELL_DAMAGE_VERSUS &Unit::HandleNULLProc, //181 unused (3.0.8a-3.2.2a) old SPELL_AURA_MOD_FLAT_SPELL_CRIT_DAMAGE_VERSUS &Unit::HandleNULLProc, //182 SPELL_AURA_MOD_RESISTANCE_OF_STAT_PERCENT &Unit::HandleNULLProc, //183 SPELL_AURA_MOD_CRITICAL_THREAT only used in 28746 &Unit::HandleNULLProc, //184 SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE &Unit::HandleNULLProc, //185 SPELL_AURA_MOD_ATTACKER_RANGED_HIT_CHANCE &Unit::HandleNULLProc, //186 SPELL_AURA_MOD_ATTACKER_SPELL_HIT_CHANCE &Unit::HandleNULLProc, //187 SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_CHANCE &Unit::HandleNULLProc, //188 SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_CHANCE &Unit::HandleModRating, //189 SPELL_AURA_MOD_RATING &Unit::HandleNULLProc, //190 SPELL_AURA_MOD_FACTION_REPUTATION_GAIN &Unit::HandleNULLProc, //191 SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED &Unit::HandleNULLProc, //192 SPELL_AURA_HASTE_MELEE &Unit::HandleNULLProc, //193 SPELL_AURA_HASTE_ALL (in fact combat (any type attack) speed pct) &Unit::HandleNULLProc, //194 SPELL_AURA_MOD_IGNORE_ABSORB_SCHOOL &Unit::HandleNULLProc, //195 SPELL_AURA_MOD_IGNORE_ABSORB_FOR_SPELL &Unit::HandleNULLProc, //196 SPELL_AURA_MOD_COOLDOWN (single spell 24818 in 3.2.2a) &Unit::HandleNULLProc, //197 SPELL_AURA_MOD_ATTACKER_SPELL_AND_WEAPON_CRIT_CHANCEe &Unit::HandleNULLProc, //198 unused (3.0.8a-3.2.2a) old SPELL_AURA_MOD_ALL_WEAPON_SKILLS &Unit::HandleNULLProc, //199 SPELL_AURA_MOD_INCREASES_SPELL_PCT_TO_HIT &Unit::HandleNULLProc, //200 SPELL_AURA_MOD_KILL_XP_PCT &Unit::HandleNULLProc, //201 SPELL_AURA_FLY this aura enable flight mode... &Unit::HandleNULLProc, //202 SPELL_AURA_CANNOT_BE_DODGED &Unit::HandleNULLProc, //203 SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE &Unit::HandleNULLProc, //204 SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE &Unit::HandleNULLProc, //205 SPELL_AURA_MOD_ATTACKER_SPELL_CRIT_DAMAGE &Unit::HandleNULLProc, //206 SPELL_AURA_MOD_FLIGHT_SPEED &Unit::HandleNULLProc, //207 SPELL_AURA_MOD_FLIGHT_SPEED_MOUNTED &Unit::HandleNULLProc, //208 SPELL_AURA_MOD_FLIGHT_SPEED_STACKING &Unit::HandleNULLProc, //209 SPELL_AURA_MOD_FLIGHT_SPEED_MOUNTED_STACKING &Unit::HandleNULLProc, //210 SPELL_AURA_MOD_FLIGHT_SPEED_NOT_STACKING &Unit::HandleNULLProc, //211 SPELL_AURA_MOD_FLIGHT_SPEED_MOUNTED_NOT_STACKING &Unit::HandleNULLProc, //212 SPELL_AURA_MOD_RANGED_ATTACK_POWER_OF_STAT_PERCENT &Unit::HandleNULLProc, //213 SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT implemented in Player::RewardRage &Unit::HandleNULLProc, //214 Tamed Pet Passive (single test like spell 20782, also single for 157 aura) &Unit::HandleNULLProc, //215 SPELL_AURA_ARENA_PREPARATION &Unit::HandleNULLProc, //216 SPELL_AURA_HASTE_SPELLS &Unit::HandleNULLProc, //217 unused (3.0.8a-3.2.2a) &Unit::HandleNULLProc, //218 SPELL_AURA_HASTE_RANGED &Unit::HandleNULLProc, //219 SPELL_AURA_MOD_MANA_REGEN_FROM_STAT &Unit::HandleNULLProc, //220 SPELL_AURA_MOD_RATING_FROM_STAT &Unit::HandleNULLProc, //221 ignored &Unit::HandleNULLProc, //222 unused (3.0.8a-3.2.2a) only for spell 44586 that not used in real spell cast &Unit::HandleNULLProc, //223 dummy code (cast damage spell to attacker) and another dymmy (jump to another nearby raid member) &Unit::HandleNULLProc, //224 unused (3.0.8a-3.2.2a) &Unit::HandleMendingAuraProc, //225 SPELL_AURA_PRAYER_OF_MENDING &Unit::HandlePeriodicDummyAuraProc, //226 SPELL_AURA_PERIODIC_DUMMY &Unit::HandleNULLProc, //227 SPELL_AURA_PERIODIC_TRIGGER_SPELL_WITH_VALUE &Unit::HandleNULLProc, //228 SPELL_AURA_DETECT_STEALTH &Unit::HandleNULLProc, //229 SPELL_AURA_MOD_AOE_DAMAGE_AVOIDANCE &Unit::HandleNULLProc, //230 Commanding Shout &Unit::HandleProcTriggerSpellAuraProc, //231 SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE &Unit::HandleNULLProc, //232 SPELL_AURA_MECHANIC_DURATION_MOD &Unit::HandleNULLProc, //233 set model id to the one of the creature with id m_modifier.m_miscvalue &Unit::HandleNULLProc, //234 SPELL_AURA_MECHANIC_DURATION_MOD_NOT_STACK &Unit::HandleNULLProc, //235 SPELL_AURA_MOD_DISPEL_RESIST &Unit::HandleNULLProc, //236 SPELL_AURA_CONTROL_VEHICLE &Unit::HandleNULLProc, //237 SPELL_AURA_MOD_SPELL_DAMAGE_OF_ATTACK_POWER &Unit::HandleNULLProc, //238 SPELL_AURA_MOD_SPELL_HEALING_OF_ATTACK_POWER &Unit::HandleNULLProc, //239 SPELL_AURA_MOD_SCALE_2 only in Noggenfogger Elixir (16595) before 2.3.0 aura 61 &Unit::HandleNULLProc, //240 SPELL_AURA_MOD_EXPERTISE &Unit::HandleNULLProc, //241 Forces the player to move forward &Unit::HandleNULLProc, //242 SPELL_AURA_MOD_SPELL_DAMAGE_FROM_HEALING (only 2 test spels in 3.2.2a) &Unit::HandleNULLProc, //243 faction reaction override spells &Unit::HandleNULLProc, //244 SPELL_AURA_COMPREHEND_LANGUAGE &Unit::HandleNULLProc, //245 SPELL_AURA_MOD_DURATION_OF_MAGIC_EFFECTS &Unit::HandleNULLProc, //246 SPELL_AURA_MOD_DURATION_OF_EFFECTS_BY_DISPEL &Unit::HandleNULLProc, //247 target to become a clone of the caster &Unit::HandleNULLProc, //248 SPELL_AURA_MOD_COMBAT_RESULT_CHANCE &Unit::HandleNULLProc, //249 SPELL_AURA_CONVERT_RUNE &Unit::HandleNULLProc, //250 SPELL_AURA_MOD_INCREASE_HEALTH_2 &Unit::HandleNULLProc, //251 SPELL_AURA_MOD_ENEMY_DODGE &Unit::HandleNULLProc, //252 SPELL_AURA_SLOW_ALL &Unit::HandleNULLProc, //253 SPELL_AURA_MOD_BLOCK_CRIT_CHANCE &Unit::HandleNULLProc, //254 SPELL_AURA_MOD_DISARM_SHIELD disarm Shield &Unit::HandleNULLProc, //255 SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT &Unit::HandleNULLProc, //256 SPELL_AURA_NO_REAGENT_USE Use SpellClassMask for spell select &Unit::HandleNULLProc, //257 SPELL_AURA_MOD_TARGET_RESIST_BY_SPELL_CLASS Use SpellClassMask for spell select &Unit::HandleNULLProc, //258 SPELL_AURA_MOD_SPELL_VISUAL &Unit::HandleNULLProc, //259 corrupt healing over time spell &Unit::HandleNULLProc, //260 SPELL_AURA_SCREEN_EFFECT (miscvalue = id in ScreenEffect.dbc) not required any code &Unit::HandleNULLProc, //261 SPELL_AURA_PHASE undetectable invisibility? &Unit::HandleNULLProc, //262 SPELL_AURA_IGNORE_UNIT_STATE &Unit::HandleNULLProc, //263 SPELL_AURA_ALLOW_ONLY_ABILITY player can use only abilities set in SpellClassMask &Unit::HandleNULLProc, //264 unused (3.0.8a-3.2.2a) &Unit::HandleNULLProc, //265 unused (3.0.8a-3.2.2a) &Unit::HandleNULLProc, //266 unused (3.0.8a-3.2.2a) &Unit::HandleNULLProc, //267 SPELL_AURA_MOD_IMMUNE_AURA_APPLY_SCHOOL &Unit::HandleNULLProc, //268 SPELL_AURA_MOD_ATTACK_POWER_OF_STAT_PERCENT &Unit::HandleNULLProc, //269 SPELL_AURA_MOD_IGNORE_DAMAGE_REDUCTION_SCHOOL &Unit::HandleNULLProc, //270 SPELL_AURA_MOD_IGNORE_TARGET_RESIST (unused in 3.2.2a) &Unit::HandleModDamageFromCasterAuraProc, //271 SPELL_AURA_MOD_DAMAGE_FROM_CASTER &Unit::HandleNULLProc, //272 SPELL_AURA_MAELSTROM_WEAPON (unclear use for aura, it used in (3.2.2a...3.3.0) in single spell 53817 that spellmode stacked and charged spell expected to be drop as stack &Unit::HandleNULLProc, //273 SPELL_AURA_X_RAY (client side implementation) &Unit::HandleNULLProc, //274 proc free shot? &Unit::HandleNULLProc, //275 SPELL_AURA_MOD_IGNORE_SHAPESHIFT Use SpellClassMask for spell select &Unit::HandleNULLProc, //276 mod damage % mechanic? &Unit::HandleNULLProc, //277 SPELL_AURA_MOD_MAX_AFFECTED_TARGETS Use SpellClassMask for spell select &Unit::HandleNULLProc, //278 SPELL_AURA_MOD_DISARM_RANGED disarm ranged weapon &Unit::HandleNULLProc, //279 visual effects? 58836 and 57507 &Unit::HandleNULLProc, //280 SPELL_AURA_MOD_TARGET_ARMOR_PCT &Unit::HandleNULLProc, //281 SPELL_AURA_MOD_HONOR_GAIN &Unit::HandleNULLProc, //282 SPELL_AURA_INCREASE_BASE_HEALTH_PERCENT &Unit::HandleNULLProc, //283 SPELL_AURA_MOD_HEALING_RECEIVED &Unit::HandleNULLProc, //284 51 spells &Unit::HandleNULLProc, //285 SPELL_AURA_MOD_ATTACK_POWER_OF_ARMOR &Unit::HandleNULLProc, //286 SPELL_AURA_ABILITY_PERIODIC_CRIT &Unit::HandleNULLProc, //287 SPELL_AURA_DEFLECT_SPELLS &Unit::HandleNULLProc, //288 increase parry/deflect, prevent attack (single spell used 67801) &Unit::HandleNULLProc, //289 unused (3.2.2a) &Unit::HandleNULLProc, //290 SPELL_AURA_MOD_ALL_CRIT_CHANCE &Unit::HandleNULLProc, //291 SPELL_AURA_MOD_QUEST_XP_PCT &Unit::HandleNULLProc, //292 call stabled pet &Unit::HandleNULLProc, //293 3 spells &Unit::HandleNULLProc, //294 2 spells, possible prevent mana regen &Unit::HandleNULLProc, //295 unused (3.2.2a) &Unit::HandleNULLProc, //296 2 spells &Unit::HandleNULLProc, //297 1 spell (counter spell school?) &Unit::HandleNULLProc, //298 unused (3.2.2a) &Unit::HandleNULLProc, //299 unused (3.2.2a) &Unit::HandleNULLProc, //300 3 spells (share damage?) &Unit::HandleNULLProc, //301 5 spells &Unit::HandleNULLProc, //302 unused (3.2.2a) &Unit::HandleNULLProc, //303 17 spells &Unit::HandleNULLProc, //304 2 spells (alcohol effect?) &Unit::HandleNULLProc, //305 SPELL_AURA_MOD_MINIMUM_SPEED &Unit::HandleNULLProc, //306 1 spell &Unit::HandleNULLProc, //307 absorb healing? &Unit::HandleNULLProc, //308 new aura for hunter traps &Unit::HandleNULLProc, //309 absorb healing? &Unit::HandleNULLProc, //310 pet avoidance passive? &Unit::HandleNULLProc, //311 0 spells in 3.3 &Unit::HandleNULLProc, //312 0 spells in 3.3 &Unit::HandleNULLProc, //313 0 spells in 3.3 &Unit::HandleNULLProc, //314 1 test spell (reduce duration of silince/magic) &Unit::HandleNULLProc, //315 underwater walking &Unit::HandleNULLProc //316 makes haste affect HOT/DOT ticks }; bool Unit::IsTriggeredAtSpellProcEvent(Unit *pVictim, SpellAuraHolder* holder, SpellEntry const* procSpell, uint32 procFlag, uint32 procExtra, WeaponAttackType attType, bool isVictim, SpellProcEventEntry const*& spellProcEvent ) { SpellEntry const* spellProto = holder->GetSpellProto (); // Get proc Event Entry spellProcEvent = sSpellMgr.GetSpellProcEvent(spellProto->Id); // Get EventProcFlag uint32 EventProcFlag; if (spellProcEvent && spellProcEvent->procFlags) // if exist get custom spellProcEvent->procFlags EventProcFlag = spellProcEvent->procFlags; else EventProcFlag = spellProto->procFlags; // else get from spell proto // Continue if no trigger exist if (!EventProcFlag) return false; // Check spellProcEvent data requirements if(!SpellMgr::IsSpellProcEventCanTriggeredBy(spellProcEvent, EventProcFlag, procSpell, procFlag, procExtra)) return false; // In most cases req get honor or XP from kill if (EventProcFlag & PROC_FLAG_KILL && GetTypeId() == TYPEID_PLAYER) { bool allow = ((Player*)this)->isHonorOrXPTarget(pVictim); // Shadow Word: Death - can trigger from every kill if (holder->GetId() == 32409) allow = true; if (!allow) return false; } // Aura added by spell can`t trigger from self (prevent drop charges/do triggers) // But except periodic triggers (can triggered from self) if(procSpell && procSpell->Id == spellProto->Id && !(spellProto->procFlags & PROC_FLAG_ON_TAKE_PERIODIC)) return false; // Check if current equipment allows aura to proc if(!isVictim && GetTypeId() == TYPEID_PLAYER) { if(spellProto->EquippedItemClass == ITEM_CLASS_WEAPON) { Item *item = NULL; if(attType == BASE_ATTACK) item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND); else if (attType == OFF_ATTACK) item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND); else item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED); if(!item || item->IsBroken() || item->GetProto()->Class != ITEM_CLASS_WEAPON || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask)) return false; } else if(spellProto->EquippedItemClass == ITEM_CLASS_ARMOR) { // Check if player is wearing shield Item *item = ((Player*)this)->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND); if(!item || item->IsBroken() || !CanUseEquippedWeapon(OFF_ATTACK) || item->GetProto()->Class != ITEM_CLASS_ARMOR || !((1<<item->GetProto()->SubClass) & spellProto->EquippedItemSubClassMask)) return false; } } // Get chance from spell float chance = (float)spellProto->procChance; // If in spellProcEvent exist custom chance, chance = spellProcEvent->customChance; if(spellProcEvent && spellProcEvent->customChance) chance = spellProcEvent->customChance; // If PPM exist calculate chance from PPM if(!isVictim && spellProcEvent && spellProcEvent->ppmRate != 0) { uint32 WeaponSpeed = GetAttackTime(attType); chance = GetPPMProcChance(WeaponSpeed, spellProcEvent->ppmRate); } // Apply chance modifier aura if(Player* modOwner = GetSpellModOwner()) { modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_CHANCE_OF_SUCCESS,chance); modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_FREQUENCY_OF_SUCCESS,chance); } return roll_chance_f(chance); } SpellAuraProcResult Unit::HandleHasteAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const * /*procSpell*/, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 cooldown) { SpellEntry const *hasteSpell = triggeredByAura->GetSpellProto(); Item* castItem = !triggeredByAura->GetCastItemGuid().IsEmpty() && GetTypeId()==TYPEID_PLAYER ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGuid()) : NULL; uint32 triggered_spell_id = 0; Unit* target = pVictim; int32 basepoints0 = 0; switch(hasteSpell->SpellFamilyName) { case SPELLFAMILY_ROGUE: { switch(hasteSpell->Id) { // Blade Flurry case 13877: case 33735: { target = SelectRandomUnfriendlyTarget(pVictim); if(!target) return SPELL_AURA_PROC_FAILED; basepoints0 = damage; triggered_spell_id = 22482; break; } } break; } } // processed charge only counting case if(!triggered_spell_id) return SPELL_AURA_PROC_OK; SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id); if(!triggerEntry) { sLog.outError("Unit::HandleHasteAuraProc: Spell %u have nonexistent triggered spell %u",hasteSpell->Id,triggered_spell_id); return SPELL_AURA_PROC_FAILED; } // default case if (!target || (target != this && !target->isAlive())) return SPELL_AURA_PROC_FAILED; if (cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id)) return SPELL_AURA_PROC_FAILED; if (basepoints0) CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura); else CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura); if (cooldown && GetTypeId()==TYPEID_PLAYER) ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown); return SPELL_AURA_PROC_OK; } SpellAuraProcResult Unit::HandleSpellCritChanceAuraProc(Unit *pVictim, uint32 /*damage*/, Aura* triggeredByAura, SpellEntry const * procSpell, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 cooldown) { if (!procSpell) return SPELL_AURA_PROC_FAILED; SpellEntry const *triggeredByAuraSpell = triggeredByAura->GetSpellProto(); Item* castItem = !triggeredByAura->GetCastItemGuid().IsEmpty() && GetTypeId()==TYPEID_PLAYER ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGuid()) : NULL; uint32 triggered_spell_id = 0; Unit* target = pVictim; int32 basepoints0 = 0; switch(triggeredByAuraSpell->SpellFamilyName) { case SPELLFAMILY_MAGE: { switch(triggeredByAuraSpell->Id) { // Focus Magic case 54646: { Unit* caster = triggeredByAura->GetCaster(); if (!caster) return SPELL_AURA_PROC_FAILED; triggered_spell_id = 54648; target = caster; break; } } } } // processed charge only counting case if (!triggered_spell_id) return SPELL_AURA_PROC_OK; SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id); if(!triggerEntry) { sLog.outError("Unit::HandleHasteAuraProc: Spell %u have nonexistent triggered spell %u",triggeredByAuraSpell->Id,triggered_spell_id); return SPELL_AURA_PROC_FAILED; } // default case if (!target || (target != this && !target->isAlive())) return SPELL_AURA_PROC_FAILED; if (cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id)) return SPELL_AURA_PROC_FAILED; if (basepoints0) CastCustomSpell(target,triggered_spell_id,&basepoints0,NULL,NULL,true,castItem,triggeredByAura); else CastSpell(target,triggered_spell_id,true,castItem,triggeredByAura); if (cooldown && GetTypeId()==TYPEID_PLAYER) ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown); return SPELL_AURA_PROC_OK; } SpellAuraProcResult Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const * procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown) { SpellEntry const *dummySpell = triggeredByAura->GetSpellProto (); SpellEffectIndex effIndex = triggeredByAura->GetEffIndex(); int32 triggerAmount = triggeredByAura->GetModifier()->m_amount; Item* castItem = !triggeredByAura->GetCastItemGuid().IsEmpty() && GetTypeId()==TYPEID_PLAYER ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGuid()) : NULL; // some dummy spells have trigger spell in spell data already (from 3.0.3) uint32 triggered_spell_id = dummySpell->EffectApplyAuraName[effIndex] == SPELL_AURA_DUMMY ? dummySpell->EffectTriggerSpell[effIndex] : 0; Unit* target = pVictim; int32 basepoints[MAX_EFFECT_INDEX] = {0, 0, 0}; ObjectGuid originalCaster = ObjectGuid(); switch(dummySpell->SpellFamilyName) { case SPELLFAMILY_GENERIC: { switch (dummySpell->Id) { // Eye for an Eye case 9799: case 25988: { // return damage % to attacker but < 50% own total health basepoints[0] = triggerAmount*int32(damage)/100; if (basepoints[0] > (int32)GetMaxHealth()/2) basepoints[0] = (int32)GetMaxHealth()/2; triggered_spell_id = 25997; break; } // Sweeping Strikes (NPC spells may be) case 18765: case 35429: { // prevent chain of triggered spell from same triggered spell if (procSpell && procSpell->Id == 26654) return SPELL_AURA_PROC_FAILED; target = SelectRandomUnfriendlyTarget(pVictim); if(!target) return SPELL_AURA_PROC_FAILED; triggered_spell_id = 26654; break; } // Twisted Reflection (boss spell) case 21063: triggered_spell_id = 21064; break; // Unstable Power case 24658: { if (!procSpell || procSpell->Id == 24659) return SPELL_AURA_PROC_FAILED; // Need remove one 24659 aura RemoveAuraHolderFromStack(24659); return SPELL_AURA_PROC_OK; } // Restless Strength case 24661: { // Need remove one 24662 aura RemoveAuraHolderFromStack(24662); return SPELL_AURA_PROC_OK; } // Adaptive Warding (Frostfire Regalia set) case 28764: { if(!procSpell) return SPELL_AURA_PROC_FAILED; // find Mage Armor bool found = false; AuraList const& mRegenInterupt = GetAurasByType(SPELL_AURA_MOD_MANA_REGEN_INTERRUPT); for(AuraList::const_iterator iter = mRegenInterupt.begin(); iter != mRegenInterupt.end(); ++iter) { if(SpellEntry const* iterSpellProto = (*iter)->GetSpellProto()) { if(iterSpellProto->SpellFamilyName==SPELLFAMILY_MAGE && (iterSpellProto->SpellFamilyFlags & UI64LIT(0x10000000))) { found=true; break; } } } if(!found) return SPELL_AURA_PROC_FAILED; switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell))) { case SPELL_SCHOOL_NORMAL: case SPELL_SCHOOL_HOLY: return SPELL_AURA_PROC_FAILED; // ignored case SPELL_SCHOOL_FIRE: triggered_spell_id = 28765; break; case SPELL_SCHOOL_NATURE: triggered_spell_id = 28768; break; case SPELL_SCHOOL_FROST: triggered_spell_id = 28766; break; case SPELL_SCHOOL_SHADOW: triggered_spell_id = 28769; break; case SPELL_SCHOOL_ARCANE: triggered_spell_id = 28770; break; default: return SPELL_AURA_PROC_FAILED; } target = this; break; } // Obsidian Armor (Justice Bearer`s Pauldrons shoulder) case 27539: { if(!procSpell) return SPELL_AURA_PROC_FAILED; switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell))) { case SPELL_SCHOOL_NORMAL: return SPELL_AURA_PROC_FAILED; // ignore case SPELL_SCHOOL_HOLY: triggered_spell_id = 27536; break; case SPELL_SCHOOL_FIRE: triggered_spell_id = 27533; break; case SPELL_SCHOOL_NATURE: triggered_spell_id = 27538; break; case SPELL_SCHOOL_FROST: triggered_spell_id = 27534; break; case SPELL_SCHOOL_SHADOW: triggered_spell_id = 27535; break; case SPELL_SCHOOL_ARCANE: triggered_spell_id = 27540; break; default: return SPELL_AURA_PROC_FAILED; } target = this; break; } // Mana Leech (Passive) (Priest Pet Aura) case 28305: { // Cast on owner target = GetOwner(); if(!target) return SPELL_AURA_PROC_FAILED; triggered_spell_id = 34650; break; } // Divine purpose case 31871: case 31872: { // Roll chance if (!roll_chance_i(triggerAmount)) return SPELL_AURA_PROC_FAILED; // Remove any stun effect on target SpellAuraHolderMap& Auras = pVictim->GetSpellAuraHolderMap(); for(SpellAuraHolderMap::const_iterator iter = Auras.begin(); iter != Auras.end();) { SpellEntry const *spell = iter->second->GetSpellProto(); if( spell->Mechanic == MECHANIC_STUN || iter->second->HasMechanic(MECHANIC_STUN)) { pVictim->RemoveAurasDueToSpell(spell->Id); iter = Auras.begin(); } else ++iter; } return SPELL_AURA_PROC_OK; } // Mark of Malice case 33493: { // Cast finish spell at last charge if (triggeredByAura->GetHolder()->GetAuraCharges() > 1) return SPELL_AURA_PROC_FAILED; target = this; triggered_spell_id = 33494; break; } // Vampiric Aura (boss spell) case 38196: { basepoints[0] = 3 * damage; // 300% if (basepoints[0] < 0) return SPELL_AURA_PROC_FAILED; triggered_spell_id = 31285; target = this; break; } // Aura of Madness (Darkmoon Card: Madness trinket) //===================================================== // 39511 Sociopath: +35 strength (Paladin, Rogue, Druid, Warrior) // 40997 Delusional: +70 attack power (Rogue, Hunter, Paladin, Warrior, Druid) // 40998 Kleptomania: +35 agility (Warrior, Rogue, Paladin, Hunter, Druid) // 40999 Megalomania: +41 damage/healing (Druid, Shaman, Priest, Warlock, Mage, Paladin) // 41002 Paranoia: +35 spell/melee/ranged crit strike rating (All classes) // 41005 Manic: +35 haste (spell, melee and ranged) (All classes) // 41009 Narcissism: +35 intellect (Druid, Shaman, Priest, Warlock, Mage, Paladin, Hunter) // 41011 Martyr Complex: +35 stamina (All classes) // 41406 Dementia: Every 5 seconds either gives you +5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin) // 41409 Dementia: Every 5 seconds either gives you -5% damage/healing. (Druid, Shaman, Priest, Warlock, Mage, Paladin) case 39446: { if(GetTypeId() != TYPEID_PLAYER) return SPELL_AURA_PROC_FAILED; // Select class defined buff switch (getClass()) { case CLASS_PALADIN: // 39511,40997,40998,40999,41002,41005,41009,41011,41409 case CLASS_DRUID: // 39511,40997,40998,40999,41002,41005,41009,41011,41409 { uint32 RandomSpell[]={39511,40997,40998,40999,41002,41005,41009,41011,41409}; triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ]; break; } case CLASS_ROGUE: // 39511,40997,40998,41002,41005,41011 case CLASS_WARRIOR: // 39511,40997,40998,41002,41005,41011 { uint32 RandomSpell[]={39511,40997,40998,41002,41005,41011}; triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ]; break; } case CLASS_PRIEST: // 40999,41002,41005,41009,41011,41406,41409 case CLASS_SHAMAN: // 40999,41002,41005,41009,41011,41406,41409 case CLASS_MAGE: // 40999,41002,41005,41009,41011,41406,41409 case CLASS_WARLOCK: // 40999,41002,41005,41009,41011,41406,41409 { uint32 RandomSpell[]={40999,41002,41005,41009,41011,41406,41409}; triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ]; break; } case CLASS_HUNTER: // 40997,40999,41002,41005,41009,41011,41406,41409 { uint32 RandomSpell[]={40997,40999,41002,41005,41009,41011,41406,41409}; triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ]; break; } default: return SPELL_AURA_PROC_FAILED; } target = this; if (roll_chance_i(10)) ((Player*)this)->Say("This is Madness!", LANG_UNIVERSAL); break; } // Sunwell Exalted Caster Neck (Shattered Sun Pendant of Acumen neck) // cast 45479 Light's Wrath if Exalted by Aldor // cast 45429 Arcane Bolt if Exalted by Scryers case 45481: { if(GetTypeId() != TYPEID_PLAYER) return SPELL_AURA_PROC_FAILED; // Get Aldor reputation rank if (((Player *)this)->GetReputationRank(932) == REP_EXALTED) { target = this; triggered_spell_id = 45479; break; } // Get Scryers reputation rank if (((Player *)this)->GetReputationRank(934) == REP_EXALTED) { // triggered at positive/self casts also, current attack target used then if(IsFriendlyTo(target)) { target = getVictim(); if(!target) { target = ObjectAccessor::GetUnit(*this,((Player *)this)->GetSelectionGuid()); if(!target) return SPELL_AURA_PROC_FAILED; } if(IsFriendlyTo(target)) return SPELL_AURA_PROC_FAILED; } triggered_spell_id = 45429; break; } return SPELL_AURA_PROC_FAILED; } // Sunwell Exalted Melee Neck (Shattered Sun Pendant of Might neck) // cast 45480 Light's Strength if Exalted by Aldor // cast 45428 Arcane Strike if Exalted by Scryers case 45482: { if(GetTypeId() != TYPEID_PLAYER) return SPELL_AURA_PROC_FAILED; // Get Aldor reputation rank if (((Player *)this)->GetReputationRank(932) == REP_EXALTED) { target = this; triggered_spell_id = 45480; break; } // Get Scryers reputation rank if (((Player *)this)->GetReputationRank(934) == REP_EXALTED) { triggered_spell_id = 45428; break; } return SPELL_AURA_PROC_FAILED; } // Sunwell Exalted Tank Neck (Shattered Sun Pendant of Resolve neck) // cast 45431 Arcane Insight if Exalted by Aldor // cast 45432 Light's Ward if Exalted by Scryers case 45483: { if(GetTypeId() != TYPEID_PLAYER) return SPELL_AURA_PROC_FAILED; // Get Aldor reputation rank if (((Player *)this)->GetReputationRank(932) == REP_EXALTED) { target = this; triggered_spell_id = 45432; break; } // Get Scryers reputation rank if (((Player *)this)->GetReputationRank(934) == REP_EXALTED) { target = this; triggered_spell_id = 45431; break; } return SPELL_AURA_PROC_FAILED; } // Sunwell Exalted Healer Neck (Shattered Sun Pendant of Restoration neck) // cast 45478 Light's Salvation if Exalted by Aldor // cast 45430 Arcane Surge if Exalted by Scryers case 45484: { if(GetTypeId() != TYPEID_PLAYER) return SPELL_AURA_PROC_FAILED; // Get Aldor reputation rank if (((Player *)this)->GetReputationRank(932) == REP_EXALTED) { target = this; triggered_spell_id = 45478; break; } // Get Scryers reputation rank if (((Player *)this)->GetReputationRank(934) == REP_EXALTED) { triggered_spell_id = 45430; break; } return SPELL_AURA_PROC_FAILED; } /* // Sunwell Exalted Caster Neck (??? neck) // cast ??? Light's Wrath if Exalted by Aldor // cast ??? Arcane Bolt if Exalted by Scryers*/ case 46569: return SPELL_AURA_PROC_FAILED; // old unused version // Living Seed case 48504: { triggered_spell_id = 48503; basepoints[0] = triggerAmount; target = this; break; } // Health Leech (used by Bloodworms) case 50453: { Unit *owner = GetOwner(); if (!owner) return SPELL_AURA_PROC_FAILED; triggered_spell_id = 50454; basepoints[0] = int32(damage*1.69); target = owner; break; } // Vampiric Touch (generic, used by some boss) case 52723: case 60501: { triggered_spell_id = 52724; basepoints[0] = damage / 2; target = this; break; } // Shadowfiend Death (Gain mana if pet dies with Glyph of Shadowfiend) case 57989: { Unit *owner = GetOwner(); if (!owner || owner->GetTypeId() != TYPEID_PLAYER) return SPELL_AURA_PROC_FAILED; // Glyph of Shadowfiend (need cast as self cast for owner, no hidden cooldown) owner->CastSpell(owner,58227,true,castItem,triggeredByAura); return SPELL_AURA_PROC_OK; } // Kill Command, pet aura case 58914: { // also decrease owner buff stack if (Unit* owner = GetOwner()) owner->RemoveAuraHolderFromStack(34027); // Remove only single aura from stack if (triggeredByAura->GetStackAmount() > 1 && !triggeredByAura->GetHolder()->ModStackAmount(-1)) return SPELL_AURA_PROC_CANT_TRIGGER; } // Glyph of Life Tap case 63320: triggered_spell_id = 63321; break; // Shiny Shard of the Scale - Equip Effect case 69739: // Cauterizing Heal or Searing Flame triggered_spell_id = (procFlag & PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL) ? 69734 : 69730; break; // Purified Shard of the Scale - Equip Effect case 69755: // Cauterizing Heal or Searing Flame triggered_spell_id = (procFlag & PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL) ? 69733 : 69729; break; case 70871: // Soul of Blood qween triggered_spell_id = 70872; basepoints[0] = int32(triggerAmount* damage /100); if (basepoints[0] < 0) return SPELL_AURA_PROC_FAILED; break; // Glyph of Shadowflame case 63310: { triggered_spell_id = 63311; break; } // Item - Shadowmourne Legendary case 71903: { if (!roll_chance_i(triggerAmount)) return SPELL_AURA_PROC_FAILED; triggered_spell_id = 71905; // Soul Fragment SpellAuraHolder *aurHolder = GetSpellAuraHolder(triggered_spell_id); // will added first to stack if (!aurHolder) CastSpell(this, 72521, true); // Shadowmourne Visual Low // half stack else if (aurHolder->GetStackAmount() + 1 == 6) CastSpell(this, 72523, true); // Shadowmourne Visual High // full stack else if (aurHolder->GetStackAmount() + 1 >= aurHolder->GetSpellProto()->StackAmount) { RemoveAurasDueToSpell(triggered_spell_id); CastSpell(this, 71904, true); // Chaos Bane return SPELL_AURA_PROC_OK; } break; } // Deathbringer's Will (Item - Icecrown 25 Normal Melee Trinket) //===================================================== // 71492 Speed of the Vrykul: +600 haste rating (Death Knight, Druid, Paladin, Rogue, Warrior, Shaman) // 71485 Agility of the Vrykul: +600 agility (Druid, Hunter, Rogue, Shaman) // 71486 Power of the Taunka: +1200 attack power (Hunter, Rogue, Shaman) // 71484 Strength of the Taunka: +600 strength (Death Knight, Druid, Paladin, Warrior) // 71491 Aim of the Iron Dwarves: +600 critical strike rating (Death Knight, Hunter, Paladin, Warrior) case 71519: { if(GetTypeId() != TYPEID_PLAYER) return SPELL_AURA_PROC_FAILED; if(HasAura(71491) || HasAura(71484) || HasAura(71492) || HasAura(71486) || HasAura(71485)) return SPELL_AURA_PROC_FAILED; // Select class defined buff switch (getClass()) { case CLASS_PALADIN: { uint32 RandomSpell[]={71492,71484,71491}; triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ]; break; } case CLASS_DRUID: { uint32 RandomSpell[]={71492,71485,71484}; triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ]; break; } case CLASS_ROGUE: { uint32 RandomSpell[]={71492,71485,71486}; triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ]; break; } case CLASS_WARRIOR: { uint32 RandomSpell[]={71492,71484,71491}; triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ]; break; } case CLASS_SHAMAN: { uint32 RandomSpell[]={71485,71486,71492}; triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ]; break; } case CLASS_HUNTER: { uint32 RandomSpell[]={71485,71486,71491}; triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ]; break; } case CLASS_DEATH_KNIGHT: { uint32 RandomSpell[]={71484,71492,71491}; triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ]; break; } default: return SPELL_AURA_PROC_FAILED; } break; } // Deathbringer's Will (Item - Icecrown 25 Heroic Melee Trinket) //===================================================== // 71560 Speed of the Vrykul: +700 haste rating (Death Knight, Druid, Paladin, Rogue, Warrior, Shaman) // 71556 Agility of the Vrykul: +700 agility (Druid, Hunter, Rogue, Shaman) // 71558 Power of the Taunka: +1400 attack power (Hunter, Rogue, Shaman) // 71561 Strength of the Taunka: +700 strength (Death Knight, Druid, Paladin, Warrior) // 71559 Aim of the Iron Dwarves: +700 critical strike rating (Death Knight, Hunter, Paladin, Warrior) case 71562: { if(GetTypeId() != TYPEID_PLAYER) return SPELL_AURA_PROC_FAILED; if(HasAura(71559) || HasAura(71561) || HasAura(71560) || HasAura(71556) || HasAura(71558)) return SPELL_AURA_PROC_FAILED; // Select class defined buff switch (getClass()) { case CLASS_PALADIN: { uint32 RandomSpell[]={71560,71561,71559}; triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ]; break; } case CLASS_DRUID: { uint32 RandomSpell[]={71560,71556,71561}; triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ]; break; } case CLASS_ROGUE: { uint32 RandomSpell[]={71560,71556,71558,}; triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ]; break; } case CLASS_WARRIOR: { uint32 RandomSpell[]={71560,71561,71559,}; triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ]; break; } case CLASS_SHAMAN: { uint32 RandomSpell[]={71556,71558,71560}; triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ]; break; } case CLASS_HUNTER: { uint32 RandomSpell[]={71556,71558,71559}; triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ]; break; } case CLASS_DEATH_KNIGHT: { uint32 RandomSpell[]={71561,71560,71559}; triggered_spell_id = RandomSpell[ irand(0, sizeof(RandomSpell)/sizeof(uint32) - 1) ]; break; } default: return SPELL_AURA_PROC_FAILED; } break; } // Necrotic Touch item 50692 case 71875: case 71877: { basepoints[0] = damage * triggerAmount / 100; target = pVictim; triggered_spell_id = 71879; break; } } break; } case SPELLFAMILY_MAGE: { // Magic Absorption if (dummySpell->SpellIconID == 459) // only this spell have SpellIconID == 459 and dummy aura { if (getPowerType() != POWER_MANA) return SPELL_AURA_PROC_FAILED; // mana reward basepoints[0] = (triggerAmount * GetMaxPower(POWER_MANA) / 100); target = this; triggered_spell_id = 29442; break; } // Master of Elements if (dummySpell->SpellIconID == 1920) { if(!procSpell) return SPELL_AURA_PROC_FAILED; // mana cost save int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100; basepoints[0] = cost * triggerAmount/100; if (basepoints[0] <=0) return SPELL_AURA_PROC_FAILED; target = this; triggered_spell_id = 29077; break; } // Arcane Potency if (dummySpell->SpellIconID == 2120) { if(!procSpell || procSpell->Id == 44401) return SPELL_AURA_PROC_FAILED; target = this; switch (dummySpell->Id) { case 31571: triggered_spell_id = 57529; break; case 31572: triggered_spell_id = 57531; break; default: sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u",dummySpell->Id); return SPELL_AURA_PROC_FAILED; } break; } // Hot Streak if (dummySpell->SpellIconID == 2999) { if (effIndex != EFFECT_INDEX_0) return SPELL_AURA_PROC_OK; Aura *counter = GetAura(triggeredByAura->GetId(), EFFECT_INDEX_1); if (!counter) return SPELL_AURA_PROC_OK; // Count spell criticals in a row in second aura Modifier *mod = counter->GetModifier(); if (procEx & PROC_EX_CRITICAL_HIT) { mod->m_amount *=2; if (mod->m_amount < 100) // not enough return SPELL_AURA_PROC_OK; // Critical counted -> roll chance if (roll_chance_i(triggerAmount)) CastSpell(this, 48108, true, castItem, triggeredByAura); } mod->m_amount = 25; return SPELL_AURA_PROC_OK; } // Burnout if (dummySpell->SpellIconID == 2998) { if(!procSpell) return SPELL_AURA_PROC_FAILED; int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100; basepoints[0] = cost * triggerAmount/100; if (basepoints[0] <=0) return SPELL_AURA_PROC_FAILED; triggered_spell_id = 44450; target = this; break; } // Incanter's Regalia set (add trigger chance to Mana Shield) if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000000000008000)) { if (GetTypeId() != TYPEID_PLAYER) return SPELL_AURA_PROC_FAILED; target = this; triggered_spell_id = 37436; break; } switch(dummySpell->Id) { // Ignite case 11119: case 11120: case 12846: case 12847: case 12848: { switch (dummySpell->Id) { case 11119: basepoints[0] = int32(0.04f*damage); break; case 11120: basepoints[0] = int32(0.08f*damage); break; case 12846: basepoints[0] = int32(0.12f*damage); break; case 12847: basepoints[0] = int32(0.16f*damage); break; case 12848: basepoints[0] = int32(0.20f*damage); break; default: sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (IG)",dummySpell->Id); return SPELL_AURA_PROC_FAILED; } triggered_spell_id = 12654; break; } // Empowered Fire (mana regen) case 12654: { Unit* caster = triggeredByAura->GetCaster(); // it should not be triggered from other ignites if (caster && pVictim && caster->GetGUID() == pVictim->GetGUID()) { Unit::AuraList const& auras = caster->GetAurasByType(SPELL_AURA_ADD_FLAT_MODIFIER); for (Unit::AuraList::const_iterator i = auras.begin(); i != auras.end(); i++) { switch((*i)->GetId()) { case 31656: case 31657: case 31658: { if(roll_chance_i(int32((*i)->GetSpellProto()->procChance))) { caster->CastSpell(caster, 67545, true); return SPELL_AURA_PROC_OK; } else return SPELL_AURA_PROC_FAILED; } } } } return SPELL_AURA_PROC_FAILED; } // Arcane Blast proc-off only from arcane school and not from self case 36032: { if(procSpell->EffectTriggerSpell[1] == 36032 || GetSpellSchoolMask(procSpell) != SPELL_SCHOOL_MASK_ARCANE) return SPELL_AURA_PROC_FAILED; } // Glyph of Ice Block case 56372: { if (GetTypeId() != TYPEID_PLAYER) return SPELL_AURA_PROC_FAILED; // not 100% safe with client version switches but for 3.1.3 no spells with cooldown that can have mage player except Frost Nova. ((Player*)this)->RemoveSpellCategoryCooldown(35, true); return SPELL_AURA_PROC_OK; } // Glyph of Icy Veins case 56374: { Unit::AuraList const& hasteAuras = GetAurasByType(SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK); for(Unit::AuraList::const_iterator i = hasteAuras.begin(); i != hasteAuras.end();) { if (!IsPositiveSpell((*i)->GetId())) { RemoveAurasDueToSpell((*i)->GetId()); i = hasteAuras.begin(); } else ++i; } RemoveSpellsCausingAura(SPELL_AURA_HASTE_SPELLS); RemoveSpellsCausingAura(SPELL_AURA_MOD_DECREASE_SPEED); return SPELL_AURA_PROC_OK; } // Glyph of Polymorph case 56375: { if (!pVictim || !pVictim->isAlive()) return SPELL_AURA_PROC_FAILED; pVictim->RemoveSpellsCausingAura(SPELL_AURA_PERIODIC_DAMAGE); pVictim->RemoveSpellsCausingAura(SPELL_AURA_PERIODIC_DAMAGE_PERCENT); pVictim->RemoveSpellsCausingAura(SPELL_AURA_PERIODIC_LEECH); return SPELL_AURA_PROC_OK; } // Blessing of Ancient Kings case 64411: { // for DOT procs if (!IsPositiveSpell(procSpell->Id)) return SPELL_AURA_PROC_FAILED; triggered_spell_id = 64413; basepoints[0] = damage * 15 / 100; break; } } break; } case SPELLFAMILY_WARRIOR: { // Retaliation if (dummySpell->SpellFamilyFlags == UI64LIT(0x0000000800000000)) { // check attack comes not from behind if (!HasInArc(M_PI_F, pVictim)) return SPELL_AURA_PROC_FAILED; triggered_spell_id = 22858; break; } // Second Wind if (dummySpell->SpellIconID == 1697) { // only for spells and hit/crit (trigger start always) and not start from self casted spells (5530 Mace Stun Effect for example) if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim) return SPELL_AURA_PROC_FAILED; // Need stun or root mechanic if (!(GetAllSpellMechanicMask(procSpell) & IMMUNE_TO_ROOT_AND_STUN_MASK)) return SPELL_AURA_PROC_FAILED; switch (dummySpell->Id) { case 29838: triggered_spell_id=29842; break; case 29834: triggered_spell_id=29841; break; case 42770: triggered_spell_id=42771; break; default: sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (SW)",dummySpell->Id); return SPELL_AURA_PROC_FAILED; } target = this; break; } // Damage Shield if (dummySpell->SpellIconID == 3214) { triggered_spell_id = 59653; basepoints[0] = GetShieldBlockValue() * triggerAmount / 100; break; } // Sweeping Strikes if (dummySpell->Id == 12328) { // prevent chain of triggered spell from same triggered spell if(procSpell && procSpell->Id == 26654) return SPELL_AURA_PROC_FAILED; target = SelectRandomUnfriendlyTarget(pVictim); if(!target) return SPELL_AURA_PROC_FAILED; triggered_spell_id = 26654; break; } // Glyph of Sunder Armor if (dummySpell->Id == 58387) { if (!procSpell) return SPELL_AURA_PROC_FAILED; target = SelectRandomUnfriendlyTarget(pVictim); if (!target) return SPELL_AURA_PROC_FAILED; triggered_spell_id = 58567; break; } break; } case SPELLFAMILY_WARLOCK: { // Seed of Corruption if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000001000000000)) { Modifier* mod = triggeredByAura->GetModifier(); // if damage is more than need or target die from damage deal finish spell if( mod->m_amount <= (int32)damage || GetHealth() <= damage ) { // remember guid before aura delete ObjectGuid casterGuid = triggeredByAura->GetCasterGuid(); // Remove aura (before cast for prevent infinite loop handlers) RemoveAurasDueToSpell(triggeredByAura->GetId()); // Cast finish spell (triggeredByAura already not exist!) CastSpell(this, 27285, true, castItem, NULL, casterGuid); return SPELL_AURA_PROC_OK; // no hidden cooldown } // Damage counting mod->m_amount-=damage; return SPELL_AURA_PROC_OK; } // Seed of Corruption (Mobs cast) - no die req if (dummySpell->SpellFamilyFlags == UI64LIT(0x0) && dummySpell->SpellIconID == 1932) { Modifier* mod = triggeredByAura->GetModifier(); // if damage is more than need deal finish spell if( mod->m_amount <= (int32)damage ) { // remember guid before aura delete ObjectGuid casterGuid = triggeredByAura->GetCasterGuid(); // Remove aura (before cast for prevent infinite loop handlers) RemoveAurasDueToSpell(triggeredByAura->GetId()); // Cast finish spell (triggeredByAura already not exist!) CastSpell(this, 32865, true, castItem, NULL, casterGuid); return SPELL_AURA_PROC_OK; // no hidden cooldown } // Damage counting mod->m_amount-=damage; return SPELL_AURA_PROC_OK; } // Fel Synergy if (dummySpell->SpellIconID == 3222) { target = GetPet(); if (!target) return SPELL_AURA_PROC_FAILED; basepoints[0] = damage * triggerAmount / 100; triggered_spell_id = 54181; break; } switch(dummySpell->Id) { // Nightfall & Glyph of Corruption case 18094: case 18095: case 56218: { target = this; triggered_spell_id = 17941; break; } //Soul Leech case 30293: case 30295: case 30296: { // health basepoints[0] = int32(damage*triggerAmount/100); target = this; triggered_spell_id = 30294; // check for Improved Soul Leech AuraList const& pDummyAuras = GetAurasByType(SPELL_AURA_DUMMY); for (AuraList::const_iterator itr = pDummyAuras.begin(); itr != pDummyAuras.end(); ++itr) { SpellEntry const* spellInfo = (*itr)->GetSpellProto(); if (spellInfo->SpellFamilyName != SPELLFAMILY_WARLOCK || (*itr)->GetSpellProto()->SpellIconID != 3176) continue; if ((*itr)->GetEffIndex() == SpellEffectIndex(0)) { // energize Proc pet (implicit target is pet) CastCustomSpell(this, 59118, &((*itr)->GetModifier()->m_amount), NULL, NULL, true, NULL, (*itr)); // energize Proc master CastCustomSpell(this, 59117, &((*itr)->GetModifier()->m_amount), NULL, NULL, true, NULL, (*itr)); } else if (roll_chance_i((*itr)->GetModifier()->m_amount)) { // Replenishment proc CastSpell(this, 57669, true, NULL, (*itr)); } } break; } // Shadowflame (Voidheart Raiment set bonus) case 37377: { triggered_spell_id = 37379; break; } // Pet Healing (Corruptor Raiment or Rift Stalker Armor) case 37381: { target = GetPet(); if (!target) return SPELL_AURA_PROC_FAILED; // heal amount basepoints[0] = damage * triggerAmount/100; triggered_spell_id = 37382; break; } // Shadowflame Hellfire (Voidheart Raiment set bonus) case 39437: { triggered_spell_id = 37378; break; } // Siphon Life case 63108: { // Glyph of Siphon Life if (Aura *aur = GetAura(56216, EFFECT_INDEX_0)) triggerAmount += triggerAmount * aur->GetModifier()->m_amount / 100; basepoints[0] = int32(damage * triggerAmount / 100); triggered_spell_id = 63106; break; } } break; } case SPELLFAMILY_PRIEST: { // Vampiric Touch if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000040000000000)) { if (!pVictim || !pVictim->isAlive()) return SPELL_AURA_PROC_FAILED; // pVictim is caster of aura if (triggeredByAura->GetCasterGuid() != pVictim->GetObjectGuid()) return SPELL_AURA_PROC_FAILED; // Energize 0.25% of max. mana pVictim->CastSpell(pVictim, 57669, true, castItem, triggeredByAura); return SPELL_AURA_PROC_OK; // no hidden cooldown } switch(dummySpell->SpellIconID) { // Improved Shadowform case 217: { if(!roll_chance_i(triggerAmount)) return SPELL_AURA_PROC_FAILED; RemoveSpellsCausingAura(SPELL_AURA_MOD_ROOT); RemoveSpellsCausingAura(SPELL_AURA_MOD_DECREASE_SPEED); break; } // Divine Aegis case 2820: { if(!pVictim || !pVictim->isAlive()) return SPELL_AURA_PROC_FAILED; // find Divine Aegis on the target and get absorb amount Aura* DivineAegis = pVictim->GetAura(47753,EFFECT_INDEX_0); if (DivineAegis) basepoints[0] = DivineAegis->GetModifier()->m_amount; basepoints[0] += damage * triggerAmount/100; // limit absorb amount int32 levelbonus = pVictim->getLevel()*125; if (basepoints[0] > levelbonus) basepoints[0] = levelbonus; triggered_spell_id = 47753; break; } // Empowered Renew case 3021: { if (!procSpell) return SPELL_AURA_PROC_FAILED; // Renew Aura* healingAura = pVictim->GetAura(SPELL_AURA_PERIODIC_HEAL, SPELLFAMILY_PRIEST, UI64LIT(0x40), 0, GetGUID()); if (!healingAura) return SPELL_AURA_PROC_FAILED; int32 healingfromticks = healingAura->GetModifier()->m_amount * GetSpellAuraMaxTicks(procSpell); basepoints[0] = healingfromticks * triggerAmount / 100; triggered_spell_id = 63544; break; } // Improved Devouring Plague case 3790: { if (!procSpell) return SPELL_AURA_PROC_FAILED; Aura* leachAura = pVictim->GetAura(SPELL_AURA_PERIODIC_LEECH, SPELLFAMILY_PRIEST, UI64LIT(0x02000000), 0, GetGUID()); if (!leachAura) return SPELL_AURA_PROC_FAILED; int32 damagefromticks = leachAura->GetModifier()->m_amount * GetSpellAuraMaxTicks(procSpell); basepoints[0] = damagefromticks * triggerAmount / 100; triggered_spell_id = 63675; break; } } switch(dummySpell->Id) { // Vampiric Embrace case 15286: { // Return if self damage if (this == pVictim) return SPELL_AURA_PROC_FAILED; // Heal amount - Self/Team int32 team = triggerAmount*damage/500; int32 self = triggerAmount*damage/100 - team; CastCustomSpell(this,15290,&team,&self,NULL,true,castItem,triggeredByAura); return SPELL_AURA_PROC_OK; // no hidden cooldown } // Priest Tier 6 Trinket (Ashtongue Talisman of Acumen) case 40438: { // Shadow Word: Pain if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000008000)) triggered_spell_id = 40441; // Renew else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000010)) triggered_spell_id = 40440; else return SPELL_AURA_PROC_FAILED; target = this; break; } // Oracle Healing Bonus ("Garments of the Oracle" set) case 26169: { // heal amount basepoints[0] = int32(damage * 10/100); target = this; triggered_spell_id = 26170; break; } // Frozen Shadoweave (Shadow's Embrace set) warning! its not only priest set case 39372: { if(!procSpell || (GetSpellSchoolMask(procSpell) & (SPELL_SCHOOL_MASK_FROST | SPELL_SCHOOL_MASK_SHADOW))==0 ) return SPELL_AURA_PROC_FAILED; // heal amount basepoints[0] = damage * triggerAmount/100; target = this; triggered_spell_id = 39373; break; } // Greater Heal (Vestments of Faith (Priest Tier 3) - 4 pieces bonus) case 28809: { triggered_spell_id = 28810; break; } // Glyph of Dispel Magic case 55677: { if(!target->IsFriendlyTo(this)) return SPELL_AURA_PROC_FAILED; if (target->GetTypeId() == TYPEID_PLAYER) basepoints[0] = int32(target->GetMaxHealth() * triggerAmount / 100); else if (Unit* caster = triggeredByAura->GetCaster()) basepoints[0] = int32(caster->GetMaxHealth() * triggerAmount / 100); // triggered_spell_id in spell data break; } // Item - Priest T10 Healer 4P Bonus case 70799: { if (GetTypeId() != TYPEID_PLAYER) return SPELL_AURA_PROC_FAILED; // Circle of Healing ((Player*)this)->RemoveSpellCategoryCooldown(1204, true); // Penance ((Player*)this)->RemoveSpellCategoryCooldown(1230, true); return SPELL_AURA_PROC_OK; } // Glyph of Prayer of Healing case 55680: { basepoints[0] = int32(damage * triggerAmount / 200); // 10% each tick triggered_spell_id = 56161; break; } } break; } case SPELLFAMILY_DRUID: { switch(dummySpell->Id) { // Leader of the Pack case 24932: { // dummy m_amount store health percent (!=0 if Improved Leader of the Pack applied) int32 heal_percent = triggeredByAura->GetModifier()->m_amount; if (!heal_percent) return SPELL_AURA_PROC_FAILED; // check explicitly only to prevent mana cast when halth cast cooldown if (cooldown && ((Player*)this)->HasSpellCooldown(34299)) return SPELL_AURA_PROC_FAILED; // health triggered_spell_id = 34299; basepoints[0] = GetMaxHealth() * heal_percent / 100; target = this; // mana to caster if (triggeredByAura->GetCasterGuid() == GetObjectGuid()) { if (SpellEntry const* manaCastEntry = sSpellStore.LookupEntry(60889)) { int32 mana_percent = manaCastEntry->CalculateSimpleValue(EFFECT_INDEX_0) * heal_percent; CastCustomSpell(this, manaCastEntry, &mana_percent, NULL, NULL, true, castItem, triggeredByAura); } } break; } // Healing Touch (Dreamwalker Raiment set) case 28719: { // mana back basepoints[0] = int32(procSpell->manaCost * 30 / 100); target = this; triggered_spell_id = 28742; break; } // Healing Touch Refund (Idol of Longevity trinket) case 28847: { target = this; triggered_spell_id = 28848; break; } // Mana Restore (Malorne Raiment set / Malorne Regalia set) case 37288: case 37295: { target = this; triggered_spell_id = 37238; break; } // Druid Tier 6 Trinket case 40442: { float chance; // Starfire if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000004)) { triggered_spell_id = 40445; chance = 25.0f; } // Rejuvenation else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000010)) { triggered_spell_id = 40446; chance = 25.0f; } // Mangle (Bear) and Mangle (Cat) else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000044000000000)) { triggered_spell_id = 40452; chance = 40.0f; } else return SPELL_AURA_PROC_FAILED; if (!roll_chance_f(chance)) return SPELL_AURA_PROC_FAILED; target = this; break; } // Maim Interrupt case 44835: { // Deadly Interrupt Effect triggered_spell_id = 32747; break; } // Glyph of Starfire case 54845: { triggered_spell_id = 54846; break; } // Glyph of Shred case 54815: { triggered_spell_id = 63974; break; } // Glyph of Rejuvenation case 54754: { // less 50% health if (pVictim->GetMaxHealth() < 2 * pVictim->GetHealth()) return SPELL_AURA_PROC_FAILED; basepoints[0] = triggerAmount * damage / 100; triggered_spell_id = 54755; break; } // Glyph of Rake case 54821: { triggered_spell_id = 54820; break; } // Item - Druid T10 Restoration 4P Bonus (Rejuvenation) case 70664: { if (!procSpell || GetTypeId() != TYPEID_PLAYER) return SPELL_AURA_PROC_FAILED; float radius; if (procSpell->EffectRadiusIndex[EFFECT_INDEX_0]) radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(procSpell->EffectRadiusIndex[EFFECT_INDEX_0])); else radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(procSpell->rangeIndex)); ((Player*)this)->ApplySpellMod(procSpell->Id, SPELLMOD_RADIUS, radius,NULL); Unit *second = pVictim->SelectRandomFriendlyTarget(pVictim, radius); if (!second) return SPELL_AURA_PROC_FAILED; pVictim->CastSpell(second, procSpell, true, NULL, triggeredByAura, GetGUID()); return SPELL_AURA_PROC_OK; } // Item - Druid T10 Balance 4P Bonus case 70723: { basepoints[0] = int32( triggerAmount * damage / 100 ); basepoints[0] = int32( basepoints[0] / 2); triggered_spell_id = 71023; break; } } // King of the Jungle if (dummySpell->SpellIconID == 2850) { switch (effIndex) { case EFFECT_INDEX_0: // Enrage (bear) { // note : aura removal is done in SpellAuraHolder::HandleSpellSpecificBoosts basepoints[0] = triggerAmount; triggered_spell_id = 51185; break; } case EFFECT_INDEX_1: // Tiger's Fury (cat) { basepoints[0] = triggerAmount; triggered_spell_id = 51178; break; } default: return SPELL_AURA_PROC_FAILED; } } // Eclipse else if (dummySpell->SpellIconID == 2856) { if (!procSpell) return SPELL_AURA_PROC_FAILED; // Wrath crit if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000001)) { if (HasAura(48517)) return SPELL_AURA_PROC_FAILED; if (!roll_chance_i(60)) return SPELL_AURA_PROC_FAILED; triggered_spell_id = 48518; target = this; break; } // Starfire crit if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000004)) { if (HasAura(48518)) return SPELL_AURA_PROC_FAILED; triggered_spell_id = 48517; target = this; break; } return SPELL_AURA_PROC_FAILED; } // Living Seed else if (dummySpell->SpellIconID == 2860) { triggered_spell_id = 48504; basepoints[0] = triggerAmount * damage / 100; break; } break; } case SPELLFAMILY_ROGUE: { switch(dummySpell->Id) { // Clean Escape case 23582: // triggered spell have same masks and etc with main Vanish spell if (!procSpell || procSpell->Effect[EFFECT_INDEX_0] == SPELL_EFFECT_NONE) return SPELL_AURA_PROC_FAILED; triggered_spell_id = 23583; break; // Deadly Throw Interrupt case 32748: { // Prevent cast Deadly Throw Interrupt on self from last effect (apply dummy) of Deadly Throw if (this == pVictim) return SPELL_AURA_PROC_FAILED; triggered_spell_id = 32747; break; } // Glyph of Backstab case 56800: { if (Aura* aura = target->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_ROGUE, UI64LIT(0x00100000), 0, GetGUID())) { uint32 countMin = aura->GetAuraMaxDuration(); uint32 countMax = GetSpellMaxDuration(aura->GetSpellProto()); countMax += 3 * triggerAmount * 1000; countMax += HasAura(56801) ? 4000 : 0; if (countMin < countMax) { aura->SetAuraDuration(aura->GetAuraDuration() + triggerAmount * 1000); aura->SetAuraMaxDuration(countMin + triggerAmount * 1000); aura->GetHolder()->SendAuraUpdate(false); return SPELL_AURA_PROC_OK; } } return SPELL_AURA_PROC_FAILED; } // Tricks of the trade case 57934: { triggered_spell_id = 57933; // Tricks of the Trade, increased damage buff target = getHostileRefManager().GetThreatRedirectionTarget(); if (!target) return SPELL_AURA_PROC_FAILED; CastSpell(this, 59628, true); // Tricks of the Trade (caster timer) break; } } // Cut to the Chase if (dummySpell->SpellIconID == 2909) { // "refresh your Slice and Dice duration to its 5 combo point maximum" // lookup Slice and Dice AuraList const& sd = GetAurasByType(SPELL_AURA_MOD_MELEE_HASTE); for(AuraList::const_iterator itr = sd.begin(); itr != sd.end(); ++itr) { SpellEntry const *spellProto = (*itr)->GetSpellProto(); if (spellProto->SpellFamilyName == SPELLFAMILY_ROGUE && (spellProto->SpellFamilyFlags & UI64LIT(0x0000000000040000))) { int32 duration = GetSpellMaxDuration(spellProto); if(GetTypeId() == TYPEID_PLAYER) static_cast<Player*>(this)->ApplySpellMod(spellProto->Id, SPELLMOD_DURATION, duration); (*itr)->SetAuraMaxDuration(duration); (*itr)->GetHolder()->RefreshHolder(); return SPELL_AURA_PROC_OK; } } return SPELL_AURA_PROC_FAILED; } // Deadly Brew if (dummySpell->SpellIconID == 2963) { triggered_spell_id = 44289; break; } // Quick Recovery if (dummySpell->SpellIconID == 2116) { if(!procSpell) return SPELL_AURA_PROC_FAILED; //do not proc from spells that do not need combo points if(!NeedsComboPoints(procSpell)) return SPELL_AURA_PROC_FAILED; // energy cost save basepoints[0] = procSpell->manaCost * triggerAmount/100; if (basepoints[0] <= 0) return SPELL_AURA_PROC_FAILED; target = this; triggered_spell_id = 31663; break; } break; } case SPELLFAMILY_HUNTER: { // Thrill of the Hunt if (dummySpell->SpellIconID == 2236) { if (!procSpell) return SPELL_AURA_PROC_FAILED; // mana cost save int32 mana = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100; basepoints[0] = mana * 40/100; if (basepoints[0] <= 0) return SPELL_AURA_PROC_FAILED; target = this; triggered_spell_id = 34720; break; } // Hunting Party if (dummySpell->SpellIconID == 3406) { triggered_spell_id = 57669; target = this; break; } // Lock and Load if ( dummySpell->SpellIconID == 3579 ) { // Proc only from periodic (from trap activation proc another aura of this spell) if (!(procFlag & PROC_FLAG_ON_DO_PERIODIC) || !roll_chance_i(triggerAmount)) return SPELL_AURA_PROC_FAILED; triggered_spell_id = 56453; target = this; break; } // Rapid Recuperation if ( dummySpell->SpellIconID == 3560 ) { // This effect only from Rapid Killing (mana regen) if (!(procSpell->SpellFamilyFlags & UI64LIT(0x0100000000000000))) return SPELL_AURA_PROC_FAILED; target = this; switch(dummySpell->Id) { case 53228: // Rank 1 triggered_spell_id = 56654; break; case 53232: // Rank 2 triggered_spell_id = 58882; break; } break; } // Glyph of Mend Pet if(dummySpell->Id == 57870) { pVictim->CastSpell(pVictim, 57894, true, NULL, NULL, GetGUID()); return SPELL_AURA_PROC_OK; } // Misdirection else if(dummySpell->Id == 34477) { triggered_spell_id = 35079; // 4 sec buff on self target = this; break; } // Guard Dog else if (dummySpell->SpellIconID == 201 && procSpell->SpellIconID == 201) { triggered_spell_id = 54445; target = this; if (pVictim) pVictim->AddThreat(this,procSpell->EffectBasePoints[0] * triggerAmount / 100.0f); break; } break; } case SPELLFAMILY_PALADIN: { // Seal of Righteousness - melee proc dummy (addition ${$MWS*(0.022*$AP+0.044*$SPH)} damage) if ((dummySpell->SpellFamilyFlags & UI64LIT(0x000000008000000)) && effIndex == EFFECT_INDEX_0) { triggered_spell_id = 25742; float ap = GetTotalAttackPowerValue(BASE_ATTACK); int32 holy = SpellBaseDamageBonusDone(SPELL_SCHOOL_MASK_HOLY); if (holy < 0) holy = 0; basepoints[0] = GetAttackTime(BASE_ATTACK) * int32(ap*0.022f + 0.044f * holy) / 1000; break; } // Righteous Vengeance if (dummySpell->SpellIconID == 3025) { // 4 damage tick basepoints[0] = triggerAmount*damage/400; triggered_spell_id = 61840; break; } // Sheath of Light if (dummySpell->SpellIconID == 3030) { // 4 healing tick basepoints[0] = triggerAmount*damage/400; triggered_spell_id = 54203; break; } switch(dummySpell->Id) { // Judgement of Light case 20185: { if (pVictim == this) return SPELL_AURA_PROC_FAILED; basepoints[0] = int32( pVictim->GetMaxHealth() * triggeredByAura->GetModifier()->m_amount / 100 ); pVictim->CastCustomSpell(pVictim, 20267, &basepoints[0], NULL, NULL, true, NULL, triggeredByAura); return SPELL_AURA_PROC_OK; } // Judgement of Wisdom case 20186: { if (pVictim->getPowerType() == POWER_MANA) { // 2% of maximum base mana basepoints[0] = int32(pVictim->GetCreateMana() * 2 / 100); pVictim->CastCustomSpell(pVictim, 20268, &basepoints[0], NULL, NULL, true, NULL, triggeredByAura); } return SPELL_AURA_PROC_OK; } // Heart of the Crusader (Rank 1) case 20335: triggered_spell_id = 21183; break; // Heart of the Crusader (Rank 2) case 20336: triggered_spell_id = 54498; break; // Heart of the Crusader (Rank 3) case 20337: triggered_spell_id = 54499; break; case 20911: // Blessing of Sanctuary case 25899: // Greater Blessing of Sanctuary { target = this; switch (target->getPowerType()) { case POWER_MANA: triggered_spell_id = 57319; break; default: return SPELL_AURA_PROC_FAILED; } break; } // Holy Power (Redemption Armor set) case 28789: { if(!pVictim) return SPELL_AURA_PROC_FAILED; // Set class defined buff switch (pVictim->getClass()) { case CLASS_PALADIN: case CLASS_PRIEST: case CLASS_SHAMAN: case CLASS_DRUID: triggered_spell_id = 28795; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d. break; case CLASS_MAGE: case CLASS_WARLOCK: triggered_spell_id = 28793; // Increases the friendly target's spell damage and healing by up to $s1 for $d. break; case CLASS_HUNTER: case CLASS_ROGUE: triggered_spell_id = 28791; // Increases the friendly target's attack power by $s1 for $d. break; case CLASS_WARRIOR: triggered_spell_id = 28790; // Increases the friendly target's armor break; default: return SPELL_AURA_PROC_FAILED; } break; } // Spiritual Attunement case 31785: case 33776: { // if healed by another unit (pVictim) if (this == pVictim) return SPELL_AURA_PROC_FAILED; // dont count overhealing uint32 diff = GetMaxHealth()-GetHealth(); if (!diff) return SPELL_AURA_PROC_FAILED; if (damage > diff) basepoints[0] = triggerAmount*diff/100; else basepoints[0] = triggerAmount*damage/100; target = this; triggered_spell_id = 31786; break; } // Seal of Vengeance (damage calc on apply aura) case 31801: { if (effIndex != EFFECT_INDEX_0) // effect 1,2 used by seal unleashing code return SPELL_AURA_PROC_FAILED; // At melee attack or Hammer of the Righteous spell damage considered as melee attack if ((procFlag & PROC_FLAG_SUCCESSFUL_MELEE_HIT) || (procSpell && procSpell->Id == 53595) ) triggered_spell_id = 31803; // Holy Vengeance // Add 5-stack effect from Holy Vengeance uint32 stacks = 0; AuraList const& auras = target->GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE); for(AuraList::const_iterator itr = auras.begin(); itr!=auras.end(); ++itr) { if (((*itr)->GetId() == 31803) && (*itr)->GetCasterGuid() == GetObjectGuid()) { stacks = (*itr)->GetStackAmount(); break; } } if (stacks >= 5) CastSpell(target,42463,true,NULL,triggeredByAura); break; } // Judgements of the Wise case 31876: case 31877: case 31878: // triggered only at casted Judgement spells, not at additional Judgement effects if(!procSpell || procSpell->Category != 1210) return SPELL_AURA_PROC_FAILED; target = this; triggered_spell_id = 31930; // Replenishment CastSpell(this, 57669, true, NULL, triggeredByAura); break; // Paladin Tier 6 Trinket (Ashtongue Talisman of Zeal) case 40470: { if (!procSpell) return SPELL_AURA_PROC_FAILED; float chance; // Flash of light/Holy light if (procSpell->SpellFamilyFlags & UI64LIT(0x00000000C0000000)) { triggered_spell_id = 40471; chance = 15.0f; } // Judgement (any) else if (GetSpellSpecific(procSpell->Id)==SPELL_JUDGEMENT) { triggered_spell_id = 40472; chance = 50.0f; } else return SPELL_AURA_PROC_FAILED; if (!roll_chance_f(chance)) return SPELL_AURA_PROC_FAILED; break; } // Light's Beacon (heal target area aura) case 53651: { // not do bonus heal for explicit beacon focus healing if (GetObjectGuid() == triggeredByAura->GetCasterGuid()) return SPELL_AURA_PROC_FAILED; // beacon Unit* beacon = triggeredByAura->GetCaster(); if (!beacon) return SPELL_AURA_PROC_FAILED; if (procSpell->Id == 20267) return SPELL_AURA_PROC_FAILED; // find caster main aura at beacon Aura* dummy = NULL; Unit::AuraList const& baa = beacon->GetAurasByType(SPELL_AURA_PERIODIC_TRIGGER_SPELL); for(Unit::AuraList::const_iterator i = baa.begin(); i != baa.end(); ++i) { if ((*i)->GetId() == 53563 && (*i)->GetCasterGuid() == pVictim->GetObjectGuid()) { dummy = (*i); break; } } // original heal must be form beacon caster if (!dummy) return SPELL_AURA_PROC_FAILED; triggered_spell_id = 53652; // Beacon of Light basepoints[0] = triggeredByAura->GetModifier()->m_amount*damage/100; // cast with original caster set but beacon to beacon for apply caster mods and avoid LoS check beacon->CastCustomSpell(beacon,triggered_spell_id,&basepoints[0],NULL,NULL,true,castItem,triggeredByAura,pVictim->GetGUID()); return SPELL_AURA_PROC_OK; } // Seal of Corruption (damage calc on apply aura) case 53736: { if (effIndex != EFFECT_INDEX_0) // effect 1,2 used by seal unleashing code return SPELL_AURA_PROC_FAILED; // At melee attack or Hammer of the Righteous spell damage considered as melee attack if ((procFlag & PROC_FLAG_SUCCESSFUL_MELEE_HIT) || (procSpell && procSpell->Id == 53595)) triggered_spell_id = 53742; // Blood Corruption // Add 5-stack effect from Blood Corruption uint32 stacks = 0; AuraList const& auras = target->GetAurasByType(SPELL_AURA_PERIODIC_DAMAGE); for(AuraList::const_iterator itr = auras.begin(); itr!=auras.end(); ++itr) { if (((*itr)->GetId() == 53742) && (*itr)->GetCasterGuid() == GetObjectGuid()) { stacks = (*itr)->GetStackAmount(); break; } } if (stacks >= 5) CastSpell(target,53739,true,NULL,triggeredByAura); break; } // Glyph of Holy Light case 54937: { triggered_spell_id = 54968; basepoints[0] = triggerAmount*damage/100; break; } // Sacred Shield (buff) case 58597: { triggered_spell_id = 66922; SpellEntry const* triggeredEntry = sSpellStore.LookupEntry(triggered_spell_id); if (!triggeredEntry) return SPELL_AURA_PROC_FAILED; if(pVictim) if(!pVictim->HasAura(53569, EFFECT_INDEX_0) && !pVictim->HasAura(53576, EFFECT_INDEX_0)) return SPELL_AURA_PROC_FAILED; basepoints[0] = int32(damage / (GetSpellDuration(triggeredEntry) / triggeredEntry->EffectAmplitude[EFFECT_INDEX_0])); target = this; break; } // Sacred Shield (talent rank) case 53601: { // triggered_spell_id in spell data target = this; break; } // Item - Paladin T10 Holy 2P Bonus case 70755: { triggered_spell_id = 71166; break; } // Item - Paladin T10 Retribution 2P Bonus case 70765: { if (GetTypeId() != TYPEID_PLAYER) return SPELL_AURA_PROC_FAILED; ((Player*)this)->RemoveSpellCooldown(53385, true); return SPELL_AURA_PROC_OK; } // Anger Capacitor case 71406: // normal case 71545: // heroic { if (!pVictim) return SPELL_AURA_PROC_FAILED; SpellEntry const* mote = sSpellStore.LookupEntry(71432); if (!mote) return SPELL_AURA_PROC_FAILED; uint32 maxStack = mote->StackAmount - (dummySpell->Id == 71545 ? 1 : 0); SpellAuraHolder *aurHolder = GetSpellAuraHolder(71432); if (aurHolder && uint32(aurHolder->GetStackAmount() +1) >= maxStack) { RemoveAurasDueToSpell(71432); // Mote of Anger // Manifest Anger (main hand/off hand) CastSpell(pVictim, !haveOffhandWeapon() || roll_chance_i(50) ? 71433 : 71434, true); return SPELL_AURA_PROC_OK; } else triggered_spell_id = 71432; break; } // Heartpierce, Item - Icecrown 25 Normal Dagger Proc case 71880: { if(GetTypeId() != TYPEID_PLAYER) return SPELL_AURA_PROC_FAILED; switch (this->getPowerType()) { case POWER_ENERGY: triggered_spell_id = 71882; break; case POWER_RAGE: triggered_spell_id = 71883; break; case POWER_MANA: triggered_spell_id = 71881; break; default: return SPELL_AURA_PROC_FAILED; } break; } // Heartpierce, Item - Icecrown 25 Heroic Dagger Proc case 71892: { if(GetTypeId() != TYPEID_PLAYER) return SPELL_AURA_PROC_FAILED; switch (this->getPowerType()) { case POWER_ENERGY: triggered_spell_id = 71887; break; case POWER_RAGE: triggered_spell_id = 71886; break; case POWER_MANA: triggered_spell_id = 71888; break; default: return SPELL_AURA_PROC_FAILED; } break; } } break; } case SPELLFAMILY_SHAMAN: { switch(dummySpell->Id) { // Totemic Power (The Earthshatterer set) case 28823: { if (!pVictim) return SPELL_AURA_PROC_FAILED; // Set class defined buff switch (pVictim->getClass()) { case CLASS_PALADIN: case CLASS_PRIEST: case CLASS_SHAMAN: case CLASS_DRUID: triggered_spell_id = 28824; // Increases the friendly target's mana regeneration by $s1 per 5 sec. for $d. break; case CLASS_MAGE: case CLASS_WARLOCK: triggered_spell_id = 28825; // Increases the friendly target's spell damage and healing by up to $s1 for $d. break; case CLASS_HUNTER: case CLASS_ROGUE: triggered_spell_id = 28826; // Increases the friendly target's attack power by $s1 for $d. break; case CLASS_WARRIOR: triggered_spell_id = 28827; // Increases the friendly target's armor break; default: return SPELL_AURA_PROC_FAILED; } break; } // Lesser Healing Wave (Totem of Flowing Water Relic) case 28849: { target = this; triggered_spell_id = 28850; break; } // Windfury Weapon (Passive) 1-5 Ranks case 33757: { if(GetTypeId()!=TYPEID_PLAYER) return SPELL_AURA_PROC_FAILED; if(!castItem || !castItem->IsEquipped()) return SPELL_AURA_PROC_FAILED; // custom cooldown processing case if (cooldown && ((Player*)this)->HasSpellCooldown(dummySpell->Id)) return SPELL_AURA_PROC_FAILED; // Now amount of extra power stored in 1 effect of Enchant spell // Get it by item enchant id uint32 spellId; switch (castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT))) { case 283: spellId = 8232; break; // 1 Rank case 284: spellId = 8235; break; // 2 Rank case 525: spellId = 10486; break; // 3 Rank case 1669:spellId = 16362; break; // 4 Rank case 2636:spellId = 25505; break; // 5 Rank case 3785:spellId = 58801; break; // 6 Rank case 3786:spellId = 58803; break; // 7 Rank case 3787:spellId = 58804; break; // 8 Rank default: { sLog.outError("Unit::HandleDummyAuraProc: non handled item enchantment (rank?) %u for spell id: %u (Windfury)", castItem->GetEnchantmentId(EnchantmentSlot(TEMP_ENCHANTMENT_SLOT)),dummySpell->Id); return SPELL_AURA_PROC_FAILED; } } SpellEntry const* windfurySpellEntry = sSpellStore.LookupEntry(spellId); if(!windfurySpellEntry) { sLog.outError("Unit::HandleDummyAuraProc: nonexistent spell id: %u (Windfury)",spellId); return SPELL_AURA_PROC_FAILED; } int32 extra_attack_power = CalculateSpellDamage(pVictim, windfurySpellEntry, EFFECT_INDEX_1); // Totem of Splintering if (Aura* aura = GetAura(60764, EFFECT_INDEX_0)) extra_attack_power += aura->GetModifier()->m_amount; // Off-Hand case if (castItem->GetSlot() == EQUIPMENT_SLOT_OFFHAND) { // Value gained from additional AP basepoints[0] = int32(extra_attack_power/14.0f * GetAttackTime(OFF_ATTACK)/1000/2); triggered_spell_id = 33750; } // Main-Hand case else { // Value gained from additional AP basepoints[0] = int32(extra_attack_power/14.0f * GetAttackTime(BASE_ATTACK)/1000); triggered_spell_id = 25504; } // apply cooldown before cast to prevent processing itself if( cooldown ) ((Player*)this)->AddSpellCooldown(dummySpell->Id,0,time(NULL) + cooldown); // Attack Twice for ( uint32 i = 0; i<2; ++i ) CastCustomSpell(pVictim,triggered_spell_id,&basepoints[0],NULL,NULL,true,castItem,triggeredByAura); return SPELL_AURA_PROC_OK; } // Shaman Tier 6 Trinket case 40463: { if (!procSpell) return SPELL_AURA_PROC_FAILED; float chance; if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000001)) { triggered_spell_id = 40465; // Lightning Bolt chance = 15.0f; } else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000080)) { triggered_spell_id = 40465; // Lesser Healing Wave chance = 10.0f; } else if (procSpell->SpellFamilyFlags & UI64LIT(0x0000001000000000)) { triggered_spell_id = 40466; // Stormstrike chance = 50.0f; } else return SPELL_AURA_PROC_FAILED; if (!roll_chance_f(chance)) return SPELL_AURA_PROC_FAILED; target = this; break; } // Earthen Power case 51523: case 51524: { triggered_spell_id = 63532; break; } // Glyph of Healing Wave case 55440: { // Not proc from self heals if (this==pVictim) return SPELL_AURA_PROC_FAILED; basepoints[0] = triggerAmount * damage / 100; target = this; triggered_spell_id = 55533; break; } // Spirit Hunt case 58877: { // Cast on owner target = GetOwner(); if (!target) return SPELL_AURA_PROC_FAILED; basepoints[0] = triggerAmount * damage / 100; triggered_spell_id = 58879; break; } // Glyph of Totem of Wrath case 63280: { Totem* totem = GetTotem(TOTEM_SLOT_FIRE); if (!totem) return SPELL_AURA_PROC_FAILED; // find totem aura bonus AuraList const& spellPower = totem->GetAurasByType(SPELL_AURA_NONE); for(AuraList::const_iterator i = spellPower.begin();i != spellPower.end(); ++i) { // select proper aura for format aura type in spell proto if ((*i)->GetTarget()==totem && (*i)->GetSpellProto()->EffectApplyAuraName[(*i)->GetEffIndex()] == SPELL_AURA_MOD_HEALING_DONE && (*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_SHAMAN && (*i)->GetSpellProto()->SpellFamilyFlags & UI64LIT(0x0000000004000000)) { basepoints[0] = triggerAmount * (*i)->GetModifier()->m_amount / 100; break; } } if (!basepoints[0]) return SPELL_AURA_PROC_FAILED; basepoints[1] = basepoints[0]; triggered_spell_id = 63283; // Totem of Wrath, caster bonus target = this; break; } // Shaman T8 Elemental 4P Bonus case 64928: { basepoints[0] = int32( basepoints[0] / 2); // basepoints is for 1 tick, not all DoT amount triggered_spell_id = 64930; // Electrified break; } // Shaman T9 Elemental 4P Bonus case 67228: { basepoints[0] = int32( basepoints[0] / 3); // basepoints is for 1 tick, not all DoT amount triggered_spell_id = 71824; break; } // Item - Shaman T10 Restoration 4P Bonus case 70808: { basepoints[0] = int32( triggerAmount * damage / 100 ); basepoints[0] = int32( basepoints[0] / 3); // basepoints is for 1 tick, not all DoT amount triggered_spell_id = 70809; break; } // Item - Shaman T10 Elemental 4P Bonus case 70817: { if (Aura *aur = pVictim->GetAura(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_SHAMAN, UI64LIT(0x0000000010000000), 0, GetGUID())) { int32 amount = aur->GetAuraDuration() + triggerAmount * IN_MILLISECONDS; aur->SetAuraDuration(amount); aur->UpdateAura(false); return SPELL_AURA_PROC_OK; } return SPELL_AURA_PROC_FAILED; } } // Storm, Earth and Fire if (dummySpell->SpellIconID == 3063) { // Earthbind Totem summon only if(procSpell->Id != 2484) return SPELL_AURA_PROC_FAILED; if (!roll_chance_i(triggerAmount)) return SPELL_AURA_PROC_FAILED; triggered_spell_id = 64695; break; } // Ancestral Awakening if (dummySpell->SpellIconID == 3065) { triggered_spell_id = 52759; basepoints[0] = triggerAmount * damage / 100; target = this; break; } // Flametongue Weapon (Passive), Ranks if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000000000200000)) { if (GetTypeId()!=TYPEID_PLAYER || !castItem) return SPELL_AURA_PROC_FAILED; // Only proc for enchanted weapon Item *usedWeapon = ((Player *)this)->GetWeaponForAttack(procFlag & PROC_FLAG_SUCCESSFUL_OFFHAND_HIT ? OFF_ATTACK : BASE_ATTACK, true, true); if (usedWeapon != castItem) return SPELL_AURA_PROC_FAILED; switch (dummySpell->Id) { case 10400: triggered_spell_id = 8026; break; // Rank 1 case 15567: triggered_spell_id = 8028; break; // Rank 2 case 15568: triggered_spell_id = 8029; break; // Rank 3 case 15569: triggered_spell_id = 10445; break; // Rank 4 case 16311: triggered_spell_id = 16343; break; // Rank 5 case 16312: triggered_spell_id = 16344; break; // Rank 6 case 16313: triggered_spell_id = 25488; break; // Rank 7 case 58784: triggered_spell_id = 58786; break; // Rank 8 case 58791: triggered_spell_id = 58787; break; // Rank 9 case 58792: triggered_spell_id = 58788; break; // Rank 10 default: return SPELL_AURA_PROC_FAILED; } break; } // Earth Shield if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000040000000000)) { originalCaster = triggeredByAura->GetCasterGuid(); target = this; basepoints[0] = triggerAmount; // Glyph of Earth Shield if (Aura* aur = GetDummyAura(63279)) { int32 aur_mod = aur->GetModifier()->m_amount; basepoints[0] = int32(basepoints[0] * (aur_mod + 100.0f) / 100.0f); } triggered_spell_id = 379; break; } // Improved Water Shield if (dummySpell->SpellIconID == 2287) { // Lesser Healing Wave need aditional 60% roll if ((procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000080)) && !roll_chance_i(60)) return SPELL_AURA_PROC_FAILED; // Chain Heal needs additional 30% roll if ((procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000100)) && !roll_chance_i(30)) return SPELL_AURA_PROC_FAILED; // lookup water shield AuraList const& vs = GetAurasByType(SPELL_AURA_PROC_TRIGGER_SPELL); for(AuraList::const_iterator itr = vs.begin(); itr != vs.end(); ++itr) { if ((*itr)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_SHAMAN && ((*itr)->GetSpellProto()->SpellFamilyFlags & UI64LIT(0x0000002000000000))) { uint32 spell = (*itr)->GetSpellProto()->EffectTriggerSpell[(*itr)->GetEffIndex()]; CastSpell(this, spell, true, castItem, triggeredByAura); return SPELL_AURA_PROC_OK; } } return SPELL_AURA_PROC_FAILED; } // Lightning Overload if (dummySpell->SpellIconID == 2018) // only this spell have SpellFamily Shaman SpellIconID == 2018 and dummy aura { if(!procSpell || GetTypeId() != TYPEID_PLAYER || !pVictim ) return SPELL_AURA_PROC_FAILED; // custom cooldown processing case if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(dummySpell->Id)) return SPELL_AURA_PROC_FAILED; uint32 spellId = 0; // Every Lightning Bolt and Chain Lightning spell have duplicate vs half damage and zero cost switch (procSpell->Id) { // Lightning Bolt case 403: spellId = 45284; break; // Rank 1 case 529: spellId = 45286; break; // Rank 2 case 548: spellId = 45287; break; // Rank 3 case 915: spellId = 45288; break; // Rank 4 case 943: spellId = 45289; break; // Rank 5 case 6041: spellId = 45290; break; // Rank 6 case 10391: spellId = 45291; break; // Rank 7 case 10392: spellId = 45292; break; // Rank 8 case 15207: spellId = 45293; break; // Rank 9 case 15208: spellId = 45294; break; // Rank 10 case 25448: spellId = 45295; break; // Rank 11 case 25449: spellId = 45296; break; // Rank 12 case 49237: spellId = 49239; break; // Rank 13 case 49238: spellId = 49240; break; // Rank 14 // Chain Lightning case 421: spellId = 45297; break; // Rank 1 case 930: spellId = 45298; break; // Rank 2 case 2860: spellId = 45299; break; // Rank 3 case 10605: spellId = 45300; break; // Rank 4 case 25439: spellId = 45301; break; // Rank 5 case 25442: spellId = 45302; break; // Rank 6 case 49270: spellId = 49268; break; // Rank 7 case 49271: spellId = 49269; break; // Rank 8 default: sLog.outError("Unit::HandleDummyAuraProc: non handled spell id: %u (LO)", procSpell->Id); return SPELL_AURA_PROC_FAILED; } // Remove cooldown (Chain Lightning - have Category Recovery time) if (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000002)) ((Player*)this)->RemoveSpellCooldown(spellId); CastSpell(pVictim, spellId, true, castItem, triggeredByAura); if (cooldown && GetTypeId() == TYPEID_PLAYER) ((Player*)this)->AddSpellCooldown(dummySpell->Id, 0, time(NULL) + cooldown); return SPELL_AURA_PROC_OK; } // Static Shock if(dummySpell->SpellIconID == 3059) { // lookup Lightning Shield AuraList const& vs = GetAurasByType(SPELL_AURA_PROC_TRIGGER_SPELL); for(AuraList::const_iterator itr = vs.begin(); itr != vs.end(); ++itr) { if ((*itr)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_SHAMAN && ((*itr)->GetSpellProto()->SpellFamilyFlags & UI64LIT(0x0000000000000400))) { uint32 spell = 0; switch ((*itr)->GetId()) { case 324: spell = 26364; break; case 325: spell = 26365; break; case 905: spell = 26366; break; case 945: spell = 26367; break; case 8134: spell = 26369; break; case 10431: spell = 26370; break; case 10432: spell = 26363; break; case 25469: spell = 26371; break; case 25472: spell = 26372; break; case 49280: spell = 49278; break; case 49281: spell = 49279; break; default: return SPELL_AURA_PROC_FAILED; } CastSpell(target, spell, true, castItem, triggeredByAura); if ((*itr)->GetHolder()->DropAuraCharge()) RemoveAuraHolderFromStack((*itr)->GetId()); return SPELL_AURA_PROC_OK; } } return SPELL_AURA_PROC_FAILED; } // Frozen Power if (dummySpell->SpellIconID == 3780) { Unit *caster = triggeredByAura->GetCaster(); if (!procSpell || !caster) return SPELL_AURA_PROC_FAILED; float distance = caster->GetDistance(pVictim); int32 chance = triggerAmount; if (distance < 15.0f || !roll_chance_i(chance)) return SPELL_AURA_PROC_FAILED; // make triggered cast apply after current damage spell processing for prevent remove by it if(Spell* spell = GetCurrentSpell(CURRENT_GENERIC_SPELL)) spell->AddTriggeredSpell(63685); return SPELL_AURA_PROC_OK; } break; } case SPELLFAMILY_DEATHKNIGHT: { // Butchery if (dummySpell->SpellIconID == 2664) { basepoints[0] = triggerAmount; triggered_spell_id = 50163; target = this; break; } // Dancing Rune Weapon if (dummySpell->Id == 49028) { // 1 dummy aura for dismiss rune blade if (effIndex != EFFECT_INDEX_1) return SPELL_AURA_PROC_FAILED; Pet* runeBlade = FindGuardianWithEntry(27893); if (runeBlade && pVictim && damage && procSpell) { int32 procDmg = damage * 0.5; runeBlade->CastCustomSpell(pVictim, procSpell->Id, &procDmg, NULL, NULL, true, NULL, NULL, runeBlade->GetGUID()); SendSpellNonMeleeDamageLog(pVictim, procSpell->Id, procDmg, SPELL_SCHOOL_MASK_NORMAL, 0, 0, false, 0, false); break; } else return SPELL_AURA_PROC_FAILED; } // Mark of Blood if (dummySpell->Id == 49005) { if (target->GetTypeId() != TYPEID_PLAYER) return SPELL_AURA_PROC_FAILED; // TODO: need more info (cooldowns/PPM) target->CastSpell(target, 61607, true, NULL, triggeredByAura); return SPELL_AURA_PROC_OK; } // Unholy Blight if (dummySpell->Id == 49194) { basepoints[0] = damage * triggerAmount / 100; // Glyph of Unholy Blight if (Aura *aura = GetDummyAura(63332)) basepoints[0] += basepoints[0] * aura->GetModifier()->m_amount / 100; // Split between 10 ticks basepoints[0] /= 10; triggered_spell_id = 50536; break; } // Vendetta if (dummySpell->SpellFamilyFlags & UI64LIT(0x0000000000010000)) { basepoints[0] = triggerAmount * GetMaxHealth() / 100; triggered_spell_id = 50181; target = this; break; } // Necrosis if (dummySpell->SpellIconID == 2709) { // only melee auto attack affected and Rune Strike if (procSpell && procSpell->Id != 56815) return SPELL_AURA_PROC_FAILED; basepoints[0] = triggerAmount * damage / 100; triggered_spell_id = 51460; break; } // Threat of Thassarian if (dummySpell->SpellIconID == 2023) { // Must Dual Wield if (!procSpell || !haveOffhandWeapon()) return SPELL_AURA_PROC_FAILED; // Chance as basepoints for dummy aura if (!roll_chance_i(triggerAmount)) return SPELL_AURA_PROC_FAILED; switch (procSpell->Id) { // Obliterate case 49020: // Rank 1 triggered_spell_id = 66198; break; case 51423: // Rank 2 triggered_spell_id = 66972; break; case 51424: // Rank 3 triggered_spell_id = 66973; break; case 51425: // Rank 4 triggered_spell_id = 66974; break; // Frost Strike case 49143: // Rank 1 triggered_spell_id = 66196; break; case 51416: // Rank 2 triggered_spell_id = 66958; break; case 51417: // Rank 3 triggered_spell_id = 66959; break; case 51418: // Rank 4 triggered_spell_id = 66960; break; case 51419: // Rank 5 triggered_spell_id = 66961; break; case 55268: // Rank 6 triggered_spell_id = 66962; break; // Plague Strike case 45462: // Rank 1 triggered_spell_id = 66216; break; case 49917: // Rank 2 triggered_spell_id = 66988; break; case 49918: // Rank 3 triggered_spell_id = 66989; break; case 49919: // Rank 4 triggered_spell_id = 66990; break; case 49920: // Rank 5 triggered_spell_id = 66991; break; case 49921: // Rank 6 triggered_spell_id = 66992; break; // Death Strike case 49998: // Rank 1 triggered_spell_id = 66188; break; case 49999: // Rank 2 triggered_spell_id = 66950; break; case 45463: // Rank 3 triggered_spell_id = 66951; break; case 49923: // Rank 4 triggered_spell_id = 66952; break; case 49924: // Rank 5 triggered_spell_id = 66953; break; // Rune Strike case 56815: triggered_spell_id = 66217; break; // Blood Strike case 45902: // Rank 1 triggered_spell_id = 66215; break; case 49926: // Rank 2 triggered_spell_id = 66975; break; case 49927: // Rank 3 triggered_spell_id = 66976; break; case 49928: // Rank 4 triggered_spell_id = 66977; break; case 49929: // Rank 5 triggered_spell_id = 66978; break; case 49930: // Rank 6 triggered_spell_id = 66979; break; default: return SPELL_AURA_PROC_FAILED; } break; } // Runic Power Back on Snare/Root if (dummySpell->Id == 61257) { // only for spells and hit/crit (trigger start always) and not start from self casted spells if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim) return SPELL_AURA_PROC_FAILED; // Need snare or root mechanic if (!(GetAllSpellMechanicMask(procSpell) & IMMUNE_TO_ROOT_AND_SNARE_MASK)) return SPELL_AURA_PROC_FAILED; triggered_spell_id = 61258; target = this; break; } // Sudden Doom if (dummySpell->SpellIconID == 1939) { if (!target || !target->isAlive() || this->GetTypeId() != TYPEID_PLAYER) return SPELL_AURA_PROC_FAILED; // get highest rank of Death Coil spell const PlayerSpellMap& sp_list = ((Player*)this)->GetSpellMap(); for (PlayerSpellMap::const_iterator itr = sp_list.begin(); itr != sp_list.end(); ++itr) { if(!itr->second.active || itr->second.disabled || itr->second.state == PLAYERSPELL_REMOVED) continue; SpellEntry const *spellInfo = sSpellStore.LookupEntry(itr->first); if (!spellInfo) continue; if (spellInfo->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT && spellInfo->SpellFamilyFlags & UI64LIT(0x2000)) { triggered_spell_id = spellInfo->Id; break; } } break; } // Wandering Plague if (dummySpell->SpellIconID == 1614) { if (!roll_chance_f(GetUnitCriticalChance(BASE_ATTACK, pVictim))) return SPELL_AURA_PROC_FAILED; basepoints[0] = triggerAmount * damage / 100; triggered_spell_id = 50526; break; } // Blood of the North and Reaping if (dummySpell->SpellIconID == 3041 || dummySpell->SpellIconID == 22) { if(GetTypeId()!=TYPEID_PLAYER) return SPELL_AURA_PROC_FAILED; Player *player = (Player*)this; for (uint32 i = 0; i < MAX_RUNES; ++i) { if (player->GetCurrentRune(i) == RUNE_BLOOD) { if(!player->GetRuneCooldown(i)) player->ConvertRune(i, RUNE_DEATH, dummySpell->Id); else { // search for another rune that might be available for (uint32 iter = i; iter < MAX_RUNES; ++iter) { if(player->GetCurrentRune(iter) == RUNE_BLOOD && !player->GetRuneCooldown(iter)) { player->ConvertRune(iter, RUNE_DEATH, dummySpell->Id); triggeredByAura->SetAuraPeriodicTimer(0); return SPELL_AURA_PROC_OK; } } player->SetNeedConvertRune(i, true, dummySpell->Id); } triggeredByAura->SetAuraPeriodicTimer(0); return SPELL_AURA_PROC_OK; } } return SPELL_AURA_PROC_FAILED; } // Death Rune Mastery if (dummySpell->SpellIconID == 2622) { if(GetTypeId()!=TYPEID_PLAYER) return SPELL_AURA_PROC_FAILED; Player *player = (Player*)this; for (uint32 i = 0; i < MAX_RUNES; ++i) { RuneType currRune = player->GetCurrentRune(i); if (currRune == RUNE_UNHOLY || currRune == RUNE_FROST) { uint16 cd = player->GetRuneCooldown(i); if(!cd) player->ConvertRune(i, RUNE_DEATH, dummySpell->Id); else // there is a cd player->SetNeedConvertRune(i, true, dummySpell->Id); // no break because it converts all } } triggeredByAura->SetAuraPeriodicTimer(0); return SPELL_AURA_PROC_OK; } // Hungering Cold - not break from diseases if (dummySpell->SpellIconID == 2797) { if (procSpell && procSpell->Dispel == DISPEL_DISEASE) return SPELL_AURA_PROC_FAILED; } // Blood-Caked Blade if (dummySpell->SpellIconID == 138) { // only main hand melee auto attack affected and Rune Strike if ((procFlag & PROC_FLAG_SUCCESSFUL_OFFHAND_HIT) || procSpell && procSpell->Id != 56815) return SPELL_AURA_PROC_FAILED; // triggered_spell_id in spell data break; } break; } case SPELLFAMILY_PET: { // Improved Cower if (dummySpell->SpellIconID == 958 && procSpell->SpellIconID == 958) { triggered_spell_id = dummySpell->Id == 53180 ? 54200 : 54201; target = this; break; } // Guard Dog if (dummySpell->SpellIconID == 201 && procSpell->SpellIconID == 201) { triggered_spell_id = 54445; target = this; break; } // Silverback if (dummySpell->SpellIconID == 1582 && procSpell->SpellIconID == 201) { triggered_spell_id = dummySpell->Id == 62764 ? 62800 : 62801; target = this; break; } break; } default: break; } // processed charge only counting case if (!triggered_spell_id) return SPELL_AURA_PROC_OK; SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id); if (!triggerEntry) { sLog.outError("Unit::HandleDummyAuraProc: Spell %u have nonexistent triggered spell %u",dummySpell->Id,triggered_spell_id); return SPELL_AURA_PROC_FAILED; } // default case if (!target || (target != this && !target->isAlive())) return SPELL_AURA_PROC_FAILED; if (cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id)) return SPELL_AURA_PROC_FAILED; if (basepoints[EFFECT_INDEX_0] || basepoints[EFFECT_INDEX_1] || basepoints[EFFECT_INDEX_2]) CastCustomSpell(target, triggerEntry, basepoints[EFFECT_INDEX_0] ? &basepoints[EFFECT_INDEX_0] : NULL, basepoints[EFFECT_INDEX_1] ? &basepoints[EFFECT_INDEX_1] : NULL, basepoints[EFFECT_INDEX_2] ? &basepoints[EFFECT_INDEX_2] : NULL, true, castItem, triggeredByAura, originalCaster); else CastSpell(target, triggerEntry, true, castItem, triggeredByAura); if (cooldown && GetTypeId()==TYPEID_PLAYER) ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown); return SPELL_AURA_PROC_OK; } SpellAuraProcResult Unit::HandleProcTriggerSpellAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlags, uint32 procEx, uint32 cooldown) { // Get triggered aura spell info SpellEntry const* auraSpellInfo = triggeredByAura->GetSpellProto(); // Basepoints of trigger aura int32 triggerAmount = triggeredByAura->GetModifier()->m_amount; // Set trigger spell id, target, custom basepoints uint32 trigger_spell_id = auraSpellInfo->EffectTriggerSpell[triggeredByAura->GetEffIndex()]; Unit* target = NULL; int32 basepoints[MAX_EFFECT_INDEX] = {0, 0, 0}; if(triggeredByAura->GetModifier()->m_auraname == SPELL_AURA_PROC_TRIGGER_SPELL_WITH_VALUE) basepoints[0] = triggerAmount; Item* castItem = !triggeredByAura->GetCastItemGuid().IsEmpty() && GetTypeId()==TYPEID_PLAYER ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGuid()) : NULL; // Try handle unknown trigger spells // Custom requirements (not listed in procEx) Warning! damage dealing after this // Custom triggered spells switch (auraSpellInfo->SpellFamilyName) { case SPELLFAMILY_GENERIC: switch(auraSpellInfo->Id) { //case 191: // Elemental Response // switch (procSpell->School) // { // case SPELL_SCHOOL_FIRE: trigger_spell_id = 34192; break; // case SPELL_SCHOOL_FROST: trigger_spell_id = 34193; break; // case SPELL_SCHOOL_ARCANE:trigger_spell_id = 34194; break; // case SPELL_SCHOOL_NATURE:trigger_spell_id = 34195; break; // case SPELL_SCHOOL_SHADOW:trigger_spell_id = 34196; break; // case SPELL_SCHOOL_HOLY: trigger_spell_id = 34197; break; // case SPELL_SCHOOL_NORMAL:trigger_spell_id = 34198; break; // } // break; //case 5301: break; // Defensive State (DND) //case 7137: break: // Shadow Charge (Rank 1) //case 7377: break: // Take Immune Periodic Damage <Not Working> //case 13358: break; // Defensive State (DND) //case 16092: break; // Defensive State (DND) //case 18943: break; // Double Attack //case 19194: break; // Double Attack //case 19817: break; // Double Attack //case 19818: break; // Double Attack //case 22835: break; // Drunken Rage // trigger_spell_id = 14822; break; case 23780: // Aegis of Preservation (Aegis of Preservation trinket) trigger_spell_id = 23781; break; //case 24949: break; // Defensive State 2 (DND) case 27522: // Mana Drain Trigger case 40336: // Mana Drain Trigger // On successful melee or ranged attack gain $29471s1 mana and if possible drain $27526s1 mana from the target. if (isAlive()) CastSpell(this, 29471, true, castItem, triggeredByAura); if (pVictim && pVictim->isAlive()) CastSpell(pVictim, 27526, true, castItem, triggeredByAura); return SPELL_AURA_PROC_OK; case 31255: // Deadly Swiftness (Rank 1) // whenever you deal damage to a target who is below 20% health. if (pVictim->GetHealth() > pVictim->GetMaxHealth() / 5) return SPELL_AURA_PROC_FAILED; target = this; trigger_spell_id = 22588; break; //case 33207: break; // Gossip NPC Periodic - Fidget case 33896: // Desperate Defense (Stonescythe Whelp, Stonescythe Alpha, Stonescythe Ambusher) trigger_spell_id = 33898; break; //case 34082: break; // Advantaged State (DND) //case 34783: break: // Spell Reflection //case 35205: break: // Vanish //case 35321: break; // Gushing Wound //case 36096: break: // Spell Reflection //case 36207: break: // Steal Weapon //case 36576: break: // Shaleskin (Shaleskin Flayer, Shaleskin Ripper) 30023 trigger //case 37030: break; // Chaotic Temperament case 38164: // Unyielding Knights if (pVictim->GetEntry() != 19457) return SPELL_AURA_PROC_FAILED; break; //case 38363: break; // Gushing Wound //case 39215: break; // Gushing Wound //case 40250: break; // Improved Duration //case 40329: break; // Demo Shout Sensor //case 40364: break; // Entangling Roots Sensor //case 41054: break; // Copy Weapon // trigger_spell_id = 41055; break; //case 41248: break; // Consuming Strikes // trigger_spell_id = 41249; break; //case 42730: break: // Woe Strike //case 43453: break: // Rune Ward //case 43504: break; // Alterac Valley OnKill Proc Aura //case 44326: break: // Pure Energy Passive //case 44526: break; // Hate Monster (Spar) (30 sec) //case 44527: break; // Hate Monster (Spar Buddy) (30 sec) //case 44819: break; // Hate Monster (Spar Buddy) (>30% Health) //case 44820: break; // Hate Monster (Spar) (<30%) case 45057: // Evasive Maneuvers (Commendation of Kael`thas trinket) // reduce you below $s1% health if (GetHealth() - damage > GetMaxHealth() * triggerAmount / 100) return SPELL_AURA_PROC_FAILED; break; //case 45903: break: // Offensive State //case 46146: break: // [PH] Ahune Spanky Hands //case 46939: break; // Black Bow of the Betrayer // trigger_spell_id = 29471; - gain mana // 27526; - drain mana if possible case 43820: // Charm of the Witch Doctor (Amani Charm of the Witch Doctor trinket) // Pct value stored in dummy basepoints[0] = pVictim->GetCreateHealth() * auraSpellInfo->CalculateSimpleValue(EFFECT_INDEX_1) / 100; target = pVictim; break; //case 45205: break; // Copy Offhand Weapon //case 45343: break; // Dark Flame Aura //case 47300: break; // Dark Flame Aura //case 48876: break; // Beast's Mark // trigger_spell_id = 48877; break; //case 49059: break; // Horde, Hate Monster (Spar Buddy) (>30% Health) //case 50051: break; // Ethereal Pet Aura //case 50689: break; // Blood Presence (Rank 1) //case 50844: break; // Blood Mirror //case 52856: break; // Charge //case 54072: break; // Knockback Ball Passive //case 54476: break; // Blood Presence //case 54775: break; // Abandon Vehicle on Poly case 56702: // { trigger_spell_id = 56701; break; } case 57345: // Darkmoon Card: Greatness { float stat = 0.0f; // strength if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 60229;stat = GetStat(STAT_STRENGTH); } // agility if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 60233;stat = GetStat(STAT_AGILITY); } // intellect if (GetStat(STAT_INTELLECT)> stat) { trigger_spell_id = 60234;stat = GetStat(STAT_INTELLECT);} // spirit if (GetStat(STAT_SPIRIT) > stat) { trigger_spell_id = 60235; } break; } //case 55580: break: // Mana Link //case 57587: break: // Steal Ranged () //case 57594: break; // Copy Ranged Weapon //case 59237: break; // Beast's Mark // trigger_spell_id = 59233; break; //case 59288: break; // Infra-Green Shield //case 59532: break; // Abandon Passengers on Poly //case 59735: break: // Woe Strike case 64415: // // Val'anyr Hammer of Ancient Kings - Equip Effect { // for DOT procs if (!IsPositiveSpell(procSpell->Id)) return SPELL_AURA_PROC_FAILED; break; } case 64440: // Blade Warding { trigger_spell_id = 64442; // need scale damage base at stack size if (SpellEntry const* trigEntry = sSpellStore.LookupEntry(trigger_spell_id)) basepoints[EFFECT_INDEX_0] = trigEntry->CalculateSimpleValue(EFFECT_INDEX_0) * triggeredByAura->GetStackAmount(); break; } case 64568: // Blood Reserve { // Check health condition - should drop to less 35% if (!(10*(int32(GetHealth() - damage)) < 3.5 * GetMaxHealth())) return SPELL_AURA_PROC_FAILED; if (!roll_chance_f(50)) return SPELL_AURA_PROC_FAILED; trigger_spell_id = 64569; basepoints[0] = triggerAmount; break; } case 67702: // Death's Choice, Item - Coliseum 25 Normal Melee Trinket { float stat = 0.0f; // strength if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 67708;stat = GetStat(STAT_STRENGTH); } // agility if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 67703; } break; } case 67771: // Death's Choice (heroic), Item - Coliseum 25 Heroic Melee Trinket { float stat = 0.0f; // strength if (GetStat(STAT_STRENGTH) > stat) { trigger_spell_id = 67773;stat = GetStat(STAT_STRENGTH); } // agility if (GetStat(STAT_AGILITY) > stat) { trigger_spell_id = 67772; } break; } case 72178: // Blood link Saurfang aura { target = this; trigger_spell_id = 72195; break; } } break; case SPELLFAMILY_MAGE: if (auraSpellInfo->SpellIconID == 2127) // Blazing Speed { switch (auraSpellInfo->Id) { case 31641: // Rank 1 case 31642: // Rank 2 trigger_spell_id = 31643; break; default: sLog.outError("Unit::HandleProcTriggerSpellAuraProc: Spell %u miss possibly Blazing Speed",auraSpellInfo->Id); return SPELL_AURA_PROC_FAILED; } } else if(auraSpellInfo->Id == 26467) // Persistent Shield (Scarab Brooch trinket) { // This spell originally trigger 13567 - Dummy Trigger (vs dummy effect) basepoints[0] = damage * 15 / 100; target = pVictim; trigger_spell_id = 26470; } else if(auraSpellInfo->Id == 71761) // Deep Freeze Immunity State { // spell applied only to permanent immunes to stun targets (bosses) if (pVictim->GetTypeId() != TYPEID_UNIT || (((Creature*)pVictim)->GetCreatureInfo()->MechanicImmuneMask & (1 << (MECHANIC_STUN - 1))) == 0) return SPELL_AURA_PROC_FAILED; } break; case SPELLFAMILY_WARRIOR: // Deep Wounds (replace triggered spells to directly apply DoT), dot spell have familyflags if (auraSpellInfo->SpellFamilyFlags == UI64LIT(0x0) && auraSpellInfo->SpellIconID == 243) { float weaponDamage; // DW should benefit of attack power, damage percent mods etc. // TODO: check if using offhand damage is correct and if it should be divided by 2 if (haveOffhandWeapon() && getAttackTimer(BASE_ATTACK) > getAttackTimer(OFF_ATTACK)) weaponDamage = (GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE) + GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE))/2; else weaponDamage = (GetFloatValue(UNIT_FIELD_MINDAMAGE) + GetFloatValue(UNIT_FIELD_MAXDAMAGE))/2; switch (auraSpellInfo->Id) { case 12834: basepoints[0] = int32(weaponDamage * 16 / 100); break; case 12849: basepoints[0] = int32(weaponDamage * 32 / 100); break; case 12867: basepoints[0] = int32(weaponDamage * 48 / 100); break; // Impossible case default: sLog.outError("Unit::HandleProcTriggerSpellAuraProc: DW unknown spell rank %u",auraSpellInfo->Id); return SPELL_AURA_PROC_FAILED; } // 1 tick/sec * 6 sec = 6 ticks basepoints[0] /= 6; trigger_spell_id = 12721; break; } if (auraSpellInfo->Id == 50421) // Scent of Blood trigger_spell_id = 50422; break; case SPELLFAMILY_WARLOCK: { // Drain Soul if (auraSpellInfo->SpellFamilyFlags & UI64LIT(0x0000000000004000)) { // search for "Improved Drain Soul" dummy aura Unit::AuraList const& mDummyAura = GetAurasByType(SPELL_AURA_DUMMY); for(Unit::AuraList::const_iterator i = mDummyAura.begin(); i != mDummyAura.end(); ++i) { if ((*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARLOCK && (*i)->GetSpellProto()->SpellIconID == 113) { // basepoints of trigger spell stored in dummyeffect of spellProto int32 basepoints = GetMaxPower(POWER_MANA) * (*i)->GetSpellProto()->CalculateSimpleValue(EFFECT_INDEX_2) / 100; CastCustomSpell(this, 18371, &basepoints, NULL, NULL, true, castItem, triggeredByAura); break; } } // Not remove charge (aura removed on death in any cases) // Need for correct work Drain Soul SPELL_AURA_CHANNEL_DEATH_ITEM aura return SPELL_AURA_PROC_FAILED; } // Nether Protection else if (auraSpellInfo->SpellIconID == 1985) { if (!procSpell) return SPELL_AURA_PROC_FAILED; switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell))) { case SPELL_SCHOOL_NORMAL: return SPELL_AURA_PROC_FAILED; // ignore case SPELL_SCHOOL_HOLY: trigger_spell_id = 54370; break; case SPELL_SCHOOL_FIRE: trigger_spell_id = 54371; break; case SPELL_SCHOOL_NATURE: trigger_spell_id = 54375; break; case SPELL_SCHOOL_FROST: trigger_spell_id = 54372; break; case SPELL_SCHOOL_SHADOW: trigger_spell_id = 54374; break; case SPELL_SCHOOL_ARCANE: trigger_spell_id = 54373; break; default: return SPELL_AURA_PROC_FAILED; } } // Cheat Death else if (auraSpellInfo->Id == 28845) { // When your health drops below 20% .... if (GetHealth() - damage > GetMaxHealth() / 5 || GetHealth() < GetMaxHealth() / 5) return SPELL_AURA_PROC_FAILED; } // Decimation else if (auraSpellInfo->Id == 63156 || auraSpellInfo->Id == 63158) { // Looking for dummy effect Aura *aur = GetAura(auraSpellInfo->Id, EFFECT_INDEX_1); if (!aur) return SPELL_AURA_PROC_FAILED; // If target's health is not below equal certain value (35%) not proc if (int32(pVictim->GetHealth() * 100 / pVictim->GetMaxHealth()) > aur->GetModifier()->m_amount) return SPELL_AURA_PROC_FAILED; } break; } case SPELLFAMILY_PRIEST: { // Greater Heal Refund (Avatar Raiment set) if (auraSpellInfo->Id==37594) { // Not give if target already have full health if (pVictim->GetHealth() == pVictim->GetMaxHealth()) return SPELL_AURA_PROC_FAILED; // If your Greater Heal brings the target to full health, you gain $37595s1 mana. if (pVictim->GetHealth() + damage < pVictim->GetMaxHealth()) return SPELL_AURA_PROC_FAILED; trigger_spell_id = 37595; } // Blessed Recovery else if (auraSpellInfo->SpellIconID == 1875) { switch (auraSpellInfo->Id) { case 27811: trigger_spell_id = 27813; break; case 27815: trigger_spell_id = 27817; break; case 27816: trigger_spell_id = 27818; break; default: sLog.outError("Unit::HandleProcTriggerSpellAuraProc: Spell %u not handled in BR", auraSpellInfo->Id); return SPELL_AURA_PROC_FAILED; } basepoints[0] = damage * triggerAmount / 100 / 3; target = this; } // Glyph of Shadow Word: Pain else if (auraSpellInfo->Id == 55681) basepoints[0] = triggerAmount * GetCreateMana() / 100; break; } case SPELLFAMILY_DRUID: { // Druid Forms Trinket if (auraSpellInfo->Id==37336) { switch(GetShapeshiftForm()) { case FORM_NONE: trigger_spell_id = 37344;break; case FORM_CAT: trigger_spell_id = 37341;break; case FORM_BEAR: case FORM_DIREBEAR: trigger_spell_id = 37340;break; case FORM_TREE: trigger_spell_id = 37342;break; case FORM_MOONKIN: trigger_spell_id = 37343;break; default: return SPELL_AURA_PROC_FAILED; } } // Druid T9 Feral Relic (Lacerate, Swipe, Mangle, and Shred) else if (auraSpellInfo->Id==67353) { switch(GetShapeshiftForm()) { case FORM_CAT: trigger_spell_id = 67355; break; case FORM_BEAR: case FORM_DIREBEAR: trigger_spell_id = 67354; break; default: return SPELL_AURA_PROC_FAILED; } } break; } case SPELLFAMILY_ROGUE: // Item - Rogue T10 2P Bonus if (auraSpellInfo->Id == 70805) { if (pVictim != this) return SPELL_AURA_PROC_FAILED; } // Item - Rogue T10 4P Bonus else if (auraSpellInfo->Id == 70803) { if (!procSpell) return SPELL_AURA_PROC_FAILED; // only allow melee finishing move to proc if (!(procSpell->AttributesEx & SPELL_ATTR_EX_REQ_TARGET_COMBO_POINTS) || procSpell->Id == 26679) return SPELL_AURA_PROC_FAILED; trigger_spell_id = 70802; target = this; } break; case SPELLFAMILY_HUNTER: { // Piercing Shots if (auraSpellInfo->SpellIconID == 3247 && auraSpellInfo->SpellVisual[0] == 0) { basepoints[0] = damage * triggerAmount / 100 / 8; trigger_spell_id = 63468; target = pVictim; } // Rapid Recuperation else if (auraSpellInfo->Id == 53228 || auraSpellInfo->Id == 53232) { // This effect only from Rapid Fire (ability cast) if (!(procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000020))) return SPELL_AURA_PROC_FAILED; } // Entrapment correction else if ((auraSpellInfo->Id == 19184 || auraSpellInfo->Id == 19387 || auraSpellInfo->Id == 19388) && !(procSpell->SpellFamilyFlags & UI64LIT(0x200000000000) || procSpell->SpellFamilyFlags2 & UI64LIT(0x40000))) return SPELL_AURA_PROC_FAILED; // Lock and Load else if (auraSpellInfo->SpellIconID == 3579) { // Check for Lock and Load Marker if (HasAura(67544)) return SPELL_AURA_PROC_FAILED; } break; } case SPELLFAMILY_PALADIN: { /* // Blessed Life if (auraSpellInfo->SpellIconID == 2137) { switch (auraSpellInfo->Id) { case 31828: // Rank 1 case 31829: // Rank 2 case 31830: // Rank 3 break; default: sLog.outError("Unit::HandleProcTriggerSpellAuraProc: Spell %u miss posibly Blessed Life", auraSpellInfo->Id); return SPELL_AURA_PROC_FAILED; } } */ // Healing Discount if (auraSpellInfo->Id==37705) { trigger_spell_id = 37706; target = this; } // Soul Preserver if (auraSpellInfo->Id==60510) { trigger_spell_id = 60515; target = this; } // Illumination else if (auraSpellInfo->SpellIconID==241) { if(!procSpell) return SPELL_AURA_PROC_FAILED; // procspell is triggered spell but we need mana cost of original casted spell uint32 originalSpellId = procSpell->Id; // Holy Shock heal if (procSpell->SpellFamilyFlags & UI64LIT(0x0001000000000000)) { switch(procSpell->Id) { case 25914: originalSpellId = 20473; break; case 25913: originalSpellId = 20929; break; case 25903: originalSpellId = 20930; break; case 27175: originalSpellId = 27174; break; case 33074: originalSpellId = 33072; break; case 48820: originalSpellId = 48824; break; case 48821: originalSpellId = 48825; break; default: sLog.outError("Unit::HandleProcTriggerSpellAuraProc: Spell %u not handled in HShock",procSpell->Id); return SPELL_AURA_PROC_FAILED; } } SpellEntry const *originalSpell = sSpellStore.LookupEntry(originalSpellId); if(!originalSpell) { sLog.outError("Unit::HandleProcTriggerSpellAuraProc: Spell %u unknown but selected as original in Illu",originalSpellId); return SPELL_AURA_PROC_FAILED; } // percent stored in effect 1 (class scripts) base points int32 cost = originalSpell->manaCost + originalSpell->ManaCostPercentage * GetCreateMana() / 100; basepoints[0] = cost*auraSpellInfo->CalculateSimpleValue(EFFECT_INDEX_1)/100; trigger_spell_id = 20272; target = this; } // Lightning Capacitor else if (auraSpellInfo->Id==37657) { if(!pVictim || !pVictim->isAlive()) return SPELL_AURA_PROC_FAILED; // stacking CastSpell(this, 37658, true, NULL, triggeredByAura); Aura * dummy = GetDummyAura(37658); // release at 3 aura in stack (cont contain in basepoint of trigger aura) if(!dummy || dummy->GetStackAmount() < uint32(triggerAmount)) return SPELL_AURA_PROC_FAILED; RemoveAurasDueToSpell(37658); trigger_spell_id = 37661; target = pVictim; } // Bonus Healing (Crystal Spire of Karabor mace) else if (auraSpellInfo->Id == 40971) { // If your target is below $s1% health if (pVictim->GetHealth() > pVictim->GetMaxHealth() * triggerAmount / 100) return SPELL_AURA_PROC_FAILED; } // Thunder Capacitor else if (auraSpellInfo->Id == 54841) { if(!pVictim || !pVictim->isAlive()) return SPELL_AURA_PROC_FAILED; // stacking CastSpell(this, 54842, true, NULL, triggeredByAura); // counting Aura * dummy = GetDummyAura(54842); // release at 3 aura in stack (cont contain in basepoint of trigger aura) if(!dummy || dummy->GetStackAmount() < uint32(triggerAmount)) return SPELL_AURA_PROC_FAILED; RemoveAurasDueToSpell(54842); trigger_spell_id = 54843; target = pVictim; } break; } case SPELLFAMILY_SHAMAN: { // Lightning Shield (overwrite non existing triggered spell call in spell.dbc if (auraSpellInfo->SpellFamilyFlags & UI64LIT(0x0000000000000400) && auraSpellInfo->SpellVisual[0] == 37) { switch(auraSpellInfo->Id) { case 324: // Rank 1 trigger_spell_id = 26364; break; case 325: // Rank 2 trigger_spell_id = 26365; break; case 905: // Rank 3 trigger_spell_id = 26366; break; case 945: // Rank 4 trigger_spell_id = 26367; break; case 8134: // Rank 5 trigger_spell_id = 26369; break; case 10431: // Rank 6 trigger_spell_id = 26370; break; case 10432: // Rank 7 trigger_spell_id = 26363; break; case 25469: // Rank 8 trigger_spell_id = 26371; break; case 25472: // Rank 9 trigger_spell_id = 26372; break; case 49280: // Rank 10 trigger_spell_id = 49278; break; case 49281: // Rank 11 trigger_spell_id = 49279; break; default: sLog.outError("Unit::HandleProcTriggerSpellAuraProc: Spell %u not handled in LShield", auraSpellInfo->Id); return SPELL_AURA_PROC_FAILED; } } // Lightning Shield (The Ten Storms set) else if (auraSpellInfo->Id == 23551) { trigger_spell_id = 23552; target = pVictim; } // Damage from Lightning Shield (The Ten Storms set) else if (auraSpellInfo->Id == 23552) trigger_spell_id = 27635; // Mana Surge (The Earthfury set) else if (auraSpellInfo->Id == 23572) { if(!procSpell) return SPELL_AURA_PROC_FAILED; basepoints[0] = procSpell->manaCost * 35 / 100; trigger_spell_id = 23571; target = this; } // Nature's Guardian else if (auraSpellInfo->SpellIconID == 2013) { // Check health condition - should drop to less 30% (damage deal after this!) if (!(10*(int32(GetHealth() - damage)) < int32(3 * GetMaxHealth()))) return SPELL_AURA_PROC_FAILED; if(pVictim && pVictim->isAlive()) pVictim->getThreatManager().modifyThreatPercent(this,-10); basepoints[0] = triggerAmount * GetMaxHealth() / 100; trigger_spell_id = 31616; target = this; } // Item - Shaman T10 Restoration 2P Bonus else if (auraSpellInfo->Id == 70807) { if (!procSpell) return SPELL_AURA_PROC_FAILED; // only allow Riptide to proc switch(procSpell->Id) { case 61295: // Rank 1 case 61299: // Rank 2 case 61300: // Rank 3 case 61301: // Rank 4 break; default: return SPELL_AURA_PROC_FAILED; } trigger_spell_id = 70806; target = this; } break; } case SPELLFAMILY_DEATHKNIGHT: { // Acclimation if (auraSpellInfo->SpellIconID == 1930) { if (!procSpell) return SPELL_AURA_PROC_FAILED; switch(GetFirstSchoolInMask(GetSpellSchoolMask(procSpell))) { case SPELL_SCHOOL_NORMAL: return SPELL_AURA_PROC_FAILED; // ignore case SPELL_SCHOOL_HOLY: trigger_spell_id = 50490; break; case SPELL_SCHOOL_FIRE: trigger_spell_id = 50362; break; case SPELL_SCHOOL_NATURE: trigger_spell_id = 50488; break; case SPELL_SCHOOL_FROST: trigger_spell_id = 50485; break; case SPELL_SCHOOL_SHADOW: trigger_spell_id = 50489; break; case SPELL_SCHOOL_ARCANE: trigger_spell_id = 50486; break; default: return SPELL_AURA_PROC_FAILED; } } // Glyph of Death's Embrace else if (auraSpellInfo->Id == 58677) { if (procSpell->Id != 47633) return SPELL_AURA_PROC_FAILED; } //Glyph of Death Grip if (auraSpellInfo->Id == 62259) { //remove cooldown of Death Grip if (GetTypeId() == TYPEID_PLAYER) ((Player*)this)->RemoveSpellCooldown(49576, true); return SPELL_AURA_PROC_OK; } // Item - Death Knight T10 Melee 4P Bonus else if (auraSpellInfo->Id == 70656) { if (GetTypeId() != TYPEID_PLAYER || getClass() != CLASS_DEATH_KNIGHT) return SPELL_AURA_PROC_FAILED; for(uint32 i = 0; i < MAX_RUNES; ++i) if (((Player*)this)->GetRuneCooldown(i) == 0) return SPELL_AURA_PROC_FAILED; } // Blade Barrier else if (auraSpellInfo->SpellIconID == 85) { if (GetTypeId() != TYPEID_PLAYER || getClass() != CLASS_DEATH_KNIGHT || !((Player*)this)->IsBaseRuneSlotsOnCooldown(RUNE_BLOOD)) return SPELL_AURA_PROC_FAILED; } // Improved Blood Presence else if (auraSpellInfo->Id == 63611) { if (GetTypeId() != TYPEID_PLAYER || !((Player*)this)->isHonorOrXPTarget(pVictim) || !damage) return SPELL_AURA_PROC_FAILED; basepoints[0] = triggerAmount * damage / 100; trigger_spell_id = 50475; } // Glyph of Death's Embrace else if (auraSpellInfo->Id == 58677) { if (procSpell->Id != 47633) return SPELL_AURA_PROC_FAILED; } break; } default: break; } // All ok. Check current trigger spell SpellEntry const* triggerEntry = sSpellStore.LookupEntry(trigger_spell_id); if (!triggerEntry) { // Not cast unknown spell // sLog.outError("Unit::HandleProcTriggerSpellAuraProc: Spell %u have 0 in EffectTriggered[%d], not handled custom case?",auraSpellInfo->Id,triggeredByAura->GetEffIndex()); return SPELL_AURA_PROC_FAILED; } // not allow proc extra attack spell at extra attack if (m_extraAttacks && IsSpellHaveEffect(triggerEntry, SPELL_EFFECT_ADD_EXTRA_ATTACKS)) return SPELL_AURA_PROC_FAILED; // Custom basepoints/target for exist spell // dummy basepoints or other customs switch(trigger_spell_id) { // Cast positive spell on enemy target case 7099: // Curse of Mending case 39647: // Curse of Mending case 29494: // Temptation case 20233: // Improved Lay on Hands (cast on target) { target = pVictim; break; } // Combo points add triggers (need add combopoint only for main target, and after possible combopoints reset) case 15250: // Rogue Setup { if(!pVictim || pVictim != getVictim()) // applied only for main target return SPELL_AURA_PROC_FAILED; break; // continue normal case } // Finishing moves that add combo points case 14189: // Seal Fate (Netherblade set) case 14157: // Ruthlessness case 70802: // Mayhem (Shadowblade sets) { // Need add combopoint AFTER finishing move (or they get dropped in finish phase) if (Spell* spell = GetCurrentSpell(CURRENT_GENERIC_SPELL)) { spell->AddTriggeredSpell(trigger_spell_id); return SPELL_AURA_PROC_OK; } return SPELL_AURA_PROC_FAILED; } // Bloodthirst (($m/100)% of max health) case 23880: { basepoints[0] = int32(GetMaxHealth() * triggerAmount / 100); break; } // Shamanistic Rage triggered spell case 30824: { basepoints[0] = int32(GetTotalAttackPowerValue(BASE_ATTACK) * triggerAmount / 100); break; } // Enlightenment (trigger only from mana cost spells) case 35095: { if(!procSpell || procSpell->powerType!=POWER_MANA || procSpell->manaCost==0 && procSpell->ManaCostPercentage==0 && procSpell->manaCostPerlevel==0) return SPELL_AURA_PROC_FAILED; break; } // Demonic Pact case 48090: { // As the spell is proced from pet's attack - find owner Unit* owner = GetOwner(); if (!owner || owner->GetTypeId() != TYPEID_PLAYER) return SPELL_AURA_PROC_FAILED; // This spell doesn't stack, but refreshes duration. So we receive current bonuses to minus them later. int32 curBonus = 0; if (Aura* aur = owner->GetAura(48090, EFFECT_INDEX_0)) curBonus = aur->GetModifier()->m_amount; int32 spellDamage = owner->SpellBaseDamageBonusDone(SPELL_SCHOOL_MASK_MAGIC) - curBonus; if(spellDamage <= 0) return SPELL_AURA_PROC_FAILED; // percent stored in owner talent dummy AuraList const& dummyAuras = owner->GetAurasByType(SPELL_AURA_DUMMY); for (AuraList::const_iterator i = dummyAuras.begin(); i != dummyAuras.end(); ++i) { if ((*i)->GetSpellProto()->SpellIconID == 3220) { basepoints[0] = basepoints[1] = int32(spellDamage * (*i)->GetModifier()->m_amount / 100); break; } } break; } // Sword and Board case 50227: { // Remove cooldown on Shield Slam if (GetTypeId() == TYPEID_PLAYER) ((Player*)this)->RemoveSpellCategoryCooldown(1209, true); break; } // Maelstrom Weapon case 53817: { // Item - Shaman T10 Enhancement 4P Bonus // Calculate before roll_chance of ranks if (Aura * dummy = GetDummyAura(70832)) { if (SpellAuraHolder *aurHolder = GetSpellAuraHolder(53817)) if ((aurHolder->GetStackAmount() == aurHolder->GetSpellProto()->StackAmount) && roll_chance_i(dummy->GetBasePoints())) CastSpell(this,70831,true,castItem,triggeredByAura); } // have rank dependent proc chance, ignore too often cases // PPM = 2.5 * (rank of talent), uint32 rank = sSpellMgr.GetSpellRank(auraSpellInfo->Id); // 5 rank -> 100% 4 rank -> 80% and etc from full rate if(!roll_chance_i(20*rank)) return SPELL_AURA_PROC_FAILED; // Item - Shaman T10 Enhancement 4P Bonus if (Aura *aur = GetAura(70832, EFFECT_INDEX_0)) { Aura *maelBuff = GetAura(trigger_spell_id, EFFECT_INDEX_0); if (maelBuff && maelBuff->GetStackAmount() + 1 == maelBuff->GetSpellProto()->StackAmount) if (roll_chance_i(aur->GetModifier()->m_amount)) CastSpell(this, 70831, true, NULL, aur); } break; } // Brain Freeze case 57761: { if(!procSpell) return SPELL_AURA_PROC_FAILED; // For trigger from Blizzard need exist Improved Blizzard if (procSpell->SpellFamilyName==SPELLFAMILY_MAGE && (procSpell->SpellFamilyFlags & UI64LIT(0x0000000000000080))) { bool found = false; AuraList const& mOverrideClassScript = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS); for(AuraList::const_iterator i = mOverrideClassScript.begin(); i != mOverrideClassScript.end(); ++i) { int32 script = (*i)->GetModifier()->m_miscvalue; if(script==836 || script==988 || script==989) { found=true; break; } } if(!found) return SPELL_AURA_PROC_FAILED; } break; } // Astral Shift case 52179: { if (procSpell == 0 || !(procEx & (PROC_EX_NORMAL_HIT|PROC_EX_CRITICAL_HIT)) || this == pVictim) return SPELL_AURA_PROC_FAILED; // Need stun, fear or silence mechanic if (!(GetAllSpellMechanicMask(procSpell) & IMMUNE_TO_SILENCE_AND_STUN_AND_FEAR_MASK)) return SPELL_AURA_PROC_FAILED; break; } // Burning Determination case 54748: { if(!procSpell) return SPELL_AURA_PROC_FAILED; // Need Interrupt or Silenced mechanic if (!(GetAllSpellMechanicMask(procSpell) & IMMUNE_TO_INTERRUPT_AND_SILENCE_MASK)) return SPELL_AURA_PROC_FAILED; break; } // Lock and Load case 56453: { // Proc only from trap activation (from periodic proc another aura of this spell) // because some spells have both flags (ON_TRAP_ACTIVATION and ON_PERIODIC), but should only proc ON_PERIODIC!! if (!(procFlags & PROC_FLAG_ON_TRAP_ACTIVATION) || !procSpell || !(procSpell->SchoolMask & SPELL_SCHOOL_MASK_FROST) || !roll_chance_i(triggerAmount)) return SPELL_AURA_PROC_FAILED; break; } // Freezing Fog (Rime triggered) case 59052: { // Howling Blast cooldown reset if (GetTypeId() == TYPEID_PLAYER) ((Player*)this)->RemoveSpellCategoryCooldown(1248, true); break; } // Druid - Savage Defense case 62606: { basepoints[0] = int32(GetTotalAttackPowerValue(BASE_ATTACK) * triggerAmount / 100); break; } // Hack for Blood mark (ICC Saurfang) case 72255: case 72444: case 72445: case 72446: { float radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(auraSpellInfo->EffectRadiusIndex[EFFECT_INDEX_0])); Map::PlayerList const& pList = GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator itr = pList.begin(); itr != pList.end(); ++itr) if (itr->getSource() && itr->getSource()->IsWithinDistInMap(this,radius) && itr->getSource()->HasAura(triggerEntry->targetAuraSpell)) { target = itr->getSource(); break; } break; } } if (cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(trigger_spell_id)) return SPELL_AURA_PROC_FAILED; // try detect target manually if not set if (target == NULL) target = !(procFlags & PROC_FLAG_SUCCESSFUL_POSITIVE_SPELL) && IsPositiveSpell(trigger_spell_id) ? this : pVictim; // default case if (!target || (target != this && !target->isAlive())) return SPELL_AURA_PROC_FAILED; if (SpellEntry const* triggeredSpellInfo = sSpellStore.LookupEntry(trigger_spell_id)) { if (basepoints[EFFECT_INDEX_0] || basepoints[EFFECT_INDEX_1] || basepoints[EFFECT_INDEX_2]) CastCustomSpell(target,triggeredSpellInfo, basepoints[EFFECT_INDEX_0] ? &basepoints[EFFECT_INDEX_0] : NULL, basepoints[EFFECT_INDEX_1] ? &basepoints[EFFECT_INDEX_1] : NULL, basepoints[EFFECT_INDEX_2] ? &basepoints[EFFECT_INDEX_2] : NULL, true, castItem, triggeredByAura); else CastSpell(target,triggeredSpellInfo,true,castItem,triggeredByAura); } else { sLog.outError("HandleProcTriggerSpellAuraProc: unknown spell id %u by caster: %s triggered by aura %u (eff %u)", trigger_spell_id, GetGuidStr().c_str(), triggeredByAura->GetId(), triggeredByAura->GetEffIndex()); return SPELL_AURA_PROC_FAILED; } if (cooldown && GetTypeId()==TYPEID_PLAYER) ((Player*)this)->AddSpellCooldown(trigger_spell_id,0,time(NULL) + cooldown); return SPELL_AURA_PROC_OK; } SpellAuraProcResult Unit::HandleProcTriggerDamageAuraProc(Unit *pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlags, uint32 procEx, uint32 cooldown) { SpellEntry const *spellInfo = triggeredByAura->GetSpellProto(); DEBUG_FILTER_LOG(LOG_FILTER_SPELL_CAST, "ProcDamageAndSpell: doing %u damage from spell id %u (triggered by auratype %u of spell %u)", triggeredByAura->GetModifier()->m_amount, spellInfo->Id, triggeredByAura->GetModifier()->m_auraname, triggeredByAura->GetId()); SpellNonMeleeDamage damageInfo(this, pVictim, spellInfo->Id, SpellSchoolMask(spellInfo->SchoolMask)); CalculateSpellDamage(&damageInfo, triggeredByAura->GetModifier()->m_amount, spellInfo); damageInfo.target->CalculateAbsorbResistBlock(this, &damageInfo, spellInfo); DealDamageMods(damageInfo.target,damageInfo.damage,&damageInfo.absorb); SendSpellNonMeleeDamageLog(&damageInfo); DealSpellDamage(&damageInfo, true); return SPELL_AURA_PROC_OK; } SpellAuraProcResult Unit::HandleOverrideClassScriptAuraProc(Unit *pVictim, uint32 /*damage*/, Aura *triggeredByAura, SpellEntry const *procSpell, uint32 /*procFlag*/, uint32 /*procEx*/ ,uint32 cooldown) { int32 scriptId = triggeredByAura->GetModifier()->m_miscvalue; if(!pVictim || !pVictim->isAlive()) return SPELL_AURA_PROC_FAILED; Item* castItem = !triggeredByAura->GetCastItemGuid().IsEmpty() && GetTypeId()==TYPEID_PLAYER ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGuid()) : NULL; // Basepoints of trigger aura int32 triggerAmount = triggeredByAura->GetModifier()->m_amount; uint32 triggered_spell_id = 0; switch(scriptId) { case 836: // Improved Blizzard (Rank 1) { if (!procSpell || procSpell->SpellVisual[0]!=9487) return SPELL_AURA_PROC_FAILED; triggered_spell_id = 12484; break; } case 988: // Improved Blizzard (Rank 2) { if (!procSpell || procSpell->SpellVisual[0]!=9487) return SPELL_AURA_PROC_FAILED; triggered_spell_id = 12485; break; } case 989: // Improved Blizzard (Rank 3) { if (!procSpell || procSpell->SpellVisual[0]!=9487) return SPELL_AURA_PROC_FAILED; triggered_spell_id = 12486; break; } case 4086: // Improved Mend Pet (Rank 1) case 4087: // Improved Mend Pet (Rank 2) { if(!roll_chance_i(triggerAmount)) return SPELL_AURA_PROC_FAILED; triggered_spell_id = 24406; break; } case 4533: // Dreamwalker Raiment 2 pieces bonus { // Chance 50% if (!roll_chance_i(50)) return SPELL_AURA_PROC_FAILED; switch (pVictim->getPowerType()) { case POWER_MANA: triggered_spell_id = 28722; break; case POWER_RAGE: triggered_spell_id = 28723; break; case POWER_ENERGY: triggered_spell_id = 28724; break; default: return SPELL_AURA_PROC_FAILED; } break; } case 4537: // Dreamwalker Raiment 6 pieces bonus triggered_spell_id = 28750; // Blessing of the Claw break; case 5497: // Improved Mana Gems (Serpent-Coil Braid) triggered_spell_id = 37445; // Mana Surge break; case 6953: // Warbringer RemoveAurasAtMechanicImmunity(IMMUNE_TO_ROOT_AND_SNARE_MASK,0,true); return SPELL_AURA_PROC_OK; case 7010: // Revitalize (rank 1) case 7011: // Revitalize (rank 2) case 7012: // Revitalize (rank 3) { if(!roll_chance_i(triggerAmount)) return SPELL_AURA_PROC_FAILED; switch( pVictim->getPowerType() ) { case POWER_MANA: triggered_spell_id = 48542; break; case POWER_RAGE: triggered_spell_id = 48541; break; case POWER_ENERGY: triggered_spell_id = 48540; break; case POWER_RUNIC_POWER: triggered_spell_id = 48543; break; default: return SPELL_AURA_PROC_FAILED; } break; } case 7282: // Crypt Fever & Ebon Plaguebringer { if (!procSpell || pVictim == this) return SPELL_AURA_PROC_FAILED; bool HasEP = false; Unit::AuraList const& scriptAuras = GetAurasByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS); for(Unit::AuraList::const_iterator i = scriptAuras.begin(); i != scriptAuras.end(); ++i) { if ((*i)->GetSpellProto()->SpellIconID == 1766) { HasEP = true; break; } } if (!HasEP) switch(triggeredByAura->GetId()) { case 49032: triggered_spell_id = 50508; break; case 49631: triggered_spell_id = 50509; break; case 49632: triggered_spell_id = 50510; break; default: return SPELL_AURA_PROC_FAILED; } else switch(triggeredByAura->GetId()) { case 51099: triggered_spell_id = 51726; break; case 51160: triggered_spell_id = 51734; break; case 51161: triggered_spell_id = 51735; break; default: return SPELL_AURA_PROC_FAILED; } break; } } // not processed if(!triggered_spell_id) return SPELL_AURA_PROC_FAILED; // standard non-dummy case SpellEntry const* triggerEntry = sSpellStore.LookupEntry(triggered_spell_id); if(!triggerEntry) { sLog.outError("Unit::HandleOverrideClassScriptAuraProc: Spell %u triggering for class script id %u",triggered_spell_id,scriptId); return SPELL_AURA_PROC_FAILED; } if( cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(triggered_spell_id)) return SPELL_AURA_PROC_FAILED; CastSpell(pVictim, triggered_spell_id, true, castItem, triggeredByAura); if( cooldown && GetTypeId()==TYPEID_PLAYER ) ((Player*)this)->AddSpellCooldown(triggered_spell_id,0,time(NULL) + cooldown); return SPELL_AURA_PROC_OK; } SpellAuraProcResult Unit::HandleMendingAuraProc( Unit* /*pVictim*/, uint32 /*damage*/, Aura* triggeredByAura, SpellEntry const* /*procSpell*/, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 /*cooldown*/ ) { // aura can be deleted at casts SpellEntry const* spellProto = triggeredByAura->GetSpellProto(); SpellEffectIndex effIdx = triggeredByAura->GetEffIndex(); int32 heal = triggeredByAura->GetModifier()->m_amount; ObjectGuid caster_guid = triggeredByAura->GetCasterGuid(); // jumps int32 jumps = triggeredByAura->GetHolder()->GetAuraCharges()-1; // current aura expire triggeredByAura->GetHolder()->SetAuraCharges(1); // will removed at next charges decrease // next target selection if (jumps > 0 && GetTypeId()==TYPEID_PLAYER && caster_guid.IsPlayer()) { float radius; if (spellProto->EffectRadiusIndex[effIdx]) radius = GetSpellRadius(sSpellRadiusStore.LookupEntry(spellProto->EffectRadiusIndex[effIdx])); else radius = GetSpellMaxRange(sSpellRangeStore.LookupEntry(spellProto->rangeIndex)); if(Player* caster = ((Player*)triggeredByAura->GetCaster())) { caster->ApplySpellMod(spellProto->Id, SPELLMOD_RADIUS, radius,NULL); if(Player* target = ((Player*)this)->GetNextRandomRaidMember(radius)) { // aura will applied from caster, but spell casted from current aura holder SpellModifier *mod = new SpellModifier(SPELLMOD_CHARGES,SPELLMOD_FLAT,jumps-5,spellProto->Id,spellProto->SpellFamilyFlags,spellProto->SpellFamilyFlags2); // remove before apply next (locked against deleted) triggeredByAura->SetInUse(true); RemoveAurasByCasterSpell(spellProto->Id,caster->GetGUID()); caster->AddSpellMod(mod, true); CastCustomSpell(target,spellProto->Id,&heal,NULL,NULL,true,NULL,triggeredByAura,caster->GetGUID()); caster->AddSpellMod(mod, false); triggeredByAura->SetInUse(false); } } } // heal CastCustomSpell(this,33110,&heal,NULL,NULL,true,NULL,NULL,caster_guid); return SPELL_AURA_PROC_OK; } SpellAuraProcResult Unit::HandleModCastingSpeedNotStackAuraProc(Unit* /*pVictim*/, uint32 /*damage*/, Aura* /*triggeredByAura*/, SpellEntry const* procSpell, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 /*cooldown*/) { // Skip melee hits or instant cast spells return !(procSpell == NULL || GetSpellCastTime(procSpell) == 0) ? SPELL_AURA_PROC_OK : SPELL_AURA_PROC_FAILED; } SpellAuraProcResult Unit::HandleReflectSpellsSchoolAuraProc(Unit* /*pVictim*/, uint32 /*damage*/, Aura* triggeredByAura, SpellEntry const* procSpell, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 /*cooldown*/) { // Skip Melee hits and spells ws wrong school return !(procSpell == NULL || (triggeredByAura->GetModifier()->m_miscvalue & procSpell->SchoolMask) == 0) ? SPELL_AURA_PROC_OK : SPELL_AURA_PROC_FAILED; } SpellAuraProcResult Unit::HandleModPowerCostSchoolAuraProc(Unit* /*pVictim*/, uint32 /*damage*/, Aura* triggeredByAura, SpellEntry const* procSpell, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 /*cooldown*/) { // Skip melee hits and spells ws wrong school or zero cost return !(procSpell == NULL || (procSpell->manaCost == 0 && procSpell->ManaCostPercentage == 0) || // Cost check (triggeredByAura->GetModifier()->m_miscvalue & procSpell->SchoolMask) == 0) ? SPELL_AURA_PROC_OK : SPELL_AURA_PROC_FAILED; // School check } SpellAuraProcResult Unit::HandleMechanicImmuneResistanceAuraProc(Unit* /*pVictim*/, uint32 /*damage*/, Aura* triggeredByAura, SpellEntry const* procSpell, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 /*cooldown*/) { // Compare mechanic return !(procSpell==NULL || int32(procSpell->Mechanic) != triggeredByAura->GetModifier()->m_miscvalue) ? SPELL_AURA_PROC_OK : SPELL_AURA_PROC_FAILED; } SpellAuraProcResult Unit::HandleModDamageFromCasterAuraProc(Unit* pVictim, uint32 /*damage*/, Aura* triggeredByAura, SpellEntry const* /*procSpell*/, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 /*cooldown*/) { // Compare casters return triggeredByAura->GetCasterGuid() == pVictim->GetObjectGuid() ? SPELL_AURA_PROC_OK : SPELL_AURA_PROC_FAILED; } SpellAuraProcResult Unit::HandleAddFlatModifierAuraProc(Unit* /*pVictim*/, uint32 /*damage*/, Aura* triggeredByAura, SpellEntry const * /*procSpell*/, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 /*cooldown*/) { SpellEntry const *spellInfo = triggeredByAura->GetSpellProto(); if (spellInfo->Id == 55166) // Tidal Force { // Remove only single aura from stack if (triggeredByAura->GetStackAmount() > 1 && !triggeredByAura->GetHolder()->ModStackAmount(-1)) return SPELL_AURA_PROC_CANT_TRIGGER; } return SPELL_AURA_PROC_OK; } SpellAuraProcResult Unit::HandleAddPctModifierAuraProc(Unit* /*pVictim*/, uint32 /*damage*/, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 /*procFlag*/, uint32 procEx, uint32 /*cooldown*/) { SpellEntry const *spellInfo = triggeredByAura->GetSpellProto(); Item* castItem = !triggeredByAura->GetCastItemGuid().IsEmpty() && GetTypeId()==TYPEID_PLAYER ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGuid()) : NULL; switch(spellInfo->SpellFamilyName) { case SPELLFAMILY_MAGE: { // Combustion if (spellInfo->Id == 11129) { //last charge and crit if (triggeredByAura->GetHolder()->GetAuraCharges() <= 1 && (procEx & PROC_EX_CRITICAL_HIT) ) return SPELL_AURA_PROC_OK; // charge counting (will removed) CastSpell(this, 28682, true, castItem, triggeredByAura); return (procEx & PROC_EX_CRITICAL_HIT) ? SPELL_AURA_PROC_OK : SPELL_AURA_PROC_FAILED; // charge update only at crit hits, no hidden cooldowns } break; } case SPELLFAMILY_PRIEST: { // Serendipity if (spellInfo->SpellIconID == 2900) { RemoveAurasDueToSpell(spellInfo->Id); return SPELL_AURA_PROC_OK; } break; } case SPELLFAMILY_PALADIN: { // Glyph of Divinity if (spellInfo->Id == 11129) { // Lookup base amount mana restore for (int i = 0; i < MAX_EFFECT_INDEX; ++i) { if (procSpell->Effect[i] == SPELL_EFFECT_ENERGIZE) { int32 mana = procSpell->CalculateSimpleValue(SpellEffectIndex(i)); CastCustomSpell(this, 54986, NULL, &mana, NULL, true, castItem, triggeredByAura); break; } } return SPELL_AURA_PROC_OK; } break; } } return SPELL_AURA_PROC_OK; } SpellAuraProcResult Unit::HandleModDamagePercentDoneAuraProc(Unit* /*pVictim*/, uint32 /*damage*/, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 /*procFlag*/, uint32 procEx, uint32 cooldown) { SpellEntry const *spellInfo = triggeredByAura->GetSpellProto(); Item* castItem = !triggeredByAura->GetCastItemGuid().IsEmpty() && GetTypeId()==TYPEID_PLAYER ? ((Player*)this)->GetItemByGuid(triggeredByAura->GetCastItemGuid()) : NULL; // Aspect of the Viper if (spellInfo->SpellFamilyName == SPELLFAMILY_HUNTER && spellInfo->SpellFamilyFlags & UI64LIT(0x4000000000000)) { uint32 maxmana = GetMaxPower(POWER_MANA); int32 bp = int32(maxmana* GetAttackTime(RANGED_ATTACK)/1000.0f/100.0f); if(cooldown && GetTypeId()==TYPEID_PLAYER && ((Player*)this)->HasSpellCooldown(34075)) return SPELL_AURA_PROC_FAILED; CastCustomSpell(this, 34075, &bp, NULL, NULL, true, castItem, triggeredByAura); } // Arcane Blast else if (spellInfo->Id == 36032 && procSpell->SpellFamilyName == SPELLFAMILY_MAGE && procSpell->SpellIconID == 2294) // prevent proc from self(spell that triggered this aura) return SPELL_AURA_PROC_FAILED; return SPELL_AURA_PROC_OK; } SpellAuraProcResult Unit::HandlePeriodicDummyAuraProc(Unit* /*pVictim*/, uint32 /*damage*/, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 /*cooldown*/) { if (!triggeredByAura) return SPELL_AURA_PROC_FAILED; SpellEntry const *spellProto = triggeredByAura->GetSpellProto(); if (!spellProto) return SPELL_AURA_PROC_FAILED; switch (spellProto->SpellFamilyName) { case SPELLFAMILY_DEATHKNIGHT: { switch (spellProto->SpellIconID) { // Reaping // Death Rune Mastery // Blood of the North case 22: case 2622: case 3041: { if(!procSpell) return SPELL_AURA_PROC_FAILED; if (getClass() != CLASS_DEATH_KNIGHT) return SPELL_AURA_PROC_FAILED; Player * plr = GetTypeId() == TYPEID_PLAYER? ((Player*)this) : NULL; if (!plr) return SPELL_AURA_PROC_FAILED; //get spell rune cost SpellRuneCostEntry const *runeCost = sSpellRuneCostStore.LookupEntry(procSpell->runeCostID); if (!runeCost) return SPELL_AURA_PROC_FAILED; //convert runes to death for (uint32 i = 0; i < NUM_RUNE_TYPES -1/*don't count death rune*/; ++i) { uint32 remainingCost = runeCost->RuneCost[i]; while(remainingCost) { int32 convertedRuneCooldown = -1; uint32 convertedRune = i; for(uint32 j = 0; j < MAX_RUNES; ++j) { // convert only valid runes if (RuneType(i) != plr->GetCurrentRune(j) && RuneType(i) != plr->GetBaseRune(j)) continue; // select rune with longest cooldown if (convertedRuneCooldown < plr->GetRuneCooldown(j)) { convertedRuneCooldown = int32(plr->GetRuneCooldown(j)); convertedRune = j; } } if (convertedRuneCooldown >= 0) plr->ConvertRune(convertedRune, RUNE_DEATH); --remainingCost; } } return SPELL_AURA_PROC_OK; } default: break; } break; } default: break; } return SPELL_AURA_PROC_OK; } SpellAuraProcResult Unit::HandleModRating(Unit* /*pVictim*/, uint32 /*damage*/, Aura* triggeredByAura, SpellEntry const * /*procSpell*/, uint32 /*procFlag*/, uint32 /*procEx*/, uint32 /*cooldown*/) { SpellEntry const *spellInfo = triggeredByAura->GetSpellProto(); if (spellInfo->Id == 71564) // Deadly Precision { // Remove only single aura from stack if (triggeredByAura->GetStackAmount() > 1 && !triggeredByAura->GetHolder()->ModStackAmount(-1)) return SPELL_AURA_PROC_CANT_TRIGGER; } return SPELL_AURA_PROC_OK; } SpellAuraProcResult Unit::HandleRemoveByDamageProc(Unit* pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown) { triggeredByAura->SetInUse(true); RemoveAurasByCasterSpell(triggeredByAura->GetSpellProto()->Id, triggeredByAura->GetCasterGUID()); triggeredByAura->SetInUse(false); return SPELL_AURA_PROC_OK; } SpellAuraProcResult Unit::HandleRemoveByDamageChanceProc(Unit* pVictim, uint32 damage, Aura* triggeredByAura, SpellEntry const *procSpell, uint32 procFlag, uint32 procEx, uint32 cooldown) { // The chance to dispel an aura depends on the damage taken with respect to the casters level. uint32 max_dmg = getLevel() > 8 ? 25 * getLevel() - 150 : 50; float chance = float(damage) / max_dmg * 100.0f; if (roll_chance_f(chance)) return HandleRemoveByDamageProc(pVictim, damage, triggeredByAura, procSpell, procFlag, procEx, cooldown); return SPELL_AURA_PROC_FAILED; }
lordaragorn/infinity_335
src/game/UnitAuraProcHandler.cpp
C++
gpl-2.0
228,258
# -*- coding: utf-8 -*- """ nidaba.plugins.leptonica ~~~~~~~~~~~~~~~~~~~~~~~~ Plugin accessing `leptonica <http://leptonica.com>`_ functions. This plugin requires a liblept shared object in the current library search path. On Debian-based systems it can be installed using apt-get .. code-block:: console # apt-get install libleptonica-dev Leptonica's APIs are rather unstable and may differ significantly between versions. If this plugin fails with weird error messages or workers are just dying without discernable cause please submit a bug report including your leptonica version. """ from __future__ import unicode_literals, print_function, absolute_import import ctypes from nidaba import storage from nidaba.celery import app from nidaba.tasks.helper import NidabaTask from nidaba.nidabaexceptions import (NidabaInvalidParameterException, NidabaLeptonicaException, NidabaPluginException) leptlib = 'liblept.so' def setup(*args, **kwargs): try: ctypes.cdll.LoadLibrary(leptlib) except Exception as e: raise NidabaPluginException(e.message) @app.task(base=NidabaTask, name=u'nidaba.binarize.sauvola', arg_values={'whsize': 'int', 'factor': (0.0, 1.0)}) def sauvola(doc, method=u'sauvola', whsize=10, factor=0.35): """ Binarizes an input document utilizing Sauvola thresholding as described in [0]. Expects 8bpp grayscale images as input. [0] Sauvola, Jaakko, and Matti Pietikäinen. "Adaptive document image binarization." Pattern recognition 33.2 (2000): 225-236. Args: doc (unicode): The input document tuple. method (unicode): The suffix string appended to all output files whsize (int): The window width and height that local statistics are calculated on are twice the value of whsize. The minimal value is 2. factor (float): The threshold reduction factor due to variance. 0 =< factor < 1. Returns: (unicode, unicode): Storage tuple of the output file Raises: NidabaInvalidParameterException: Input parameters are outside the valid range. """ input_path = storage.get_abs_path(*doc) output_path = storage.insert_suffix(input_path, method, unicode(whsize), unicode(factor)) lept_sauvola(input_path, output_path, whsize, factor) return storage.get_storage_path(output_path) def lept_sauvola(image_path, output_path, whsize=10, factor=0.35): """ Binarizes an input document utilizing Sauvola thresholding as described in [0]. Expects 8bpp grayscale images as input. [0] Sauvola, Jaakko, and Matti Pietikäinen. "Adaptive document image binarization." Pattern recognition 33.2 (2000): 225-236. Args: image_path (unicode): Input image path output_path (unicode): Output image path whsize (int): The window width and height that local statistics are calculated on are twice the value of whsize. The minimal value is 2. factor (float): The threshold reduction factor due to variance. 0 =< factor < 1. Raises: NidabaInvalidParameterException: Input parameters are outside the valid range. """ if whsize < 2 or factor >= 1.0 or factor < 0: raise NidabaInvalidParameterException('Parameters ({}, {}) outside of valid range'.format(whsize, factor)) try: lept = ctypes.cdll.LoadLibrary(leptlib) except OSError as e: raise NidabaLeptonicaException('Loading leptonica failed: ' + e.message) pix = ctypes.c_void_p(lept.pixRead(image_path.encode('utf-8'))) opix = ctypes.c_void_p() if lept.pixGetDepth(pix) != 8: lept.pixDestroy(ctypes.byref(pix)) raise NidabaLeptonicaException('Input image is not grayscale') if lept.pixSauvolaBinarize(pix, whsize, ctypes.c_float(factor), 0, None, None, None, ctypes.byref(opix)): lept.pixDestroy(ctypes.byref(pix)) raise NidabaLeptonicaException('Binarization failed for unknown ' 'reason.') if lept.pixWriteImpliedFormat(output_path.encode('utf-8'), opix, 100, 0): lept.pixDestroy(ctypes.byref(pix)) lept.pixDestroy(ctypes.byref(pix)) raise NidabaLeptonicaException('Writing binarized PIX failed') lept.pixDestroy(ctypes.byref(opix)) lept.pixDestroy(ctypes.byref(pix)) @app.task(base=NidabaTask, name=u'nidaba.img.dewarp') def dewarp(doc, method=u'dewarp'): """ Removes perspective distortion (as commonly exhibited by overhead scans) from an 1bpp input image. Args: doc (unicode, unicode): The input document tuple. method (unicode): The suffix string appended to all output files. Returns: (unicode, unicode): Storage tuple of the output file """ input_path = storage.get_abs_path(*doc) output_path = storage.insert_suffix(input_path, method) lept_dewarp(input_path, output_path) return storage.get_storage_path(output_path) def lept_dewarp(image_path, output_path): """ Removes perspective distortion from an 1bpp input image. Args: image_path (unicode): Path to the input image output_path (unicode): Path to the output image Raises: NidabaLeptonicaException if one of leptonica's functions failed. """ try: lept = ctypes.cdll.LoadLibrary(leptlib) except OSError as e: raise NidabaLeptonicaException('Loading leptonica failed: ' + e.message) pix = ctypes.c_void_p(lept.pixRead(image_path.encode('utf-8'))) opix = ctypes.c_void_p() ret = lept.dewarpSinglePage(pix, 0, 1, 1, ctypes.byref(opix), None, 0) if ret == 1 or ret is None: lept.pixDestroy(ctypes.byref(pix)) lept.pixDestroy(ctypes.byref(opix)) raise NidabaLeptonicaException('Dewarping failed for unknown reason.') if lept.pixWriteImpliedFormat(output_path.encode('utf-8'), opix, 100, 0): lept.pixDestroy(ctypes.byref(pix)) lept.pixDestroy(ctypes.byref(opix)) raise NidabaLeptonicaException('Writing dewarped PIX failed') lept.pixDestroy(ctypes.byref(pix)) lept.pixDestroy(ctypes.byref(opix)) @app.task(base=NidabaTask, name=u'nidaba.img.deskew') def deskew(doc, method=u'deskew'): """ Removes skew (rotational distortion) from an 1bpp input image. Args: doc (unicode, unicode): The input document tuple. method (unicode): The suffix string appended to all output files. Returns: (unicode, unicode): Storage tuple of the output file """ input_path = storage.get_abs_path(*doc) output_path = storage.insert_suffix(input_path, method) lept_deskew(input_path, output_path) return storage.get_storage_path(output_path) def lept_deskew(image_path, output_path): """ Removes skew (rotational distortion from an 1bpp input image. Args: image_path (unicode): Input image output_path (unicode): Path to the output document Raises: NidabaLeptonicaException if one of leptonica's functions failed. """ try: lept = ctypes.cdll.LoadLibrary(leptlib) except OSError as e: raise NidabaLeptonicaException('Loading leptonica failed: ' + e.message) pix = ctypes.c_void_p(lept.pixRead(image_path.encode('utf-8'))) opix = ctypes.c_void_p(lept.pixFindSkewAndDeskew(pix, 4, None, None)) if opix is None: lept.pixDestroy(ctypes.byref(pix)) raise NidabaLeptonicaException('Deskewing failed for unknown reason.') if lept.pixWriteImpliedFormat(output_path.encode('utf-8'), opix, 100, 0): lept.pixDestroy(ctypes.byref(pix)) lept.pixDestroy(ctypes.byref(opix)) raise NidabaLeptonicaException('Writing deskewed PIX failed') lept.pixDestroy(ctypes.byref(pix)) lept.pixDestroy(ctypes.byref(opix))
OpenPhilology/nidaba
nidaba/plugins/leptonica.py
Python
gpl-2.0
8,246
/* * Copyright 2009-2012 Freescale Semiconductor, Inc. All Rights Reserved. */ /* * The code contained herein is licensed under the GNU General Public * License. You may obtain a copy of the GNU General Public License * Version 2 or later at the following locations: * * http://www.opensource.org/licenses/gpl-license.html * http://www.gnu.org/copyleft/gpl.html */ /*! * @file ipu_csi_enc.c * * @brief CSI Use case for video capture * * @ingroup IPU */ #include <linux/platform_device.h> #include <linux/dma-mapping.h> #include <linux/ipu.h> #include <mach/mipi_csi2.h> #include "mxc_v4l2_capture.h" #include "ipu_prp_sw.h" #ifdef CAMERA_DBG #define CAMERA_TRACE(x) (printk)x #else #define CAMERA_TRACE(x) #endif /* * Function definitions */ /*! * csi ENC callback function. * * @param irq int irq line * @param dev_id void * device id * * @return status IRQ_HANDLED for handled */ static irqreturn_t csi_enc_callback(int irq, void *dev_id) { cam_data *cam = (cam_data *) dev_id; if (cam->enc_callback == NULL) return IRQ_HANDLED; cam->enc_callback(irq, dev_id); return IRQ_HANDLED; } /*! * CSI ENC enable channel setup function * * @param cam struct cam_data * mxc capture instance * * @return status */ static int csi_enc_setup(cam_data *cam) { ipu_channel_params_t params; u32 pixel_fmt; int err = 0, sensor_protocol = 0; dma_addr_t dummy = cam->dummy_frame.buffer.m.offset; #ifdef CONFIG_MXC_MIPI_CSI2 void *mipi_csi2_info; int ipu_id; int csi_id; #endif CAMERA_TRACE("In csi_enc_setup\n"); if (!cam) { printk(KERN_ERR "cam private is NULL\n"); return -ENXIO; } memset(&params, 0, sizeof(ipu_channel_params_t)); params.csi_mem.csi = cam->csi; sensor_protocol = ipu_csi_get_sensor_protocol(cam->ipu, cam->csi); switch (sensor_protocol) { case IPU_CSI_CLK_MODE_GATED_CLK: case IPU_CSI_CLK_MODE_NONGATED_CLK: case IPU_CSI_CLK_MODE_CCIR656_PROGRESSIVE: case IPU_CSI_CLK_MODE_CCIR1120_PROGRESSIVE_DDR: case IPU_CSI_CLK_MODE_CCIR1120_PROGRESSIVE_SDR: params.csi_mem.interlaced = false; break; case IPU_CSI_CLK_MODE_CCIR656_INTERLACED: case IPU_CSI_CLK_MODE_CCIR1120_INTERLACED_DDR: case IPU_CSI_CLK_MODE_CCIR1120_INTERLACED_SDR: params.csi_mem.interlaced = true; break; default: printk(KERN_ERR "sensor protocol unsupported\n"); return -EINVAL; } if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_YUV420) pixel_fmt = IPU_PIX_FMT_YUV420P; else if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_YUV422P) pixel_fmt = IPU_PIX_FMT_YUV422P; else if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_UYVY) pixel_fmt = IPU_PIX_FMT_UYVY; else if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_YUYV) pixel_fmt = IPU_PIX_FMT_YUYV; else if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_NV12) pixel_fmt = IPU_PIX_FMT_NV12; else if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_BGR24) pixel_fmt = IPU_PIX_FMT_BGR24; else if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_RGB24) pixel_fmt = IPU_PIX_FMT_RGB24; else if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_RGB565) pixel_fmt = IPU_PIX_FMT_RGB565; else if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_BGR32) pixel_fmt = IPU_PIX_FMT_BGR32; else if (cam->v2f.fmt.pix.pixelformat == V4L2_PIX_FMT_RGB32) pixel_fmt = IPU_PIX_FMT_RGB32; else { printk(KERN_ERR "format not supported\n"); return -EINVAL; } #ifdef CONFIG_MXC_MIPI_CSI2 mipi_csi2_info = mipi_csi2_get_info(); if (mipi_csi2_info) { if (mipi_csi2_get_status(mipi_csi2_info)) { ipu_id = mipi_csi2_get_bind_ipu(mipi_csi2_info); csi_id = mipi_csi2_get_bind_csi(mipi_csi2_info); if (cam->ipu == ipu_get_soc(ipu_id) && cam->csi == csi_id) { params.csi_mem.mipi_en = true; params.csi_mem.mipi_vc = mipi_csi2_get_virtual_channel(mipi_csi2_info); params.csi_mem.mipi_id = mipi_csi2_get_datatype(mipi_csi2_info); mipi_csi2_pixelclk_enable(mipi_csi2_info); } else { params.csi_mem.mipi_en = false; params.csi_mem.mipi_vc = 0; params.csi_mem.mipi_id = 0; } } else { params.csi_mem.mipi_en = false; params.csi_mem.mipi_vc = 0; params.csi_mem.mipi_id = 0; } } else { printk(KERN_ERR "Fail to get mipi_csi2_info!\n"); return -EPERM; } #endif err = ipu_init_channel(cam->ipu, CSI_MEM, &params); if (err != 0) { printk(KERN_ERR "ipu_init_channel %d\n", err); return err; } err = ipu_init_channel_buffer(cam->ipu, CSI_MEM, IPU_OUTPUT_BUFFER, pixel_fmt, cam->v2f.fmt.pix.width, cam->v2f.fmt.pix.height, cam->v2f.fmt.pix.bytesperline, cam->rotation, dummy, dummy, 0, cam->offset.u_offset, cam->offset.v_offset); if (err != 0) { printk(KERN_ERR "CSI_MEM output buffer\n"); return err; } err = ipu_enable_channel(cam->ipu, CSI_MEM); if (err < 0) { printk(KERN_ERR "ipu_enable_channel CSI_MEM\n"); return err; } return err; } /*! * function to update physical buffer address for encorder IDMA channel * * @param eba physical buffer address for encorder IDMA channel * @param buffer_num int buffer 0 or buffer 1 * * @return status */ static int csi_enc_eba_update(struct ipu_soc *ipu, dma_addr_t eba, int *buffer_num) { int err = 0; pr_debug("eba %x\n", eba); err = ipu_update_channel_buffer(ipu, CSI_MEM, IPU_OUTPUT_BUFFER, *buffer_num, eba); if (err != 0) { ipu_clear_buffer_ready(ipu, CSI_MEM, IPU_OUTPUT_BUFFER, *buffer_num); err = ipu_update_channel_buffer(ipu, CSI_MEM, IPU_OUTPUT_BUFFER, *buffer_num, eba); if (err != 0) { pr_err("ERROR: v4l2 capture: fail to update " "buf%d\n", *buffer_num); return err; } } ipu_select_buffer(ipu, CSI_MEM, IPU_OUTPUT_BUFFER, *buffer_num); *buffer_num = (*buffer_num == 0) ? 1 : 0; return 0; } /*! * Enable encoder task * @param private struct cam_data * mxc capture instance * * @return status */ static int csi_enc_enabling_tasks(void *private) { cam_data *cam = (cam_data *) private; int err = 0; CAMERA_TRACE("IPU:In csi_enc_enabling_tasks\n"); if (cam->dummy_frame.vaddress && cam->dummy_frame.buffer.length < PAGE_ALIGN(cam->v2f.fmt.pix.sizeimage)) { dma_free_coherent(0, cam->dummy_frame.buffer.length, cam->dummy_frame.vaddress, cam->dummy_frame.paddress); cam->dummy_frame.vaddress = 0; } if (!cam->dummy_frame.vaddress) { cam->dummy_frame.vaddress = dma_alloc_coherent(0, PAGE_ALIGN(cam->v2f.fmt.pix.sizeimage), &cam->dummy_frame.paddress, GFP_DMA | GFP_KERNEL); if (cam->dummy_frame.vaddress == 0) { pr_err("ERROR: v4l2 capture: Allocate dummy frame " "failed.\n"); return -ENOBUFS; } cam->dummy_frame.buffer.length = PAGE_ALIGN(cam->v2f.fmt.pix.sizeimage); } cam->dummy_frame.buffer.type = V4L2_BUF_TYPE_PRIVATE; cam->dummy_frame.buffer.m.offset = cam->dummy_frame.paddress; ipu_clear_irq(cam->ipu, IPU_IRQ_CSI0_OUT_EOF); err = ipu_request_irq(cam->ipu, IPU_IRQ_CSI0_OUT_EOF, csi_enc_callback, 0, "Mxc Camera", cam); if (err != 0) { printk(KERN_ERR "Error registering rot irq\n"); return err; } err = csi_enc_setup(cam); if (err != 0) { printk(KERN_ERR "csi_enc_setup %d\n", err); return err; } return err; } /*! * Disable encoder task * @param private struct cam_data * mxc capture instance * * @return int */ static int csi_enc_disabling_tasks(void *private) { cam_data *cam = (cam_data *) private; int err = 0; #ifdef CONFIG_MXC_MIPI_CSI2 void *mipi_csi2_info; int ipu_id; int csi_id; #endif err = ipu_disable_channel(cam->ipu, CSI_MEM, true); ipu_uninit_channel(cam->ipu, CSI_MEM); #ifdef CONFIG_MXC_MIPI_CSI2 mipi_csi2_info = mipi_csi2_get_info(); if (mipi_csi2_info) { if (mipi_csi2_get_status(mipi_csi2_info)) { ipu_id = mipi_csi2_get_bind_ipu(mipi_csi2_info); csi_id = mipi_csi2_get_bind_csi(mipi_csi2_info); if (cam->ipu == ipu_get_soc(ipu_id) && cam->csi == csi_id) mipi_csi2_pixelclk_disable(mipi_csi2_info); } } else { printk(KERN_ERR "Fail to get mipi_csi2_info!\n"); return -EPERM; } #endif return err; } /*! * Enable csi * @param private struct cam_data * mxc capture instance * * @return status */ static int csi_enc_enable_csi(void *private) { cam_data *cam = (cam_data *) private; return ipu_enable_csi(cam->ipu, cam->csi); } /*! * Disable csi * @param private struct cam_data * mxc capture instance * * @return status */ static int csi_enc_disable_csi(void *private) { cam_data *cam = (cam_data *) private; /* free csi eof irq firstly. * when disable csi, wait for idmac eof. * it requests eof irq again */ ipu_free_irq(cam->ipu, IPU_IRQ_CSI0_OUT_EOF, cam); return ipu_disable_csi(cam->ipu, cam->csi); } /*! * function to select CSI ENC as the working path * * @param private struct cam_data * mxc capture instance * * @return int */ int csi_enc_select(void *private) { cam_data *cam = (cam_data *) private; int err = 0; if (cam) { cam->enc_update_eba = csi_enc_eba_update; cam->enc_enable = csi_enc_enabling_tasks; cam->enc_disable = csi_enc_disabling_tasks; cam->enc_enable_csi = csi_enc_enable_csi; cam->enc_disable_csi = csi_enc_disable_csi; } else { err = -EIO; } return err; } /*! * function to de-select CSI ENC as the working path * * @param private struct cam_data * mxc capture instance * * @return int */ int csi_enc_deselect(void *private) { cam_data *cam = (cam_data *) private; int err = 0; if (cam) { cam->enc_update_eba = NULL; cam->enc_enable = NULL; cam->enc_disable = NULL; cam->enc_enable_csi = NULL; cam->enc_disable_csi = NULL; } return err; } /*! * Init the Encorder channels * * @return Error code indicating success or failure */ __init int csi_enc_init(void) { return 0; } /*! * Deinit the Encorder channels * */ void __exit csi_enc_exit(void) { } module_init(csi_enc_init); module_exit(csi_enc_exit); EXPORT_SYMBOL(csi_enc_select); EXPORT_SYMBOL(csi_enc_deselect); MODULE_AUTHOR("Freescale Semiconductor, Inc."); MODULE_DESCRIPTION("CSI ENC Driver"); MODULE_LICENSE("GPL");
zOrg1331/wandboard-kernel
drivers/media/video/mxc/capture/ipu_csi_enc.c
C
gpl-2.0
10,146
<?php /** * @version 0.0.6 * @package com_jazz_mastering * @copyright Copyright (C) 2012. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt * @author Artur Pañach Bargalló <[email protected]> - http:// */ defined('_JEXEC') or die; jimport('joomla.application.component.modellist'); /** * Methods supporting a list of Jazz_mastering records. */ class Jazz_masteringModelCadencias extends JModelList { /** * Constructor. * * @param array An optional associative array of configuration settings. * @see JController * @since 1.6 */ public function __construct($config = array()) { parent::__construct($config); } /** * Method to auto-populate the model state. * * Note. Calling getState in this method will result in recursion. * * @since 1.6 */ protected function populateState($ordering = null, $direction = null) { // Initialise variables. $app = JFactory::getApplication(); // List state information $limit = $app->getUserStateFromRequest('global.list.limit', 'limit', $app->getCfg('list_limit')); $this->setState('list.limit', $limit); $limitstart = JFactory::getApplication()->input->getInt('limitstart', 0); $this->setState('list.start', $limitstart); // List state information. parent::populateState($ordering, $direction); } /** * Build an SQL query to load the list data. * * @return JDatabaseQuery * @since 1.6 */ protected function getListQuery() { // Create a new query object. $db = $this->getDbo(); $query = $db->getQuery(true); // Select the required fields from the table. $query->select( $this->getState( 'list.select', 'a.*' ) ); $query->from('`#__jazz_mastering_cadencia` AS a'); // Join over the created by field 'values_cadencia_creado_por' $query->select('values_cadencia_creado_por.name AS values_cadencia_creado_por'); $query->join('LEFT', '#__users AS values_cadencia_creado_por ON values_cadencia_creado_por.id = a.values_cadencia_creado_por'); // Filter by search in title $search = $this->getState('filter.search'); if (!empty($search)) { if (stripos($search, 'id:') === 0) { $query->where('a.id = '.(int) substr($search, 3)); } else { $search = $db->Quote('%'.$db->escape($search, true).'%'); } } return $query; } }
lion01/weprob
components/com_jazz_mastering/models/cadencias.php
PHP
gpl-2.0
2,698
/* * linux/mm/filemap.c * * Copyright (C) 1994-1999 Linus Torvalds */ /* * This file handles the generic file mmap semantics used by * most "normal" filesystems (but you don't /have/ to use this: * the NFS filesystem used to do this differently, for example) */ #include <linux/export.h> #include <linux/compiler.h> #include <linux/fs.h> #include <linux/uaccess.h> #include <linux/aio.h> #include <linux/capability.h> #include <linux/kernel_stat.h> #include <linux/gfp.h> #include <linux/mm.h> #include <linux/swap.h> #include <linux/mman.h> #include <linux/pagemap.h> #include <linux/file.h> #include <linux/uio.h> #include <linux/hash.h> #include <linux/writeback.h> #include <linux/backing-dev.h> #include <linux/pagevec.h> #include <linux/blkdev.h> #include <linux/security.h> #include <linux/cpuset.h> #include <linux/hardirq.h> /* for BUG_ON(!in_atomic()) only */ #include <linux/memcontrol.h> #include <linux/cleancache.h> #include "internal.h" #include "../fs/sreadahead_prof.h" /* * FIXME: remove all knowledge of the buffer layer from the core VM */ #include <linux/buffer_head.h> /* for try_to_free_buffers */ #include <asm/mman.h> /* * Shared mappings implemented 30.11.1994. It's not fully working yet, * though. * * Shared mappings now work. 15.8.1995 Bruno. * * finished 'unifying' the page and buffer cache and SMP-threaded the * page-cache, 21.05.1999, Ingo Molnar <[email protected]> * * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <[email protected]> */ /* * Lock ordering: * * ->i_mmap_mutex (truncate_pagecache) * ->private_lock (__free_pte->__set_page_dirty_buffers) * ->swap_lock (exclusive_swap_page, others) * ->mapping->tree_lock * * ->i_mutex * ->i_mmap_mutex (truncate->unmap_mapping_range) * * ->mmap_sem * ->i_mmap_mutex * ->page_table_lock or pte_lock (various, mainly in memory.c) * ->mapping->tree_lock (arch-dependent flush_dcache_mmap_lock) * * ->mmap_sem * ->lock_page (access_process_vm) * * ->i_mutex (generic_file_buffered_write) * ->mmap_sem (fault_in_pages_readable->do_page_fault) * * bdi->wb.list_lock * sb_lock (fs/fs-writeback.c) * ->mapping->tree_lock (__sync_single_inode) * * ->i_mmap_mutex * ->anon_vma.lock (vma_adjust) * * ->anon_vma.lock * ->page_table_lock or pte_lock (anon_vma_prepare and various) * * ->page_table_lock or pte_lock * ->swap_lock (try_to_unmap_one) * ->private_lock (try_to_unmap_one) * ->tree_lock (try_to_unmap_one) * ->zone.lru_lock (follow_page->mark_page_accessed) * ->zone.lru_lock (check_pte_range->isolate_lru_page) * ->private_lock (page_remove_rmap->set_page_dirty) * ->tree_lock (page_remove_rmap->set_page_dirty) * bdi.wb->list_lock (page_remove_rmap->set_page_dirty) * ->inode->i_lock (page_remove_rmap->set_page_dirty) * bdi.wb->list_lock (zap_pte_range->set_page_dirty) * ->inode->i_lock (zap_pte_range->set_page_dirty) * ->private_lock (zap_pte_range->__set_page_dirty_buffers) * * ->i_mmap_mutex * ->tasklist_lock (memory_failure, collect_procs_ao) */ /* * Delete a page from the page cache and free it. Caller has to make * sure the page is locked and that nobody else uses it - or that usage * is safe. The caller must hold the mapping's tree_lock. */ void __delete_from_page_cache(struct page *page) { struct address_space *mapping = page->mapping; /* * if we're uptodate, flush out into the cleancache, otherwise * invalidate any existing cleancache entries. We can't leave * stale data around in the cleancache once our page is gone */ if (PageUptodate(page) && PageMappedToDisk(page)) cleancache_put_page(page); else cleancache_invalidate_page(mapping, page); radix_tree_delete(&mapping->page_tree, page->index); page->mapping = NULL; /* Leave page->index set: truncation lookup relies upon it */ mapping->nrpages--; __dec_zone_page_state(page, NR_FILE_PAGES); if (PageSwapBacked(page)) __dec_zone_page_state(page, NR_SHMEM); BUG_ON(page_mapped(page)); /* * Some filesystems seem to re-dirty the page even after * the VM has canceled the dirty bit (eg ext3 journaling). * * Fix it up by doing a final dirty accounting check after * having removed the page entirely. */ if (PageDirty(page) && mapping_cap_account_dirty(mapping)) { dec_zone_page_state(page, NR_FILE_DIRTY); dec_bdi_stat(mapping->backing_dev_info, BDI_RECLAIMABLE); } } /** * delete_from_page_cache - delete page from page cache * @page: the page which the kernel is trying to remove from page cache * * This must be called only on pages that have been verified to be in the page * cache and locked. It will never put the page into the free list, the caller * has a reference on the page. */ void delete_from_page_cache(struct page *page) { struct address_space *mapping = page->mapping; void (*freepage)(struct page *); BUG_ON(!PageLocked(page)); freepage = mapping->a_ops->freepage; spin_lock_irq(&mapping->tree_lock); __delete_from_page_cache(page); spin_unlock_irq(&mapping->tree_lock); mem_cgroup_uncharge_cache_page(page); if (freepage) freepage(page); page_cache_release(page); } EXPORT_SYMBOL(delete_from_page_cache); static int sleep_on_page(void *word) { io_schedule(); return 0; } static int sleep_on_page_killable(void *word) { sleep_on_page(word); return fatal_signal_pending(current) ? -EINTR : 0; } /** * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range * @mapping: address space structure to write * @start: offset in bytes where the range starts * @end: offset in bytes where the range ends (inclusive) * @sync_mode: enable synchronous operation * * Start writeback against all of a mapping's dirty pages that lie * within the byte offsets <start, end> inclusive. * * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as * opposed to a regular memory cleansing writeback. The difference between * these two operations is that if a dirty page/buffer is encountered, it must * be waited upon, and not just skipped over. */ int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start, loff_t end, int sync_mode) { int ret; struct writeback_control wbc = { .sync_mode = sync_mode, .nr_to_write = LONG_MAX, .range_start = start, .range_end = end, }; if (!mapping_cap_writeback_dirty(mapping)) return 0; ret = do_writepages(mapping, &wbc); return ret; } static inline int __filemap_fdatawrite(struct address_space *mapping, int sync_mode) { return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode); } int filemap_fdatawrite(struct address_space *mapping) { return __filemap_fdatawrite(mapping, WB_SYNC_ALL); } EXPORT_SYMBOL(filemap_fdatawrite); int filemap_fdatawrite_range(struct address_space *mapping, loff_t start, loff_t end) { return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL); } EXPORT_SYMBOL(filemap_fdatawrite_range); /** * filemap_flush - mostly a non-blocking flush * @mapping: target address_space * * This is a mostly non-blocking flush. Not suitable for data-integrity * purposes - I/O may not be started against all dirty pages. */ int filemap_flush(struct address_space *mapping) { return __filemap_fdatawrite(mapping, WB_SYNC_NONE); } EXPORT_SYMBOL(filemap_flush); /** * filemap_fdatawait_range - wait for writeback to complete * @mapping: address space structure to wait for * @start_byte: offset in bytes where the range starts * @end_byte: offset in bytes where the range ends (inclusive) * * Walk the list of under-writeback pages of the given address space * in the given range and wait for all of them. */ int filemap_fdatawait_range(struct address_space *mapping, loff_t start_byte, loff_t end_byte) { pgoff_t index = start_byte >> PAGE_CACHE_SHIFT; pgoff_t end = end_byte >> PAGE_CACHE_SHIFT; struct pagevec pvec; int nr_pages; int ret = 0; if (end_byte < start_byte) return 0; pagevec_init(&pvec, 0); while ((index <= end) && (nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, PAGECACHE_TAG_WRITEBACK, min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1)) != 0) { unsigned i; for (i = 0; i < nr_pages; i++) { struct page *page = pvec.pages[i]; /* until radix tree lookup accepts end_index */ if (page->index > end) continue; wait_on_page_writeback(page); if (TestClearPageError(page)) ret = -EIO; } pagevec_release(&pvec); cond_resched(); } /* Check for outstanding write errors */ if (test_and_clear_bit(AS_ENOSPC, &mapping->flags)) ret = -ENOSPC; if (test_and_clear_bit(AS_EIO, &mapping->flags)) ret = -EIO; return ret; } EXPORT_SYMBOL(filemap_fdatawait_range); /** * filemap_fdatawait - wait for all under-writeback pages to complete * @mapping: address space structure to wait for * * Walk the list of under-writeback pages of the given address space * and wait for all of them. */ int filemap_fdatawait(struct address_space *mapping) { loff_t i_size = i_size_read(mapping->host); if (i_size == 0) return 0; return filemap_fdatawait_range(mapping, 0, i_size - 1); } EXPORT_SYMBOL(filemap_fdatawait); int filemap_write_and_wait(struct address_space *mapping) { int err = 0; if (mapping->nrpages) { err = filemap_fdatawrite(mapping); /* * Even if the above returned error, the pages may be * written partially (e.g. -ENOSPC), so we wait for it. * But the -EIO is special case, it may indicate the worst * thing (e.g. bug) happened, so we avoid waiting for it. */ if (err != -EIO) { int err2 = filemap_fdatawait(mapping); if (!err) err = err2; } } return err; } EXPORT_SYMBOL(filemap_write_and_wait); /** * filemap_write_and_wait_range - write out & wait on a file range * @mapping: the address_space for the pages * @lstart: offset in bytes where the range starts * @lend: offset in bytes where the range ends (inclusive) * * Write out and wait upon file offsets lstart->lend, inclusive. * * Note that `lend' is inclusive (describes the last byte to be written) so * that this function can be used to write to the very end-of-file (end = -1). */ int filemap_write_and_wait_range(struct address_space *mapping, loff_t lstart, loff_t lend) { int err = 0; if (mapping->nrpages) { err = __filemap_fdatawrite_range(mapping, lstart, lend, WB_SYNC_ALL); /* See comment of filemap_write_and_wait() */ if (err != -EIO) { int err2 = filemap_fdatawait_range(mapping, lstart, lend); if (!err) err = err2; } } return err; } EXPORT_SYMBOL(filemap_write_and_wait_range); /** * replace_page_cache_page - replace a pagecache page with a new one * @old: page to be replaced * @new: page to replace with * @gfp_mask: allocation mode * * This function replaces a page in the pagecache with a new one. On * success it acquires the pagecache reference for the new page and * drops it for the old page. Both the old and new pages must be * locked. This function does not add the new page to the LRU, the * caller must do that. * * The remove + add is atomic. The only way this function can fail is * memory allocation failure. */ int replace_page_cache_page(struct page *old, struct page *new, gfp_t gfp_mask) { int error; VM_BUG_ON(!PageLocked(old)); VM_BUG_ON(!PageLocked(new)); VM_BUG_ON(new->mapping); error = radix_tree_preload(gfp_mask & ~__GFP_HIGHMEM); if (!error) { struct address_space *mapping = old->mapping; void (*freepage)(struct page *); pgoff_t offset = old->index; freepage = mapping->a_ops->freepage; page_cache_get(new); new->mapping = mapping; new->index = offset; spin_lock_irq(&mapping->tree_lock); __delete_from_page_cache(old); error = radix_tree_insert(&mapping->page_tree, offset, new); BUG_ON(error); mapping->nrpages++; __inc_zone_page_state(new, NR_FILE_PAGES); if (PageSwapBacked(new)) __inc_zone_page_state(new, NR_SHMEM); spin_unlock_irq(&mapping->tree_lock); /* mem_cgroup codes must not be called under tree_lock */ mem_cgroup_replace_page_cache(old, new); radix_tree_preload_end(); if (freepage) freepage(old); page_cache_release(old); } return error; } EXPORT_SYMBOL_GPL(replace_page_cache_page); /** * add_to_page_cache_locked - add a locked page to the pagecache * @page: page to add * @mapping: the page's address_space * @offset: page index * @gfp_mask: page allocation mode * * This function is used to add a page to the pagecache. It must be locked. * This function does not add the page to the LRU. The caller must do that. */ int add_to_page_cache_locked(struct page *page, struct address_space *mapping, pgoff_t offset, gfp_t gfp_mask) { int error; VM_BUG_ON(!PageLocked(page)); VM_BUG_ON(PageSwapBacked(page)); error = mem_cgroup_cache_charge(page, current->mm, gfp_mask & GFP_RECLAIM_MASK); if (error) goto out; error = radix_tree_preload(gfp_mask & ~__GFP_HIGHMEM); if (error == 0) { page_cache_get(page); page->mapping = mapping; page->index = offset; spin_lock_irq(&mapping->tree_lock); error = radix_tree_insert(&mapping->page_tree, offset, page); if (likely(!error)) { mapping->nrpages++; __inc_zone_page_state(page, NR_FILE_PAGES); spin_unlock_irq(&mapping->tree_lock); } else { page->mapping = NULL; /* Leave page->index set: truncation relies upon it */ spin_unlock_irq(&mapping->tree_lock); mem_cgroup_uncharge_cache_page(page); page_cache_release(page); } radix_tree_preload_end(); } else mem_cgroup_uncharge_cache_page(page); out: return error; } EXPORT_SYMBOL(add_to_page_cache_locked); int add_to_page_cache_lru(struct page *page, struct address_space *mapping, pgoff_t offset, gfp_t gfp_mask) { int ret; ret = add_to_page_cache(page, mapping, offset, gfp_mask); if (ret == 0) lru_cache_add_file(page); return ret; } EXPORT_SYMBOL_GPL(add_to_page_cache_lru); #ifdef CONFIG_NUMA struct page *__page_cache_alloc(gfp_t gfp) { int n; struct page *page; if (cpuset_do_page_mem_spread()) { unsigned int cpuset_mems_cookie; do { cpuset_mems_cookie = get_mems_allowed(); n = cpuset_mem_spread_node(); page = alloc_pages_exact_node(n, gfp, 0); } while (!put_mems_allowed(cpuset_mems_cookie) && !page); return page; } return alloc_pages(gfp, 0); } EXPORT_SYMBOL(__page_cache_alloc); #endif /* * In order to wait for pages to become available there must be * waitqueues associated with pages. By using a hash table of * waitqueues where the bucket discipline is to maintain all * waiters on the same queue and wake all when any of the pages * become available, and for the woken contexts to check to be * sure the appropriate page became available, this saves space * at a cost of "thundering herd" phenomena during rare hash * collisions. */ static wait_queue_head_t *page_waitqueue(struct page *page) { const struct zone *zone = page_zone(page); return &zone->wait_table[hash_ptr(page, zone->wait_table_bits)]; } static inline void wake_up_page(struct page *page, int bit) { __wake_up_bit(page_waitqueue(page), &page->flags, bit); } void wait_on_page_bit(struct page *page, int bit_nr) { DEFINE_WAIT_BIT(wait, &page->flags, bit_nr); if (test_bit(bit_nr, &page->flags)) __wait_on_bit(page_waitqueue(page), &wait, sleep_on_page, TASK_UNINTERRUPTIBLE); } EXPORT_SYMBOL(wait_on_page_bit); int wait_on_page_bit_killable(struct page *page, int bit_nr) { DEFINE_WAIT_BIT(wait, &page->flags, bit_nr); if (!test_bit(bit_nr, &page->flags)) return 0; return __wait_on_bit(page_waitqueue(page), &wait, sleep_on_page_killable, TASK_KILLABLE); } /** * add_page_wait_queue - Add an arbitrary waiter to a page's wait queue * @page: Page defining the wait queue of interest * @waiter: Waiter to add to the queue * * Add an arbitrary @waiter to the wait queue for the nominated @page. */ void add_page_wait_queue(struct page *page, wait_queue_t *waiter) { wait_queue_head_t *q = page_waitqueue(page); unsigned long flags; spin_lock_irqsave(&q->lock, flags); __add_wait_queue(q, waiter); spin_unlock_irqrestore(&q->lock, flags); } EXPORT_SYMBOL_GPL(add_page_wait_queue); /** * unlock_page - unlock a locked page * @page: the page * * Unlocks the page and wakes up sleepers in ___wait_on_page_locked(). * Also wakes sleepers in wait_on_page_writeback() because the wakeup * mechananism between PageLocked pages and PageWriteback pages is shared. * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep. * * The mb is necessary to enforce ordering between the clear_bit and the read * of the waitqueue (to avoid SMP races with a parallel wait_on_page_locked()). */ void unlock_page(struct page *page) { VM_BUG_ON(!PageLocked(page)); clear_bit_unlock(PG_locked, &page->flags); smp_mb__after_clear_bit(); wake_up_page(page, PG_locked); } EXPORT_SYMBOL(unlock_page); /** * end_page_writeback - end writeback against a page * @page: the page */ void end_page_writeback(struct page *page) { if (TestClearPageReclaim(page)) rotate_reclaimable_page(page); if (!test_clear_page_writeback(page)) BUG(); smp_mb__after_clear_bit(); wake_up_page(page, PG_writeback); } EXPORT_SYMBOL(end_page_writeback); /** * __lock_page - get a lock on the page, assuming we need to sleep to get it * @page: the page to lock */ void __lock_page(struct page *page) { DEFINE_WAIT_BIT(wait, &page->flags, PG_locked); __wait_on_bit_lock(page_waitqueue(page), &wait, sleep_on_page, TASK_UNINTERRUPTIBLE); } EXPORT_SYMBOL(__lock_page); int __lock_page_killable(struct page *page) { DEFINE_WAIT_BIT(wait, &page->flags, PG_locked); return __wait_on_bit_lock(page_waitqueue(page), &wait, sleep_on_page_killable, TASK_KILLABLE); } EXPORT_SYMBOL_GPL(__lock_page_killable); int __lock_page_or_retry(struct page *page, struct mm_struct *mm, unsigned int flags) { if (flags & FAULT_FLAG_ALLOW_RETRY) { /* * CAUTION! In this case, mmap_sem is not released * even though return 0. */ if (flags & FAULT_FLAG_RETRY_NOWAIT) return 0; up_read(&mm->mmap_sem); if (flags & FAULT_FLAG_KILLABLE) wait_on_page_locked_killable(page); else wait_on_page_locked(page); return 0; } else { if (flags & FAULT_FLAG_KILLABLE) { int ret; ret = __lock_page_killable(page); if (ret) { up_read(&mm->mmap_sem); return 0; } } else __lock_page(page); return 1; } } /** * find_get_page - find and get a page reference * @mapping: the address_space to search * @offset: the page index * * Is there a pagecache struct page at the given (mapping, offset) tuple? * If yes, increment its refcount and return it; if no, return NULL. */ struct page *find_get_page(struct address_space *mapping, pgoff_t offset) { void **pagep; struct page *page; rcu_read_lock(); repeat: page = NULL; pagep = radix_tree_lookup_slot(&mapping->page_tree, offset); if (pagep) { page = radix_tree_deref_slot(pagep); if (unlikely(!page)) goto out; if (radix_tree_exception(page)) { if (radix_tree_deref_retry(page)) goto repeat; /* * Otherwise, shmem/tmpfs must be storing a swap entry * here as an exceptional entry: so return it without * attempting to raise page count. */ goto out; } if (!page_cache_get_speculative(page)) goto repeat; /* * Has the page moved? * This is part of the lockless pagecache protocol. See * include/linux/pagemap.h for details. */ if (unlikely(page != *pagep)) { page_cache_release(page); goto repeat; } } out: rcu_read_unlock(); return page; } EXPORT_SYMBOL(find_get_page); /** * find_lock_page - locate, pin and lock a pagecache page * @mapping: the address_space to search * @offset: the page index * * Locates the desired pagecache page, locks it, increments its reference * count and returns its address. * * Returns zero if the page was not present. find_lock_page() may sleep. */ struct page *find_lock_page(struct address_space *mapping, pgoff_t offset) { struct page *page; repeat: page = find_get_page(mapping, offset); if (page && !radix_tree_exception(page)) { lock_page(page); /* Has the page been truncated? */ if (unlikely(page->mapping != mapping)) { unlock_page(page); page_cache_release(page); goto repeat; } VM_BUG_ON(page->index != offset); } return page; } EXPORT_SYMBOL(find_lock_page); /** * find_or_create_page - locate or add a pagecache page * @mapping: the page's address_space * @index: the page's index into the mapping * @gfp_mask: page allocation mode * * Locates a page in the pagecache. If the page is not present, a new page * is allocated using @gfp_mask and is added to the pagecache and to the VM's * LRU list. The returned page is locked and has its reference count * incremented. * * find_or_create_page() may sleep, even if @gfp_flags specifies an atomic * allocation! * * find_or_create_page() returns the desired page's address, or zero on * memory exhaustion. */ struct page *find_or_create_page(struct address_space *mapping, pgoff_t index, gfp_t gfp_mask) { struct page *page; int err; repeat: page = find_lock_page(mapping, index); if (!page) { page = __page_cache_alloc(gfp_mask); if (!page) return NULL; /* * We want a regular kernel memory (not highmem or DMA etc) * allocation for the radix tree nodes, but we need to honour * the context-specific requirements the caller has asked for. * GFP_RECLAIM_MASK collects those requirements. */ err = add_to_page_cache_lru(page, mapping, index, (gfp_mask & GFP_RECLAIM_MASK)); if (unlikely(err)) { page_cache_release(page); page = NULL; if (err == -EEXIST) goto repeat; } } return page; } EXPORT_SYMBOL(find_or_create_page); /** * find_get_pages - gang pagecache lookup * @mapping: The address_space to search * @start: The starting page index * @nr_pages: The maximum number of pages * @pages: Where the resulting pages are placed * * find_get_pages() will search for and return a group of up to * @nr_pages pages in the mapping. The pages are placed at @pages. * find_get_pages() takes a reference against the returned pages. * * The search returns a group of mapping-contiguous pages with ascending * indexes. There may be holes in the indices due to not-present pages. * * find_get_pages() returns the number of pages which were found. */ unsigned find_get_pages(struct address_space *mapping, pgoff_t start, unsigned int nr_pages, struct page **pages) { struct radix_tree_iter iter; void **slot; unsigned ret = 0; if (unlikely(!nr_pages)) return 0; rcu_read_lock(); restart: radix_tree_for_each_slot(slot, &mapping->page_tree, &iter, start) { struct page *page; repeat: page = radix_tree_deref_slot(slot); if (unlikely(!page)) continue; if (radix_tree_exception(page)) { if (radix_tree_deref_retry(page)) { /* * Transient condition which can only trigger * when entry at index 0 moves out of or back * to root: none yet gotten, safe to restart. */ WARN_ON(iter.index); goto restart; } /* * Otherwise, shmem/tmpfs must be storing a swap entry * here as an exceptional entry: so skip over it - * we only reach this from invalidate_mapping_pages(). */ continue; } if (!page_cache_get_speculative(page)) goto repeat; /* Has the page moved? */ if (unlikely(page != *slot)) { page_cache_release(page); goto repeat; } pages[ret] = page; if (++ret == nr_pages) break; } rcu_read_unlock(); return ret; } /** * find_get_pages_contig - gang contiguous pagecache lookup * @mapping: The address_space to search * @index: The starting page index * @nr_pages: The maximum number of pages * @pages: Where the resulting pages are placed * * find_get_pages_contig() works exactly like find_get_pages(), except * that the returned number of pages are guaranteed to be contiguous. * * find_get_pages_contig() returns the number of pages which were found. */ unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index, unsigned int nr_pages, struct page **pages) { struct radix_tree_iter iter; void **slot; unsigned int ret = 0; if (unlikely(!nr_pages)) return 0; rcu_read_lock(); restart: radix_tree_for_each_contig(slot, &mapping->page_tree, &iter, index) { struct page *page; repeat: page = radix_tree_deref_slot(slot); /* The hole, there no reason to continue */ if (unlikely(!page)) break; if (radix_tree_exception(page)) { if (radix_tree_deref_retry(page)) { /* * Transient condition which can only trigger * when entry at index 0 moves out of or back * to root: none yet gotten, safe to restart. */ goto restart; } /* * Otherwise, shmem/tmpfs must be storing a swap entry * here as an exceptional entry: so stop looking for * contiguous pages. */ break; } if (!page_cache_get_speculative(page)) goto repeat; /* Has the page moved? */ if (unlikely(page != *slot)) { page_cache_release(page); goto repeat; } /* * must check mapping and index after taking the ref. * otherwise we can get both false positives and false * negatives, which is just confusing to the caller. */ if (page->mapping == NULL || page->index != iter.index) { page_cache_release(page); break; } pages[ret] = page; if (++ret == nr_pages) break; } rcu_read_unlock(); return ret; } EXPORT_SYMBOL(find_get_pages_contig); /** * find_get_pages_tag - find and return pages that match @tag * @mapping: the address_space to search * @index: the starting page index * @tag: the tag index * @nr_pages: the maximum number of pages * @pages: where the resulting pages are placed * * Like find_get_pages, except we only return pages which are tagged with * @tag. We update @index to index the next page for the traversal. */ unsigned find_get_pages_tag(struct address_space *mapping, pgoff_t *index, int tag, unsigned int nr_pages, struct page **pages) { struct radix_tree_iter iter; void **slot; unsigned ret = 0; if (unlikely(!nr_pages)) return 0; rcu_read_lock(); restart: radix_tree_for_each_tagged(slot, &mapping->page_tree, &iter, *index, tag) { struct page *page; repeat: page = radix_tree_deref_slot(slot); if (unlikely(!page)) continue; if (radix_tree_exception(page)) { if (radix_tree_deref_retry(page)) { /* * Transient condition which can only trigger * when entry at index 0 moves out of or back * to root: none yet gotten, safe to restart. */ goto restart; } /* * This function is never used on a shmem/tmpfs * mapping, so a swap entry won't be found here. */ BUG(); } if (!page_cache_get_speculative(page)) goto repeat; /* Has the page moved? */ if (unlikely(page != *slot)) { page_cache_release(page); goto repeat; } pages[ret] = page; if (++ret == nr_pages) break; } rcu_read_unlock(); if (ret) *index = pages[ret - 1]->index + 1; return ret; } EXPORT_SYMBOL(find_get_pages_tag); /** * grab_cache_page_nowait - returns locked page at given index in given cache * @mapping: target address_space * @index: the page index * * Same as grab_cache_page(), but do not wait if the page is unavailable. * This is intended for speculative data generators, where the data can * be regenerated if the page couldn't be grabbed. This routine should * be safe to call while holding the lock for another page. * * Clear __GFP_FS when allocating the page to avoid recursion into the fs * and deadlock against the caller's locked page. */ struct page * grab_cache_page_nowait(struct address_space *mapping, pgoff_t index) { struct page *page = find_get_page(mapping, index); if (page) { if (trylock_page(page)) return page; page_cache_release(page); return NULL; } page = __page_cache_alloc(mapping_gfp_mask(mapping) & ~__GFP_FS); if (page && add_to_page_cache_lru(page, mapping, index, GFP_NOFS)) { page_cache_release(page); page = NULL; } return page; } EXPORT_SYMBOL(grab_cache_page_nowait); /* * CD/DVDs are error prone. When a medium error occurs, the driver may fail * a _large_ part of the i/o request. Imagine the worst scenario: * * ---R__________________________________________B__________ * ^ reading here ^ bad block(assume 4k) * * read(R) => miss => readahead(R...B) => media error => frustrating retries * => failing the whole request => read(R) => read(R+1) => * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) => * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) => * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ...... * * It is going insane. Fix it by quickly scaling down the readahead size. */ static void shrink_readahead_size_eio(struct file *filp, struct file_ra_state *ra) { ra->ra_pages /= 4; } /** * do_generic_file_read - generic file read routine * @filp: the file to read * @ppos: current file position * @desc: read_descriptor * @actor: read method * * This is a generic file read routine, and uses the * mapping->a_ops->readpage() function for the actual low-level stuff. * * This is really ugly. But the goto's actually try to clarify some * of the logic when it comes to error handling etc. */ static void do_generic_file_read(struct file *filp, loff_t *ppos, read_descriptor_t *desc, read_actor_t actor) { struct address_space *mapping = filp->f_mapping; struct inode *inode = mapping->host; struct file_ra_state *ra = &filp->f_ra; pgoff_t index; pgoff_t last_index; pgoff_t prev_index; unsigned long offset; /* offset into pagecache page */ unsigned int prev_offset; int error; index = *ppos >> PAGE_CACHE_SHIFT; prev_index = ra->prev_pos >> PAGE_CACHE_SHIFT; prev_offset = ra->prev_pos & (PAGE_CACHE_SIZE-1); last_index = (*ppos + desc->count + PAGE_CACHE_SIZE-1) >> PAGE_CACHE_SHIFT; offset = *ppos & ~PAGE_CACHE_MASK; for (;;) { struct page *page; pgoff_t end_index; loff_t isize; unsigned long nr, ret; cond_resched(); find_page: page = find_get_page(mapping, index); if (!page) { page_cache_sync_readahead(mapping, ra, filp, index, last_index - index); page = find_get_page(mapping, index); if (unlikely(page == NULL)) goto no_cached_page; } if (PageReadahead(page)) { page_cache_async_readahead(mapping, ra, filp, page, index, last_index - index); } if (!PageUptodate(page)) { if (inode->i_blkbits == PAGE_CACHE_SHIFT || !mapping->a_ops->is_partially_uptodate) goto page_not_up_to_date; if (!trylock_page(page)) goto page_not_up_to_date; /* Did it get truncated before we got the lock? */ if (!page->mapping) goto page_not_up_to_date_locked; if (!mapping->a_ops->is_partially_uptodate(page, desc, offset)) goto page_not_up_to_date_locked; unlock_page(page); } page_ok: /* * i_size must be checked after we know the page is Uptodate. * * Checking i_size after the check allows us to calculate * the correct value for "nr", which means the zero-filled * part of the page is not copied back to userspace (unless * another truncate extends the file - this is desired though). */ isize = i_size_read(inode); end_index = (isize - 1) >> PAGE_CACHE_SHIFT; if (unlikely(!isize || index > end_index)) { page_cache_release(page); goto out; } /* nr is the maximum number of bytes to copy from this page */ nr = PAGE_CACHE_SIZE; if (index == end_index) { nr = ((isize - 1) & ~PAGE_CACHE_MASK) + 1; if (nr <= offset) { page_cache_release(page); goto out; } } nr = nr - offset; /* If users can be writing to this page using arbitrary * virtual addresses, take care about potential aliasing * before reading the page on the kernel side. */ if (mapping_writably_mapped(mapping)) flush_dcache_page(page); /* * When a sequential read accesses a page several times, * only mark it as accessed the first time. */ if (prev_index != index || offset != prev_offset) mark_page_accessed(page); prev_index = index; /* * Ok, we have the page, and it's up-to-date, so * now we can copy it to user space... * * The actor routine returns how many bytes were actually used.. * NOTE! This may not be the same as how much of a user buffer * we filled up (we may be padding etc), so we can only update * "pos" here (the actor routine has to update the user buffer * pointers and the remaining count). */ ret = actor(desc, page, offset, nr); offset += ret; index += offset >> PAGE_CACHE_SHIFT; offset &= ~PAGE_CACHE_MASK; prev_offset = offset; page_cache_release(page); if (ret == nr && desc->count) continue; goto out; page_not_up_to_date: /* Get exclusive access to the page ... */ error = lock_page_killable(page); if (unlikely(error)) goto readpage_error; page_not_up_to_date_locked: /* Did it get truncated before we got the lock? */ if (!page->mapping) { unlock_page(page); page_cache_release(page); continue; } /* Did somebody else fill it already? */ if (PageUptodate(page)) { unlock_page(page); goto page_ok; } readpage: /* * A previous I/O error may have been due to temporary * failures, eg. multipath errors. * PG_error will be set again if readpage fails. */ ClearPageError(page); /* Start the actual read. The read will unlock the page. */ error = mapping->a_ops->readpage(filp, page); if (unlikely(error)) { if (error == AOP_TRUNCATED_PAGE) { page_cache_release(page); goto find_page; } goto readpage_error; } if (!PageUptodate(page)) { error = lock_page_killable(page); if (unlikely(error)) goto readpage_error; if (!PageUptodate(page)) { if (page->mapping == NULL) { /* * invalidate_mapping_pages got it */ unlock_page(page); page_cache_release(page); goto find_page; } unlock_page(page); shrink_readahead_size_eio(filp, ra); error = -EIO; goto readpage_error; } unlock_page(page); } goto page_ok; readpage_error: /* UHHUH! A synchronous read error occurred. Report it */ desc->error = error; page_cache_release(page); goto out; no_cached_page: /* * Ok, it wasn't cached, so we need to create a new * page.. */ page = page_cache_alloc_cold(mapping); if (!page) { desc->error = -ENOMEM; goto out; } error = add_to_page_cache_lru(page, mapping, index, GFP_KERNEL); if (error) { page_cache_release(page); if (error == -EEXIST) goto find_page; desc->error = error; goto out; } goto readpage; } out: ra->prev_pos = prev_index; ra->prev_pos <<= PAGE_CACHE_SHIFT; ra->prev_pos |= prev_offset; *ppos = ((loff_t)index << PAGE_CACHE_SHIFT) + offset; file_accessed(filp); } /* * Performs necessary checks before doing a write * @iov: io vector request * @nr_segs: number of segments in the iovec * @count: number of bytes to write * @access_flags: type of access: %VERIFY_READ or %VERIFY_WRITE * * Adjust number of segments and amount of bytes to write (nr_segs should be * properly initialized first). Returns appropriate error code that caller * should return or zero in case that write should be allowed. */ int generic_segment_checks(const struct iovec *iov, unsigned long *nr_segs, size_t *count, int access_flags) { unsigned long seg; size_t cnt = 0; for (seg = 0; seg < *nr_segs; seg++) { const struct iovec *iv = &iov[seg]; /* * If any segment has a negative length, or the cumulative * length ever wraps negative then return -EINVAL. */ cnt += iv->iov_len; if (unlikely((ssize_t)(cnt|iv->iov_len) < 0)) return -EINVAL; if (access_ok(access_flags, iv->iov_base, iv->iov_len)) continue; if (seg == 0) return -EFAULT; *nr_segs = seg; cnt -= iv->iov_len; /* This segment is no good */ break; } *count = cnt; return 0; } EXPORT_SYMBOL(generic_segment_checks); int file_read_iter_actor(read_descriptor_t *desc, struct page *page, unsigned long offset, unsigned long size) { struct iov_iter *iter = desc->arg.data; unsigned long copied = 0; if (size > desc->count) size = desc->count; copied = iov_iter_copy_to_user(page, iter, offset, size); if (copied < size) desc->error = -EFAULT; iov_iter_advance(iter, copied); desc->count -= copied; desc->written += copied; return copied; } /** * generic_file_read_iter - generic filesystem read routine * @iocb: kernel I/O control block * @iov_iter: memory vector * @pos: current file position */ ssize_t generic_file_read_iter(struct kiocb *iocb, struct iov_iter *iter, loff_t pos) { struct file *filp = iocb->ki_filp; read_descriptor_t desc; ssize_t retval = 0; size_t count = iov_iter_count(iter); loff_t *ppos = &iocb->ki_pos; /* coalesce the iovecs and go direct-to-BIO for O_DIRECT */ if (filp->f_flags & O_DIRECT) { loff_t size; struct address_space *mapping; struct inode *inode; mapping = filp->f_mapping; inode = mapping->host; if (!count) goto out; /* skip atime */ size = i_size_read(inode); if (pos < size) { retval = filemap_write_and_wait_range(mapping, pos, pos + count - 1); if (!retval) { struct blk_plug plug; blk_start_plug(&plug); retval = mapping->a_ops->direct_IO(READ, iocb, iter, pos); blk_finish_plug(&plug); } if (retval > 0) { *ppos = pos + retval; count -= retval; } /* * Btrfs can have a short DIO read if we encounter * compressed extents, so if there was an error, or if * we've already read everything we wanted to, or if * there was a short read because we hit EOF, go ahead * and return. Otherwise fallthrough to buffered io for * the rest of the read. */ if (retval < 0 || !count || *ppos >= size) { file_accessed(filp); goto out; } } } desc.written = 0; desc.arg.data = iter; desc.count = count; desc.error = 0; do_generic_file_read(filp, ppos, &desc, file_read_iter_actor); if (desc.written) retval = desc.written; else retval = desc.error; out: return retval; } EXPORT_SYMBOL(generic_file_read_iter); /** * generic_file_aio_read - generic filesystem read routine * @iocb: kernel I/O control block * @iov: io vector request * @nr_segs: number of segments in the iovec * @pos: current file position * * This is the "read()" routine for all filesystems * that can use the page cache directly. */ ssize_t generic_file_aio_read(struct kiocb *iocb, const struct iovec *iov, unsigned long nr_segs, loff_t pos) { struct iov_iter iter; int ret; size_t count; count = 0; ret = generic_segment_checks(iov, &nr_segs, &count, VERIFY_WRITE); if (ret) return ret; iov_iter_init(&iter, iov, nr_segs, count, 0); return generic_file_read_iter(iocb, &iter, pos); } EXPORT_SYMBOL(generic_file_aio_read); #ifdef CONFIG_MMU /** * page_cache_read - adds requested page to the page cache if not already there * @file: file to read * @offset: page index * * This adds the requested page to the page cache if it isn't already there, * and schedules an I/O to read in its contents from disk. */ static int page_cache_read(struct file *file, pgoff_t offset) { struct address_space *mapping = file->f_mapping; struct page *page; int ret; do { page = page_cache_alloc_cold(mapping); if (!page) return -ENOMEM; ret = add_to_page_cache_lru(page, mapping, offset, GFP_KERNEL); if (ret == 0) ret = mapping->a_ops->readpage(file, page); else if (ret == -EEXIST) ret = 0; /* losing race to add is OK */ page_cache_release(page); } while (ret == AOP_TRUNCATED_PAGE); return ret; } #define MMAP_LOTSAMISS (100) /* * Synchronous readahead happens when we don't even find * a page in the page cache at all. */ static void do_sync_mmap_readahead(struct vm_area_struct *vma, struct file_ra_state *ra, struct file *file, pgoff_t offset) { unsigned long ra_pages; struct address_space *mapping = file->f_mapping; /* If we don't want any read-ahead, don't bother */ if (VM_RandomReadHint(vma)) return; if (!ra->ra_pages) return; if (VM_SequentialReadHint(vma)) { page_cache_sync_readahead(mapping, ra, file, offset, ra->ra_pages); return; } /* Avoid banging the cache line if not needed */ if (ra->mmap_miss < MMAP_LOTSAMISS * 10) ra->mmap_miss++; /* * Do we miss much more than hit in this file? If so, * stop bothering with read-ahead. It will only hurt. */ if (ra->mmap_miss > MMAP_LOTSAMISS) return; /* * mmap read-around */ ra_pages = max_sane_readahead(ra->ra_pages); ra->start = max_t(long, 0, offset - ra_pages / 2); ra->size = ra_pages; ra->async_size = ra_pages / 4; ra_submit(ra, mapping, file); } /* * Asynchronous readahead happens when we find the page and PG_readahead, * so we want to possibly extend the readahead further.. */ static void do_async_mmap_readahead(struct vm_area_struct *vma, struct file_ra_state *ra, struct file *file, struct page *page, pgoff_t offset) { struct address_space *mapping = file->f_mapping; /* If we don't want any read-ahead, don't bother */ if (VM_RandomReadHint(vma)) return; if (ra->mmap_miss > 0) ra->mmap_miss--; if (PageReadahead(page)) page_cache_async_readahead(mapping, ra, file, page, offset, ra->ra_pages); } /** * filemap_fault - read in file data for page fault handling * @vma: vma in which the fault was taken * @vmf: struct vm_fault containing details of the fault * * filemap_fault() is invoked via the vma operations vector for a * mapped memory region to read in file data during a page fault. * * The goto's are kind of ugly, but this streamlines the normal case of having * it in the page cache, and handles the special cases reasonably without * having a lot of duplicated code. */ int filemap_fault(struct vm_area_struct *vma, struct vm_fault *vmf) { int error; struct file *file = vma->vm_file; struct address_space *mapping = file->f_mapping; struct file_ra_state *ra = &file->f_ra; struct inode *inode = mapping->host; pgoff_t offset = vmf->pgoff; struct page *page; pgoff_t size; int ret = 0; size = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT; if (offset >= size) return VM_FAULT_SIGBUS; /* * Do we have something in the page cache already? */ page = find_get_page(mapping, offset); if (likely(page)) { /* * We found the page, so try async readahead before * waiting for the lock. */ do_async_mmap_readahead(vma, ra, file, page, offset); } else { /* No page in the page cache at all */ do_sync_mmap_readahead(vma, ra, file, offset); count_vm_event(PGMAJFAULT); /* */ sreadahead_prof(file, 0, 0); /* */ mem_cgroup_count_vm_event(vma->vm_mm, PGMAJFAULT); ret = VM_FAULT_MAJOR; retry_find: page = find_get_page(mapping, offset); if (!page) goto no_cached_page; } if (!lock_page_or_retry(page, vma->vm_mm, vmf->flags)) { page_cache_release(page); return ret | VM_FAULT_RETRY; } /* Did it get truncated? */ if (unlikely(page->mapping != mapping)) { unlock_page(page); put_page(page); goto retry_find; } VM_BUG_ON(page->index != offset); /* * We have a locked page in the page cache, now we need to check * that it's up-to-date. If not, it is going to be due to an error. */ if (unlikely(!PageUptodate(page))) goto page_not_uptodate; /* * Found the page and have a reference on it. * We must recheck i_size under page lock. */ size = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT; if (unlikely(offset >= size)) { unlock_page(page); page_cache_release(page); return VM_FAULT_SIGBUS; } vmf->page = page; return ret | VM_FAULT_LOCKED; no_cached_page: /* * We're only likely to ever get here if MADV_RANDOM is in * effect. */ error = page_cache_read(file, offset); /* * The page we want has now been added to the page cache. * In the unlikely event that someone removed it in the * meantime, we'll just come back here and read it again. */ if (error >= 0) goto retry_find; /* * An error return from page_cache_read can result if the * system is low on memory, or a problem occurs while trying * to schedule I/O. */ if (error == -ENOMEM) return VM_FAULT_OOM; return VM_FAULT_SIGBUS; page_not_uptodate: /* * Umm, take care of errors if the page isn't up-to-date. * Try to re-read it _once_. We do this synchronously, * because there really aren't any performance issues here * and we need to check for errors. */ ClearPageError(page); error = mapping->a_ops->readpage(file, page); if (!error) { wait_on_page_locked(page); if (!PageUptodate(page)) error = -EIO; } page_cache_release(page); if (!error || error == AOP_TRUNCATED_PAGE) goto retry_find; /* Things didn't work out. Return zero to tell the mm layer so. */ shrink_readahead_size_eio(file, ra); return VM_FAULT_SIGBUS; } EXPORT_SYMBOL(filemap_fault); int filemap_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf) { struct page *page = vmf->page; struct inode *inode = vma->vm_file->f_path.dentry->d_inode; int ret = VM_FAULT_LOCKED; sb_start_pagefault(inode->i_sb); file_update_time(vma->vm_file); lock_page(page); if (page->mapping != inode->i_mapping) { unlock_page(page); ret = VM_FAULT_NOPAGE; goto out; } /* * We mark the page dirty already here so that when freeze is in * progress, we are guaranteed that writeback during freezing will * see the dirty page and writeprotect it again. */ set_page_dirty(page); out: sb_end_pagefault(inode->i_sb); return ret; } EXPORT_SYMBOL(filemap_page_mkwrite); const struct vm_operations_struct generic_file_vm_ops = { .fault = filemap_fault, .page_mkwrite = filemap_page_mkwrite, }; /* This is used for a general mmap of a disk file */ int generic_file_mmap(struct file * file, struct vm_area_struct * vma) { struct address_space *mapping = file->f_mapping; if (!mapping->a_ops->readpage) return -ENOEXEC; file_accessed(file); vma->vm_ops = &generic_file_vm_ops; vma->vm_flags |= VM_CAN_NONLINEAR; return 0; } /* * This is for filesystems which do not implement ->writepage. */ int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma) { if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE)) return -EINVAL; return generic_file_mmap(file, vma); } #else int generic_file_mmap(struct file * file, struct vm_area_struct * vma) { return -ENOSYS; } int generic_file_readonly_mmap(struct file * file, struct vm_area_struct * vma) { return -ENOSYS; } #endif /* CONFIG_MMU */ EXPORT_SYMBOL(generic_file_mmap); EXPORT_SYMBOL(generic_file_readonly_mmap); static struct page *__read_cache_page(struct address_space *mapping, pgoff_t index, int (*filler)(void *, struct page *), void *data, gfp_t gfp) { struct page *page; int err; repeat: page = find_get_page(mapping, index); if (!page) { page = __page_cache_alloc(gfp | __GFP_COLD); if (!page) return ERR_PTR(-ENOMEM); err = add_to_page_cache_lru(page, mapping, index, gfp); if (unlikely(err)) { page_cache_release(page); if (err == -EEXIST) goto repeat; /* Presumably ENOMEM for radix tree node */ return ERR_PTR(err); } err = filler(data, page); if (err < 0) { page_cache_release(page); page = ERR_PTR(err); } } return page; } static struct page *do_read_cache_page(struct address_space *mapping, pgoff_t index, int (*filler)(void *, struct page *), void *data, gfp_t gfp) { struct page *page; int err; retry: page = __read_cache_page(mapping, index, filler, data, gfp); if (IS_ERR(page)) return page; if (PageUptodate(page)) goto out; lock_page(page); if (!page->mapping) { unlock_page(page); page_cache_release(page); goto retry; } if (PageUptodate(page)) { unlock_page(page); goto out; } err = filler(data, page); if (err < 0) { page_cache_release(page); return ERR_PTR(err); } out: mark_page_accessed(page); return page; } /** * read_cache_page_async - read into page cache, fill it if needed * @mapping: the page's address_space * @index: the page index * @filler: function to perform the read * @data: first arg to filler(data, page) function, often left as NULL * * Same as read_cache_page, but don't wait for page to become unlocked * after submitting it to the filler. * * Read into the page cache. If a page already exists, and PageUptodate() is * not set, try to fill the page but don't wait for it to become unlocked. * * If the page does not get brought uptodate, return -EIO. */ struct page *read_cache_page_async(struct address_space *mapping, pgoff_t index, int (*filler)(void *, struct page *), void *data) { return do_read_cache_page(mapping, index, filler, data, mapping_gfp_mask(mapping)); } EXPORT_SYMBOL(read_cache_page_async); static struct page *wait_on_page_read(struct page *page) { if (!IS_ERR(page)) { wait_on_page_locked(page); if (!PageUptodate(page)) { page_cache_release(page); page = ERR_PTR(-EIO); } } return page; } /** * read_cache_page_gfp - read into page cache, using specified page allocation flags. * @mapping: the page's address_space * @index: the page index * @gfp: the page allocator flags to use if allocating * * This is the same as "read_mapping_page(mapping, index, NULL)", but with * any new page allocations done using the specified allocation flags. * * If the page does not get brought uptodate, return -EIO. */ struct page *read_cache_page_gfp(struct address_space *mapping, pgoff_t index, gfp_t gfp) { filler_t *filler = (filler_t *)mapping->a_ops->readpage; return wait_on_page_read(do_read_cache_page(mapping, index, filler, NULL, gfp)); } EXPORT_SYMBOL(read_cache_page_gfp); /** * read_cache_page - read into page cache, fill it if needed * @mapping: the page's address_space * @index: the page index * @filler: function to perform the read * @data: first arg to filler(data, page) function, often left as NULL * * Read into the page cache. If a page already exists, and PageUptodate() is * not set, try to fill the page then wait for it to become unlocked. * * If the page does not get brought uptodate, return -EIO. */ struct page *read_cache_page(struct address_space *mapping, pgoff_t index, int (*filler)(void *, struct page *), void *data) { return wait_on_page_read(read_cache_page_async(mapping, index, filler, data)); } EXPORT_SYMBOL(read_cache_page); /* * The logic we want is * * if suid or (sgid and xgrp) * remove privs */ int should_remove_suid(struct dentry *dentry) { umode_t mode = dentry->d_inode->i_mode; int kill = 0; /* suid always must be killed */ if (unlikely(mode & S_ISUID)) kill = ATTR_KILL_SUID; /* * sgid without any exec bits is just a mandatory locking mark; leave * it alone. If some exec bits are set, it's a real sgid; kill it. */ if (unlikely((mode & S_ISGID) && (mode & S_IXGRP))) kill |= ATTR_KILL_SGID; if (unlikely(kill && !capable(CAP_FSETID) && S_ISREG(mode))) return kill; return 0; } EXPORT_SYMBOL(should_remove_suid); static int __remove_suid(struct dentry *dentry, int kill) { struct iattr newattrs; newattrs.ia_valid = ATTR_FORCE | kill; return notify_change(dentry, &newattrs); } int file_remove_suid(struct file *file) { struct dentry *dentry = file->f_path.dentry; struct inode *inode = dentry->d_inode; int killsuid; int killpriv; int error = 0; /* Fast path for nothing security related */ if (IS_NOSEC(inode)) return 0; killsuid = should_remove_suid(dentry); killpriv = security_inode_need_killpriv(dentry); if (killpriv < 0) return killpriv; if (killpriv) error = security_inode_killpriv(dentry); if (!error && killsuid) error = __remove_suid(dentry, killsuid); if (!error && (inode->i_sb->s_flags & MS_NOSEC)) inode->i_flags |= S_NOSEC; return error; } EXPORT_SYMBOL(file_remove_suid); /* * Performs necessary checks before doing a write * * Can adjust writing position or amount of bytes to write. * Returns appropriate error code that caller should return or * zero in case that write should be allowed. */ inline int generic_write_checks(struct file *file, loff_t *pos, size_t *count, int isblk) { struct inode *inode = file->f_mapping->host; unsigned long limit = rlimit(RLIMIT_FSIZE); if (unlikely(*pos < 0)) return -EINVAL; if (!isblk) { /* FIXME: this is for backwards compatibility with 2.4 */ if (file->f_flags & O_APPEND) *pos = i_size_read(inode); if (limit != RLIM_INFINITY) { if (*pos >= limit) { send_sig(SIGXFSZ, current, 0); return -EFBIG; } if (*count > limit - (typeof(limit))*pos) { *count = limit - (typeof(limit))*pos; } } } /* * LFS rule */ if (unlikely(*pos + *count > MAX_NON_LFS && !(file->f_flags & O_LARGEFILE))) { if (*pos >= MAX_NON_LFS) { return -EFBIG; } if (*count > MAX_NON_LFS - (unsigned long)*pos) { *count = MAX_NON_LFS - (unsigned long)*pos; } } /* * Are we about to exceed the fs block limit ? * * If we have written data it becomes a short write. If we have * exceeded without writing data we send a signal and return EFBIG. * Linus frestrict idea will clean these up nicely.. */ if (likely(!isblk)) { if (unlikely(*pos >= inode->i_sb->s_maxbytes)) { if (*count || *pos > inode->i_sb->s_maxbytes) { return -EFBIG; } /* zero-length writes at ->s_maxbytes are OK */ } if (unlikely(*pos + *count > inode->i_sb->s_maxbytes)) *count = inode->i_sb->s_maxbytes - *pos; } else { #ifdef CONFIG_BLOCK loff_t isize; if (bdev_read_only(I_BDEV(inode))) return -EPERM; isize = i_size_read(inode); if (*pos >= isize) { if (*count || *pos > isize) return -ENOSPC; } if (*pos + *count > isize) *count = isize - *pos; #else return -EPERM; #endif } return 0; } EXPORT_SYMBOL(generic_write_checks); int pagecache_write_begin(struct file *file, struct address_space *mapping, loff_t pos, unsigned len, unsigned flags, struct page **pagep, void **fsdata) { const struct address_space_operations *aops = mapping->a_ops; return aops->write_begin(file, mapping, pos, len, flags, pagep, fsdata); } EXPORT_SYMBOL(pagecache_write_begin); int pagecache_write_end(struct file *file, struct address_space *mapping, loff_t pos, unsigned len, unsigned copied, struct page *page, void *fsdata) { const struct address_space_operations *aops = mapping->a_ops; mark_page_accessed(page); return aops->write_end(file, mapping, pos, len, copied, page, fsdata); } EXPORT_SYMBOL(pagecache_write_end); ssize_t generic_file_direct_write_iter(struct kiocb *iocb, struct iov_iter *iter, loff_t pos, loff_t *ppos, size_t count) { struct file *file = iocb->ki_filp; struct address_space *mapping = file->f_mapping; struct inode *inode = mapping->host; ssize_t written; size_t write_len; pgoff_t end; if (count != iov_iter_count(iter)) { written = iov_iter_shorten(iter, count); if (written) goto out; } write_len = count; end = (pos + write_len - 1) >> PAGE_CACHE_SHIFT; written = filemap_write_and_wait_range(mapping, pos, pos + write_len - 1); if (written) goto out; /* * After a write we want buffered reads to be sure to go to disk to get * the new data. We invalidate clean cached page from the region we're * about to write. We do this *before* the write so that we can return * without clobbering -EIOCBQUEUED from ->direct_IO(). */ if (mapping->nrpages) { written = invalidate_inode_pages2_range(mapping, pos >> PAGE_CACHE_SHIFT, end); /* * If a page can not be invalidated, return 0 to fall back * to buffered write. */ if (written) { if (written == -EBUSY) return 0; goto out; } } written = mapping->a_ops->direct_IO(WRITE, iocb, iter, pos); /* * Finally, try again to invalidate clean pages which might have been * cached by non-direct readahead, or faulted in by get_user_pages() * if the source of the write was an mmap'ed region of the file * we're writing. Either one is a pretty crazy thing to do, * so we don't support it 100%. If this invalidation * fails, tough, the write still worked... */ if (mapping->nrpages) { invalidate_inode_pages2_range(mapping, pos >> PAGE_CACHE_SHIFT, end); } if (written > 0) { pos += written; if (pos > i_size_read(inode) && !S_ISBLK(inode->i_mode)) { i_size_write(inode, pos); mark_inode_dirty(inode); } *ppos = pos; } out: return written; } EXPORT_SYMBOL(generic_file_direct_write_iter); ssize_t generic_file_direct_write(struct kiocb *iocb, const struct iovec *iov, unsigned long *nr_segs, loff_t pos, loff_t *ppos, size_t count, size_t ocount) { struct iov_iter iter; ssize_t ret; iov_iter_init(&iter, iov, *nr_segs, ocount, 0); ret = generic_file_direct_write_iter(iocb, &iter, pos, ppos, count); /* generic_file_direct_write_iter() might have shortened the vec */ if (*nr_segs != iter.nr_segs) *nr_segs = iter.nr_segs; return ret; } EXPORT_SYMBOL(generic_file_direct_write); /* * Find or create a page at the given pagecache position. Return the locked * page. This function is specifically for buffered writes. */ struct page *grab_cache_page_write_begin(struct address_space *mapping, pgoff_t index, unsigned flags) { int status; gfp_t gfp_mask; struct page *page; gfp_t gfp_notmask = 0; gfp_mask = mapping_gfp_mask(mapping); if (mapping_cap_account_dirty(mapping)) gfp_mask |= __GFP_WRITE; if (flags & AOP_FLAG_NOFS) gfp_notmask = __GFP_FS; repeat: page = find_lock_page(mapping, index); if (page) goto found; retry: page = __page_cache_alloc(gfp_mask & ~gfp_notmask); if (!page) return NULL; if (is_cma_pageblock(page)) { __free_page(page); gfp_notmask |= __GFP_MOVABLE; goto retry; } status = add_to_page_cache_lru(page, mapping, index, GFP_KERNEL & ~gfp_notmask); if (unlikely(status)) { page_cache_release(page); if (status == -EEXIST) goto repeat; return NULL; } found: wait_on_page_writeback(page); return page; } EXPORT_SYMBOL(grab_cache_page_write_begin); static ssize_t generic_perform_write(struct file *file, struct iov_iter *i, loff_t pos) { struct address_space *mapping = file->f_mapping; const struct address_space_operations *a_ops = mapping->a_ops; long status = 0; ssize_t written = 0; unsigned int flags = 0; /* * Copies from kernel address space cannot fail (NFSD is a big user). */ if (segment_eq(get_fs(), KERNEL_DS)) flags |= AOP_FLAG_UNINTERRUPTIBLE; do { struct page *page; unsigned long offset; /* Offset into pagecache page */ unsigned long bytes; /* Bytes to write to page */ size_t copied; /* Bytes copied from user */ void *fsdata; offset = (pos & (PAGE_CACHE_SIZE - 1)); bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset, iov_iter_count(i)); again: /* * Bring in the user page that we will copy from _first_. * Otherwise there's a nasty deadlock on copying from the * same page as we're writing to, without it being marked * up-to-date. * * Not only is this an optimisation, but it is also required * to check that the address is actually valid, when atomic * usercopies are used, below. */ if (unlikely(iov_iter_fault_in_readable(i, bytes))) { status = -EFAULT; break; } status = a_ops->write_begin(file, mapping, pos, bytes, flags, &page, &fsdata); if (unlikely(status)) break; if (mapping_writably_mapped(mapping)) flush_dcache_page(page); pagefault_disable(); copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes); pagefault_enable(); flush_dcache_page(page); mark_page_accessed(page); status = a_ops->write_end(file, mapping, pos, bytes, copied, page, fsdata); if (unlikely(status < 0)) break; copied = status; cond_resched(); iov_iter_advance(i, copied); if (unlikely(copied == 0)) { /* * If we were unable to copy any data at all, we must * fall back to a single segment length write. * * If we didn't fallback here, we could livelock * because not all segments in the iov can be copied at * once without a pagefault. */ bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset, iov_iter_single_seg_count(i)); goto again; } pos += copied; written += copied; balance_dirty_pages_ratelimited(mapping); if (fatal_signal_pending(current)) { status = -EINTR; break; } } while (iov_iter_count(i)); return written ? written : status; } ssize_t generic_file_buffered_write_iter(struct kiocb *iocb, struct iov_iter *iter, loff_t pos, loff_t *ppos, size_t count, ssize_t written) { struct file *file = iocb->ki_filp; ssize_t status; if ((count + written) != iov_iter_count(iter)) { int rc = iov_iter_shorten(iter, count + written); if (rc) return rc; } status = generic_perform_write(file, iter, pos); if (likely(status >= 0)) { written += status; *ppos = pos + status; } return written ? written : status; } EXPORT_SYMBOL(generic_file_buffered_write_iter); ssize_t generic_file_buffered_write(struct kiocb *iocb, const struct iovec *iov, unsigned long nr_segs, loff_t pos, loff_t *ppos, size_t count, ssize_t written) { struct iov_iter iter; iov_iter_init(&iter, iov, nr_segs, count, written); return generic_file_buffered_write_iter(iocb, &iter, pos, ppos, count, written); } EXPORT_SYMBOL(generic_file_buffered_write); /** * __generic_file_aio_write - write data to a file * @iocb: IO state structure (file, offset, etc.) * @iter: iov_iter specifying memory to write * @ppos: position where to write * * This function does all the work needed for actually writing data to a * file. It does all basic checks, removes SUID from the file, updates * modification times and calls proper subroutines depending on whether we * do direct IO or a standard buffered write. * * It expects i_mutex to be grabbed unless we work on a block device or similar * object which does not need locking at all. * * This function does *not* take care of syncing data in case of O_SYNC write. * A caller has to handle it. This is mainly due to the fact that we want to * avoid syncing under i_mutex. */ ssize_t __generic_file_write_iter(struct kiocb *iocb, struct iov_iter *iter, loff_t *ppos) { struct file *file = iocb->ki_filp; struct address_space * mapping = file->f_mapping; size_t count; /* after file limit checks */ struct inode *inode = mapping->host; loff_t pos; ssize_t written; ssize_t err; count = iov_iter_count(iter); pos = *ppos; /* We can write back this queue in page reclaim */ current->backing_dev_info = mapping->backing_dev_info; written = 0; err = generic_write_checks(file, &pos, &count, S_ISBLK(inode->i_mode)); if (err) goto out; if (count == 0) goto out; err = file_remove_suid(file); if (err) goto out; err = file_update_time(file); if (err) goto out; /* coalesce the iovecs and go direct-to-BIO for O_DIRECT */ if (unlikely(file->f_flags & O_DIRECT)) { loff_t endbyte; ssize_t written_buffered; written = generic_file_direct_write_iter(iocb, iter, pos, ppos, count); if (written < 0 || written == count) goto out; /* * direct-io write to a hole: fall through to buffered I/O * for completing the rest of the request. */ pos += written; count -= written; iov_iter_advance(iter, written); written_buffered = generic_file_buffered_write_iter(iocb, iter, pos, ppos, count, written); /* * If generic_file_buffered_write() retuned a synchronous error * then we want to return the number of bytes which were * direct-written, or the error code if that was zero. Note * that this differs from normal direct-io semantics, which * will return -EFOO even if some bytes were written. */ if (written_buffered < 0) { err = written_buffered; goto out; } /* * We need to ensure that the page cache pages are written to * disk and invalidated to preserve the expected O_DIRECT * semantics. */ endbyte = pos + written_buffered - written - 1; err = filemap_write_and_wait_range(file->f_mapping, pos, endbyte); if (err == 0) { written = written_buffered; invalidate_mapping_pages(mapping, pos >> PAGE_CACHE_SHIFT, endbyte >> PAGE_CACHE_SHIFT); } else { /* * We don't know how much we wrote, so just return * the number of bytes which were direct-written */ } } else { iter->count = count; written = generic_file_buffered_write_iter(iocb, iter, pos, ppos, count, written); } out: current->backing_dev_info = NULL; return written ? written : err; } EXPORT_SYMBOL(__generic_file_write_iter); ssize_t generic_file_write_iter(struct kiocb *iocb, struct iov_iter *iter, loff_t pos) { struct file *file = iocb->ki_filp; struct inode *inode = file->f_mapping->host; ssize_t ret; mutex_lock(&inode->i_mutex); ret = __generic_file_write_iter(iocb, iter, &iocb->ki_pos); mutex_unlock(&inode->i_mutex); if (ret > 0 || ret == -EIOCBQUEUED) { ssize_t err; err = generic_write_sync(file, pos, ret); if (err < 0 && ret > 0) ret = err; } return ret; } EXPORT_SYMBOL(generic_file_write_iter); ssize_t __generic_file_aio_write(struct kiocb *iocb, const struct iovec *iov, unsigned long nr_segs, loff_t *ppos) { struct iov_iter iter; size_t count; int ret; count = 0; ret = generic_segment_checks(iov, &nr_segs, &count, VERIFY_READ); if (ret) goto out; iov_iter_init(&iter, iov, nr_segs, count, 0); ret = __generic_file_write_iter(iocb, &iter, ppos); out: return ret; } EXPORT_SYMBOL(__generic_file_aio_write); /** * generic_file_aio_write - write data to a file * @iocb: IO state structure * @iov: vector with data to write * @nr_segs: number of segments in the vector * @pos: position in file where to write * * This is a wrapper around __generic_file_aio_write() to be used by most * filesystems. It takes care of syncing the file in case of O_SYNC file * and acquires i_mutex as needed. */ ssize_t generic_file_aio_write(struct kiocb *iocb, const struct iovec *iov, unsigned long nr_segs, loff_t pos) { struct file *file = iocb->ki_filp; struct inode *inode = file->f_mapping->host; struct blk_plug plug; ssize_t ret; BUG_ON(iocb->ki_pos != pos); sb_start_write(inode->i_sb); mutex_lock(&inode->i_mutex); blk_start_plug(&plug); ret = __generic_file_aio_write(iocb, iov, nr_segs, &iocb->ki_pos); mutex_unlock(&inode->i_mutex); if (ret > 0 || ret == -EIOCBQUEUED) { ssize_t err; err = generic_write_sync(file, pos, ret); if (err < 0 && ret > 0) ret = err; } blk_finish_plug(&plug); sb_end_write(inode->i_sb); return ret; } EXPORT_SYMBOL(generic_file_aio_write); /** * try_to_release_page() - release old fs-specific metadata on a page * * @page: the page which the kernel is trying to free * @gfp_mask: memory allocation flags (and I/O mode) * * The address_space is to try to release any data against the page * (presumably at page->private). If the release was successful, return `1'. * Otherwise return zero. * * This may also be called if PG_fscache is set on a page, indicating that the * page is known to the local caching routines. * * The @gfp_mask argument specifies whether I/O may be performed to release * this page (__GFP_IO), and whether the call may block (__GFP_WAIT & __GFP_FS). * */ int try_to_release_page(struct page *page, gfp_t gfp_mask) { struct address_space * const mapping = page->mapping; BUG_ON(!PageLocked(page)); if (PageWriteback(page)) return 0; if (mapping && mapping->a_ops->releasepage) return mapping->a_ops->releasepage(page, gfp_mask); return try_to_free_buffers(page); } EXPORT_SYMBOL(try_to_release_page);
shengdie/Dorimanx-LG-G2-D802-Kernel
mm/filemap.c
C
gpl-2.0
68,410
#ifndef PERF_LINUX_LINKAGE_H_ #define PERF_LINUX_LINKAGE_H_ /* linkage.h ... for including arch/x86/lib/memcpy_64.S */ #define ENTRY(name) \ .globl name; \ name: #define ENDPROC(name) #endif /* PERF_LINUX_LINKAGE_H_ */
andi34/kernel_samsung_espresso-cm
tools/perf/util/include/linux/linkage.h
C
gpl-2.0
231
#pragma once #include <Nena\Window.h> #include <Nena\StepTimer.h> #include <Nena\DeviceResources.h> #include <Nena\RenderTargetOverlay.h> #include "TextRenderer.h" namespace Framework { namespace Application { void Start(); void Stop(); struct Window; struct Dispatcher { Framework::Application::Window *Host; Framework::Application::Dispatcher::Dispatcher( Framework::Application::Window *host ); LRESULT Framework::Application::Dispatcher::Process( _In_::HWND hwnd, _In_::UINT umsg, _In_::WPARAM wparam, _In_::LPARAM lparam ); }; struct WindowDeviceNotify : Nena::Graphics::IDeviceNotify { Framework::Application::Window *Host; Framework::Application::WindowDeviceNotify::WindowDeviceNotify(Framework::Application::Window *host); virtual void OnDeviceLost() override; virtual void OnDeviceRestored() override; }; struct Window : Nena::Application::Window { friend WindowDeviceNotify; Framework::Application::Window::Window(); ::BOOL Framework::Application::Window::Update(); LRESULT Framework::Application::Window::OnMouseLeftButtonPressed(_In_ ::INT16 x, _In_ ::INT16 y); LRESULT Framework::Application::Window::OnMouseRightButtonPressed(_In_ ::INT16 x, _In_ ::INT16 y); LRESULT Framework::Application::Window::OnMouseLeftButtonReleased(_In_ ::INT16 x, _In_ ::INT16 y); LRESULT Framework::Application::Window::OnMouseRightButtonReleased(_In_::INT16 x, _In_::INT16 y); LRESULT Framework::Application::Window::OnMouseMoved(_In_::INT16 x, _In_::INT16 y); LRESULT Framework::Application::Window::OnKeyPressed(::UINT16 virtualKey); LRESULT Framework::Application::Window::OnResized(); static Framework::Application::Window *Framework::Application::Window::GetForCurrentThread(); Nena::Graphics::OverlayResources Overlay; Nena::Graphics::DeviceResources Graphics; Nena::Simulation::StepTimer Timer; TextRenderer Renderer; WindowDeviceNotify DeviceNotify; Dispatcher EventHandler; }; } }
VladSerhiienko/Nena.v.1
Demo/SimpleText/Framework.h
C
gpl-2.0
2,024
/* Map (unsigned int) keys to (source file, line, column) triples. Copyright (C) 2001-2016 Free Software Foundation, Inc. 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 3, 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; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. In other words, you are welcome to use, share and improve this program. You are forbidden to forbid anyone else to use, share and improve what you give them. Help stamp out software-hoarding! */ #include "config.h" #include "system.h" #include "line-map.h" #include "cpplib.h" #include "internal.h" #include "hashtab.h" /* Do not track column numbers higher than this one. As a result, the range of column_bits is [12, 18] (or 0 if column numbers are disabled). */ const unsigned int LINE_MAP_MAX_COLUMN_NUMBER = (1U << 12); /* Do not pack ranges if locations get higher than this. If you change this, update: gcc.dg/plugin/location_overflow_plugin.c gcc.dg/plugin/location-overflow-test-*.c. */ const source_location LINE_MAP_MAX_LOCATION_WITH_PACKED_RANGES = 0x50000000; /* Do not track column numbers if locations get higher than this. If you change this, update: gcc.dg/plugin/location_overflow_plugin.c gcc.dg/plugin/location-overflow-test-*.c. */ const source_location LINE_MAP_MAX_LOCATION_WITH_COLS = 0x60000000; /* Highest possible source location encoded within an ordinary or macro map. */ const source_location LINE_MAP_MAX_SOURCE_LOCATION = 0x70000000; static void trace_include (const struct line_maps *, const line_map_ordinary *); static const line_map_ordinary * linemap_ordinary_map_lookup (struct line_maps *, source_location); static const line_map_macro* linemap_macro_map_lookup (struct line_maps *, source_location); static source_location linemap_macro_map_loc_to_def_point (const line_map_macro *, source_location); static source_location linemap_macro_map_loc_unwind_toward_spelling (line_maps *set, const line_map_macro *, source_location); static source_location linemap_macro_map_loc_to_exp_point (const line_map_macro *, source_location); static source_location linemap_macro_loc_to_spelling_point (struct line_maps *, source_location, const line_map_ordinary **); static source_location linemap_macro_loc_to_def_point (struct line_maps *, source_location, const line_map_ordinary **); static source_location linemap_macro_loc_to_exp_point (struct line_maps *, source_location, const line_map_ordinary **); /* Counters defined in macro.c. */ extern unsigned num_expanded_macros_counter; extern unsigned num_macro_tokens_counter; /* Hash function for location_adhoc_data hashtable. */ static hashval_t location_adhoc_data_hash (const void *l) { const struct location_adhoc_data *lb = (const struct location_adhoc_data *) l; return ((hashval_t) lb->locus + (hashval_t) lb->src_range.m_start + (hashval_t) lb->src_range.m_finish + (size_t) lb->data); } /* Compare function for location_adhoc_data hashtable. */ static int location_adhoc_data_eq (const void *l1, const void *l2) { const struct location_adhoc_data *lb1 = (const struct location_adhoc_data *) l1; const struct location_adhoc_data *lb2 = (const struct location_adhoc_data *) l2; return (lb1->locus == lb2->locus && lb1->src_range.m_start == lb2->src_range.m_start && lb1->src_range.m_finish == lb2->src_range.m_finish && lb1->data == lb2->data); } /* Update the hashtable when location_adhoc_data is reallocated. */ static int location_adhoc_data_update (void **slot, void *data) { *((char **) slot) += *((long long *) data); return 1; } /* Rebuild the hash table from the location adhoc data. */ void rebuild_location_adhoc_htab (struct line_maps *set) { unsigned i; set->location_adhoc_data_map.htab = htab_create (100, location_adhoc_data_hash, location_adhoc_data_eq, NULL); for (i = 0; i < set->location_adhoc_data_map.curr_loc; i++) htab_find_slot (set->location_adhoc_data_map.htab, set->location_adhoc_data_map.data + i, INSERT); } /* Helper function for get_combined_adhoc_loc. Can the given LOCUS + SRC_RANGE and DATA pointer be stored compactly within a source_location, without needing to use an ad-hoc location. */ static bool can_be_stored_compactly_p (struct line_maps *set, source_location locus, source_range src_range, void *data) { /* If there's an ad-hoc pointer, we can't store it directly in the source_location, we need the lookaside. */ if (data) return false; /* We only store ranges that begin at the locus and that are sufficiently "sane". */ if (src_range.m_start != locus) return false; if (src_range.m_finish < src_range.m_start) return false; if (src_range.m_start < RESERVED_LOCATION_COUNT) return false; if (locus >= LINE_MAP_MAX_LOCATION_WITH_PACKED_RANGES) return false; /* All 3 locations must be within ordinary maps, typically, the same ordinary map. */ source_location lowest_macro_loc = LINEMAPS_MACRO_LOWEST_LOCATION (set); if (locus >= lowest_macro_loc) return false; if (src_range.m_start >= lowest_macro_loc) return false; if (src_range.m_finish >= lowest_macro_loc) return false; /* Passed all tests. */ return true; } /* Combine LOCUS and DATA to a combined adhoc loc. */ source_location get_combined_adhoc_loc (struct line_maps *set, source_location locus, source_range src_range, void *data) { struct location_adhoc_data lb; struct location_adhoc_data **slot; if (IS_ADHOC_LOC (locus)) locus = set->location_adhoc_data_map.data[locus & MAX_SOURCE_LOCATION].locus; if (locus == 0 && data == NULL) return 0; /* Any ordinary locations ought to be "pure" at this point: no compressed ranges. */ linemap_assert (locus < RESERVED_LOCATION_COUNT || locus >= LINE_MAP_MAX_LOCATION_WITH_PACKED_RANGES || locus >= LINEMAPS_MACRO_LOWEST_LOCATION (set) || pure_location_p (set, locus)); /* Consider short-range optimization. */ if (can_be_stored_compactly_p (set, locus, src_range, data)) { /* The low bits ought to be clear. */ linemap_assert (pure_location_p (set, locus)); const line_map *map = linemap_lookup (set, locus); const line_map_ordinary *ordmap = linemap_check_ordinary (map); unsigned int int_diff = src_range.m_finish - src_range.m_start; unsigned int col_diff = (int_diff >> ordmap->m_range_bits); if (col_diff < (1U << ordmap->m_range_bits)) { source_location packed = locus | col_diff; set->num_optimized_ranges++; return packed; } } /* We can also compactly store locations when locus == start == finish (and data is NULL). */ if (locus == src_range.m_start && locus == src_range.m_finish && !data) return locus; if (!data) set->num_unoptimized_ranges++; lb.locus = locus; lb.src_range = src_range; lb.data = data; slot = (struct location_adhoc_data **) htab_find_slot (set->location_adhoc_data_map.htab, &lb, INSERT); if (*slot == NULL) { if (set->location_adhoc_data_map.curr_loc >= set->location_adhoc_data_map.allocated) { char *orig_data = (char *) set->location_adhoc_data_map.data; long long offset; /* Cast away extern "C" from the type of xrealloc. */ line_map_realloc reallocator = (set->reallocator ? set->reallocator : (line_map_realloc) xrealloc); if (set->location_adhoc_data_map.allocated == 0) set->location_adhoc_data_map.allocated = 128; else set->location_adhoc_data_map.allocated *= 2; set->location_adhoc_data_map.data = (struct location_adhoc_data *) reallocator (set->location_adhoc_data_map.data, set->location_adhoc_data_map.allocated * sizeof (struct location_adhoc_data)); offset = (char *) (set->location_adhoc_data_map.data) - orig_data; if (set->location_adhoc_data_map.allocated > 128) htab_traverse (set->location_adhoc_data_map.htab, location_adhoc_data_update, &offset); } *slot = set->location_adhoc_data_map.data + set->location_adhoc_data_map.curr_loc; set->location_adhoc_data_map.data[set->location_adhoc_data_map.curr_loc++] = lb; } return ((*slot) - set->location_adhoc_data_map.data) | 0x80000000; } /* Return the data for the adhoc loc. */ void * get_data_from_adhoc_loc (struct line_maps *set, source_location loc) { linemap_assert (IS_ADHOC_LOC (loc)); return set->location_adhoc_data_map.data[loc & MAX_SOURCE_LOCATION].data; } /* Return the location for the adhoc loc. */ source_location get_location_from_adhoc_loc (struct line_maps *set, source_location loc) { linemap_assert (IS_ADHOC_LOC (loc)); return set->location_adhoc_data_map.data[loc & MAX_SOURCE_LOCATION].locus; } /* Return the source_range for adhoc location LOC. */ static source_range get_range_from_adhoc_loc (struct line_maps *set, source_location loc) { linemap_assert (IS_ADHOC_LOC (loc)); return set->location_adhoc_data_map.data[loc & MAX_SOURCE_LOCATION].src_range; } /* Get the source_range of location LOC, either from the ad-hoc lookaside table, or embedded inside LOC itself. */ source_range get_range_from_loc (struct line_maps *set, source_location loc) { if (IS_ADHOC_LOC (loc)) return get_range_from_adhoc_loc (set, loc); /* For ordinary maps, extract packed range. */ if (loc >= RESERVED_LOCATION_COUNT && loc < LINEMAPS_MACRO_LOWEST_LOCATION (set) && loc <= LINE_MAP_MAX_LOCATION_WITH_PACKED_RANGES) { const line_map *map = linemap_lookup (set, loc); const line_map_ordinary *ordmap = linemap_check_ordinary (map); source_range result; int offset = loc & ((1 << ordmap->m_range_bits) - 1); result.m_start = loc - offset; result.m_finish = result.m_start + (offset << ordmap->m_range_bits); return result; } return source_range::from_location (loc); } /* Get whether location LOC is a "pure" location, or whether it is an ad-hoc location, or embeds range information. */ bool pure_location_p (line_maps *set, source_location loc) { if (IS_ADHOC_LOC (loc)) return false; const line_map *map = linemap_lookup (set, loc); const line_map_ordinary *ordmap = linemap_check_ordinary (map); if (loc & ((1U << ordmap->m_range_bits) - 1)) return false; return true; } /* Finalize the location_adhoc_data structure. */ void location_adhoc_data_fini (struct line_maps *set) { htab_delete (set->location_adhoc_data_map.htab); } /* Initialize a line map set. */ void linemap_init (struct line_maps *set, source_location builtin_location) { memset (set, 0, sizeof (struct line_maps)); set->highest_location = RESERVED_LOCATION_COUNT - 1; set->highest_line = RESERVED_LOCATION_COUNT - 1; set->location_adhoc_data_map.htab = htab_create (100, location_adhoc_data_hash, location_adhoc_data_eq, NULL); set->builtin_location = builtin_location; } /* Check for and warn about line_maps entered but not exited. */ void linemap_check_files_exited (struct line_maps *set) { const line_map_ordinary *map; /* Depending upon whether we are handling preprocessed input or not, this can be a user error or an ICE. */ for (map = LINEMAPS_LAST_ORDINARY_MAP (set); ! MAIN_FILE_P (map); map = INCLUDED_FROM (set, map)) fprintf (stderr, "line-map.c: file \"%s\" entered but not left\n", ORDINARY_MAP_FILE_NAME (map)); } /* Create a new line map in the line map set SET, and return it. REASON is the reason of creating the map. It determines the type of map created (ordinary or macro map). Note that ordinary maps and macro maps are allocated in different memory location. */ static struct line_map * new_linemap (struct line_maps *set, enum lc_reason reason) { /* Depending on this variable, a macro map would be allocated in a different memory location than an ordinary map. */ bool macro_map_p = (reason == LC_ENTER_MACRO); struct line_map *result; if (LINEMAPS_USED (set, macro_map_p) == LINEMAPS_ALLOCATED (set, macro_map_p)) { /* We ran out of allocated line maps. Let's allocate more. */ unsigned alloc_size; /* Cast away extern "C" from the type of xrealloc. */ line_map_realloc reallocator = (set->reallocator ? set->reallocator : (line_map_realloc) xrealloc); line_map_round_alloc_size_func round_alloc_size = set->round_alloc_size; size_t map_size = (macro_map_p ? sizeof (line_map_macro) : sizeof (line_map_ordinary)); /* We are going to execute some dance to try to reduce the overhead of the memory allocator, in case we are using the ggc-page.c one. The actual size of memory we are going to get back from the allocator is the smallest power of 2 that is greater than the size we requested. So let's consider that size then. */ alloc_size = (2 * LINEMAPS_ALLOCATED (set, macro_map_p) + 256) * map_size; /* Get the actual size of memory that is going to be allocated by the allocator. */ alloc_size = round_alloc_size (alloc_size); /* Now alloc_size contains the exact memory size we would get if we have asked for the initial alloc_size amount of memory. Let's get back to the number of macro map that amounts to. */ LINEMAPS_ALLOCATED (set, macro_map_p) = alloc_size / map_size; /* And now let's really do the re-allocation. */ if (macro_map_p) { set->info_macro.maps = (line_map_macro *) (*reallocator) (set->info_macro.maps, (LINEMAPS_ALLOCATED (set, macro_map_p) * map_size)); result = &set->info_macro.maps[LINEMAPS_USED (set, macro_map_p)]; } else { set->info_ordinary.maps = (line_map_ordinary *) (*reallocator) (set->info_ordinary.maps, (LINEMAPS_ALLOCATED (set, macro_map_p) * map_size)); result = &set->info_ordinary.maps[LINEMAPS_USED (set, macro_map_p)]; } memset (result, 0, ((LINEMAPS_ALLOCATED (set, macro_map_p) - LINEMAPS_USED (set, macro_map_p)) * map_size)); } else { if (macro_map_p) result = &set->info_macro.maps[LINEMAPS_USED (set, macro_map_p)]; else result = &set->info_ordinary.maps[LINEMAPS_USED (set, macro_map_p)]; } LINEMAPS_USED (set, macro_map_p)++; result->reason = reason; return result; } /* Add a mapping of logical source line to physical source file and line number. The text pointed to by TO_FILE must have a lifetime at least as long as the final call to lookup_line (). An empty TO_FILE means standard input. If reason is LC_LEAVE, and TO_FILE is NULL, then TO_FILE, TO_LINE and SYSP are given their natural values considering the file we are returning to. FROM_LINE should be monotonic increasing across calls to this function. A call to this function can relocate the previous set of maps, so any stored line_map pointers should not be used. */ const struct line_map * linemap_add (struct line_maps *set, enum lc_reason reason, unsigned int sysp, const char *to_file, linenum_type to_line) { /* Generate a start_location above the current highest_location. If possible, make the low range bits be zero. */ source_location start_location; if (set->highest_location < LINE_MAP_MAX_LOCATION_WITH_COLS) { start_location = set->highest_location + (1 << set->default_range_bits); if (set->default_range_bits) start_location &= ~((1 << set->default_range_bits) - 1); linemap_assert (0 == (start_location & ((1 << set->default_range_bits) - 1))); } else start_location = set->highest_location + 1; linemap_assert (!(LINEMAPS_ORDINARY_USED (set) && (start_location < MAP_START_LOCATION (LINEMAPS_LAST_ORDINARY_MAP (set))))); /* When we enter the file for the first time reason cannot be LC_RENAME. */ linemap_assert (!(set->depth == 0 && reason == LC_RENAME)); /* If we are leaving the main file, return a NULL map. */ if (reason == LC_LEAVE && MAIN_FILE_P (LINEMAPS_LAST_ORDINARY_MAP (set)) && to_file == NULL) { set->depth--; return NULL; } linemap_assert (reason != LC_ENTER_MACRO); line_map_ordinary *map = linemap_check_ordinary (new_linemap (set, reason)); if (to_file && *to_file == '\0' && reason != LC_RENAME_VERBATIM) to_file = "<stdin>"; if (reason == LC_RENAME_VERBATIM) reason = LC_RENAME; if (reason == LC_LEAVE) { /* When we are just leaving an "included" file, and jump to the next location inside the "includer" right after the #include "included", this variable points the map in use right before the #include "included", inside the same "includer" file. */ line_map_ordinary *from; bool error; if (MAIN_FILE_P (map - 1)) { /* So this _should_ mean we are leaving the main file -- effectively ending the compilation unit. But to_file not being NULL means the caller thinks we are leaving to another file. This is an erroneous behaviour but we'll try to recover from it. Let's pretend we are not leaving the main file. */ error = true; reason = LC_RENAME; from = map - 1; } else { /* (MAP - 1) points to the map we are leaving. The map from which (MAP - 1) got included should be the map that comes right before MAP in the same file. */ from = INCLUDED_FROM (set, map - 1); error = to_file && filename_cmp (ORDINARY_MAP_FILE_NAME (from), to_file); } /* Depending upon whether we are handling preprocessed input or not, this can be a user error or an ICE. */ if (error) fprintf (stderr, "line-map.c: file \"%s\" left but not entered\n", to_file); /* A TO_FILE of NULL is special - we use the natural values. */ if (error || to_file == NULL) { to_file = ORDINARY_MAP_FILE_NAME (from); to_line = SOURCE_LINE (from, from[1].start_location); sysp = ORDINARY_MAP_IN_SYSTEM_HEADER_P (from); } } map->sysp = sysp; map->start_location = start_location; map->to_file = to_file; map->to_line = to_line; LINEMAPS_ORDINARY_CACHE (set) = LINEMAPS_ORDINARY_USED (set) - 1; map->m_column_and_range_bits = 0; map->m_range_bits = 0; set->highest_location = start_location; set->highest_line = start_location; set->max_column_hint = 0; /* This assertion is placed after set->highest_location has been updated, since the latter affects linemap_location_from_macro_expansion_p, which ultimately affects pure_location_p. */ linemap_assert (pure_location_p (set, start_location)); if (reason == LC_ENTER) { map->included_from = set->depth == 0 ? -1 : (int) (LINEMAPS_ORDINARY_USED (set) - 2); set->depth++; if (set->trace_includes) trace_include (set, map); } else if (reason == LC_RENAME) map->included_from = ORDINARY_MAP_INCLUDER_FILE_INDEX (&map[-1]); else if (reason == LC_LEAVE) { set->depth--; map->included_from = ORDINARY_MAP_INCLUDER_FILE_INDEX (INCLUDED_FROM (set, map - 1)); } return map; } /* Returns TRUE if the line table set tracks token locations across macro expansion, FALSE otherwise. */ bool linemap_tracks_macro_expansion_locs_p (struct line_maps *set) { return LINEMAPS_MACRO_MAPS (set) != NULL; } /* Create a macro map. A macro map encodes source locations of tokens that are part of a macro replacement-list, at a macro expansion point. See the extensive comments of struct line_map and struct line_map_macro, in line-map.h. This map shall be created when the macro is expanded. The map encodes the source location of the expansion point of the macro as well as the "original" source location of each token that is part of the macro replacement-list. If a macro is defined but never expanded, it has no macro map. SET is the set of maps the macro map should be part of. MACRO_NODE is the macro which the new macro map should encode source locations for. EXPANSION is the location of the expansion point of MACRO. For function-like macros invocations, it's best to make it point to the closing parenthesis of the macro, rather than the the location of the first character of the macro. NUM_TOKENS is the number of tokens that are part of the replacement-list of MACRO. Note that when we run out of the integer space available for source locations, this function returns NULL. In that case, callers of this function cannot encode {line,column} pairs into locations of macro tokens anymore. */ const line_map_macro * linemap_enter_macro (struct line_maps *set, struct cpp_hashnode *macro_node, source_location expansion, unsigned int num_tokens) { line_map_macro *map; source_location start_location; /* Cast away extern "C" from the type of xrealloc. */ line_map_realloc reallocator = (set->reallocator ? set->reallocator : (line_map_realloc) xrealloc); start_location = LINEMAPS_MACRO_LOWEST_LOCATION (set) - num_tokens; if (start_location <= set->highest_line || start_location > LINEMAPS_MACRO_LOWEST_LOCATION (set)) /* We ran out of macro map space. */ return NULL; map = linemap_check_macro (new_linemap (set, LC_ENTER_MACRO)); map->start_location = start_location; map->macro = macro_node; map->n_tokens = num_tokens; map->macro_locations = (source_location*) reallocator (NULL, 2 * num_tokens * sizeof (source_location)); map->expansion = expansion; memset (MACRO_MAP_LOCATIONS (map), 0, num_tokens * sizeof (source_location)); LINEMAPS_MACRO_CACHE (set) = LINEMAPS_MACRO_USED (set) - 1; return map; } /* Create and return a virtual location for a token that is part of a macro expansion-list at a macro expansion point. See the comment inside struct line_map_macro to see what an expansion-list exactly is. A call to this function must come after a call to linemap_enter_macro. MAP is the map into which the source location is created. TOKEN_NO is the index of the token in the macro replacement-list, starting at number 0. ORIG_LOC is the location of the token outside of this macro expansion. If the token comes originally from the macro definition, it is the locus in the macro definition; otherwise it is a location in the context of the caller of this macro expansion (which is a virtual location or a source location if the caller is itself a macro expansion or not). ORIG_PARM_REPLACEMENT_LOC is the location in the macro definition, either of the token itself or of a macro parameter that it replaces. */ source_location linemap_add_macro_token (const line_map_macro *map, unsigned int token_no, source_location orig_loc, source_location orig_parm_replacement_loc) { source_location result; linemap_assert (linemap_macro_expansion_map_p (map)); linemap_assert (token_no < MACRO_MAP_NUM_MACRO_TOKENS (map)); MACRO_MAP_LOCATIONS (map)[2 * token_no] = orig_loc; MACRO_MAP_LOCATIONS (map)[2 * token_no + 1] = orig_parm_replacement_loc; result = MAP_START_LOCATION (map) + token_no; return result; } /* Return a source_location for the start (i.e. column==0) of (physical) line TO_LINE in the current source file (as in the most recent linemap_add). MAX_COLUMN_HINT is the highest column number we expect to use in this line (but it does not change the highest_location). */ source_location linemap_line_start (struct line_maps *set, linenum_type to_line, unsigned int max_column_hint) { line_map_ordinary *map = LINEMAPS_LAST_ORDINARY_MAP (set); source_location highest = set->highest_location; source_location r; linenum_type last_line = SOURCE_LINE (map, set->highest_line); int line_delta = to_line - last_line; bool add_map = false; linemap_assert (map->m_column_and_range_bits >= map->m_range_bits); int effective_column_bits = map->m_column_and_range_bits - map->m_range_bits; if (line_delta < 0 || (line_delta > 10 && line_delta * map->m_column_and_range_bits > 1000) || (max_column_hint >= (1U << effective_column_bits)) || (max_column_hint <= 80 && effective_column_bits >= 10) || (highest > LINE_MAP_MAX_LOCATION_WITH_PACKED_RANGES && map->m_range_bits > 0) || (highest > LINE_MAP_MAX_LOCATION_WITH_COLS && (set->max_column_hint || highest >= LINE_MAP_MAX_SOURCE_LOCATION))) add_map = true; else max_column_hint = set->max_column_hint; if (add_map) { int column_bits; int range_bits; if (max_column_hint > LINE_MAP_MAX_COLUMN_NUMBER || highest > LINE_MAP_MAX_LOCATION_WITH_COLS) { /* If the column number is ridiculous or we've allocated a huge number of source_locations, give up on column numbers (and on packed ranges). */ max_column_hint = 0; column_bits = 0; range_bits = 0; if (highest > LINE_MAP_MAX_SOURCE_LOCATION) return 0; } else { column_bits = 7; if (highest <= LINE_MAP_MAX_LOCATION_WITH_PACKED_RANGES) range_bits = set->default_range_bits; else range_bits = 0; while (max_column_hint >= (1U << column_bits)) column_bits++; max_column_hint = 1U << column_bits; column_bits += range_bits; } /* Allocate the new line_map. However, if the current map only has a single line we can sometimes just increase its column_bits instead. */ if (line_delta < 0 || last_line != ORDINARY_MAP_STARTING_LINE_NUMBER (map) || SOURCE_COLUMN (map, highest) >= (1U << column_bits) || range_bits < map->m_range_bits) map = linemap_check_ordinary (const_cast <line_map *> (linemap_add (set, LC_RENAME, ORDINARY_MAP_IN_SYSTEM_HEADER_P (map), ORDINARY_MAP_FILE_NAME (map), to_line))); map->m_column_and_range_bits = column_bits; map->m_range_bits = range_bits; r = (MAP_START_LOCATION (map) + ((to_line - ORDINARY_MAP_STARTING_LINE_NUMBER (map)) << column_bits)); } else r = set->highest_line + (line_delta << map->m_column_and_range_bits); /* Locations of ordinary tokens are always lower than locations of macro tokens. */ if (r >= LINEMAPS_MACRO_LOWEST_LOCATION (set)) return 0; set->highest_line = r; if (r > set->highest_location) set->highest_location = r; set->max_column_hint = max_column_hint; /* At this point, we expect one of: (a) the normal case: a "pure" location with 0 range bits, or (b) we've gone past LINE_MAP_MAX_LOCATION_WITH_COLS so can't track columns anymore (or ranges), or (c) we're in a region with a column hint exceeding LINE_MAP_MAX_COLUMN_NUMBER, so column-tracking is off, with column_bits == 0. */ linemap_assert (pure_location_p (set, r) || r >= LINE_MAP_MAX_LOCATION_WITH_COLS || map->m_column_and_range_bits == 0); linemap_assert (SOURCE_LINE (map, r) == to_line); return r; } /* Encode and return a source_location from a column number. The source line considered is the last source line used to call linemap_line_start, i.e, the last source line which a location was encoded from. */ source_location linemap_position_for_column (struct line_maps *set, unsigned int to_column) { source_location r = set->highest_line; linemap_assert (!linemap_macro_expansion_map_p (LINEMAPS_LAST_ORDINARY_MAP (set))); if (to_column >= set->max_column_hint) { if (r > LINE_MAP_MAX_LOCATION_WITH_COLS || to_column > LINE_MAP_MAX_COLUMN_NUMBER) { /* Running low on source_locations - disable column numbers. */ return r; } else { line_map_ordinary *map = LINEMAPS_LAST_ORDINARY_MAP (set); r = linemap_line_start (set, SOURCE_LINE (map, r), to_column + 50); } } line_map_ordinary *map = LINEMAPS_LAST_ORDINARY_MAP (set); r = r + (to_column << map->m_range_bits); if (r >= set->highest_location) set->highest_location = r; return r; } /* Encode and return a source location from a given line and column. */ source_location linemap_position_for_line_and_column (line_maps *set, const line_map_ordinary *ord_map, linenum_type line, unsigned column) { linemap_assert (ORDINARY_MAP_STARTING_LINE_NUMBER (ord_map) <= line); source_location r = MAP_START_LOCATION (ord_map); r += ((line - ORDINARY_MAP_STARTING_LINE_NUMBER (ord_map)) << ord_map->m_column_and_range_bits); if (r <= LINE_MAP_MAX_LOCATION_WITH_COLS) r += ((column & ((1 << ord_map->m_column_and_range_bits) - 1)) << ord_map->m_range_bits); source_location upper_limit = LINEMAPS_MACRO_LOWEST_LOCATION (set); if (r >= upper_limit) r = upper_limit - 1; if (r > set->highest_location) set->highest_location = r; return r; } /* Encode and return a source_location starting from location LOC and shifting it by OFFSET columns. This function does not support virtual locations. */ source_location linemap_position_for_loc_and_offset (struct line_maps *set, source_location loc, unsigned int offset) { const line_map_ordinary * map = NULL; if (IS_ADHOC_LOC (loc)) loc = set->location_adhoc_data_map.data[loc & MAX_SOURCE_LOCATION].locus; /* This function does not support virtual locations yet. */ if (linemap_assert_fails (!linemap_location_from_macro_expansion_p (set, loc))) return loc; if (offset == 0 /* Adding an offset to a reserved location (like UNKNOWN_LOCATION for the C/C++ FEs) does not really make sense. So let's leave the location intact in that case. */ || loc < RESERVED_LOCATION_COUNT) return loc; /* We find the real location and shift it. */ loc = linemap_resolve_location (set, loc, LRK_SPELLING_LOCATION, &map); /* The new location (loc + offset) should be higher than the first location encoded by MAP. This can fail if the line information is messed up because of line directives (see PR66415). */ if (MAP_START_LOCATION (map) >= loc + offset) return loc; linenum_type line = SOURCE_LINE (map, loc); unsigned int column = SOURCE_COLUMN (map, loc); /* If MAP is not the last line map of its set, then the new location (loc + offset) should be less than the first location encoded by the next line map of the set. Otherwise, we try to encode the location in the next map. */ while (map != LINEMAPS_LAST_ORDINARY_MAP (set) && loc + offset >= MAP_START_LOCATION (&map[1])) { map = &map[1]; /* If the next map starts in a higher line, we cannot encode the location there. */ if (line < ORDINARY_MAP_STARTING_LINE_NUMBER (map)) return loc; } offset += column; if (linemap_assert_fails (offset < (1u << map->m_column_and_range_bits))) return loc; source_location r = linemap_position_for_line_and_column (set, map, line, offset); if (linemap_assert_fails (r <= set->highest_location) || linemap_assert_fails (map == linemap_lookup (set, r))) return loc; return r; } /* Given a virtual source location yielded by a map (either an ordinary or a macro map), returns that map. */ const struct line_map* linemap_lookup (struct line_maps *set, source_location line) { if (IS_ADHOC_LOC (line)) line = set->location_adhoc_data_map.data[line & MAX_SOURCE_LOCATION].locus; if (linemap_location_from_macro_expansion_p (set, line)) return linemap_macro_map_lookup (set, line); return linemap_ordinary_map_lookup (set, line); } /* Given a source location yielded by an ordinary map, returns that map. Since the set is built chronologically, the logical lines are monotonic increasing, and so the list is sorted and we can use a binary search. */ static const line_map_ordinary * linemap_ordinary_map_lookup (struct line_maps *set, source_location line) { unsigned int md, mn, mx; const line_map_ordinary *cached, *result; if (IS_ADHOC_LOC (line)) line = set->location_adhoc_data_map.data[line & MAX_SOURCE_LOCATION].locus; if (set == NULL || line < RESERVED_LOCATION_COUNT) return NULL; mn = LINEMAPS_ORDINARY_CACHE (set); mx = LINEMAPS_ORDINARY_USED (set); cached = LINEMAPS_ORDINARY_MAP_AT (set, mn); /* We should get a segfault if no line_maps have been added yet. */ if (line >= MAP_START_LOCATION (cached)) { if (mn + 1 == mx || line < MAP_START_LOCATION (&cached[1])) return cached; } else { mx = mn; mn = 0; } while (mx - mn > 1) { md = (mn + mx) / 2; if (MAP_START_LOCATION (LINEMAPS_ORDINARY_MAP_AT (set, md)) > line) mx = md; else mn = md; } LINEMAPS_ORDINARY_CACHE (set) = mn; result = LINEMAPS_ORDINARY_MAP_AT (set, mn); linemap_assert (line >= MAP_START_LOCATION (result)); return result; } /* Given a source location yielded by a macro map, returns that map. Since the set is built chronologically, the logical lines are monotonic decreasing, and so the list is sorted and we can use a binary search. */ static const line_map_macro * linemap_macro_map_lookup (struct line_maps *set, source_location line) { unsigned int md, mn, mx; const struct line_map_macro *cached, *result; if (IS_ADHOC_LOC (line)) line = set->location_adhoc_data_map.data[line & MAX_SOURCE_LOCATION].locus; linemap_assert (line >= LINEMAPS_MACRO_LOWEST_LOCATION (set)); if (set == NULL) return NULL; mn = LINEMAPS_MACRO_CACHE (set); mx = LINEMAPS_MACRO_USED (set); cached = LINEMAPS_MACRO_MAP_AT (set, mn); if (line >= MAP_START_LOCATION (cached)) { if (mn == 0 || line < MAP_START_LOCATION (&cached[-1])) return cached; mx = mn - 1; mn = 0; } while (mn < mx) { md = (mx + mn) / 2; if (MAP_START_LOCATION (LINEMAPS_MACRO_MAP_AT (set, md)) > line) mn = md + 1; else mx = md; } LINEMAPS_MACRO_CACHE (set) = mx; result = LINEMAPS_MACRO_MAP_AT (set, LINEMAPS_MACRO_CACHE (set)); linemap_assert (MAP_START_LOCATION (result) <= line); return result; } /* Return TRUE if MAP encodes locations coming from a macro replacement-list at macro expansion point. */ bool linemap_macro_expansion_map_p (const struct line_map *map) { if (!map) return false; return (map->reason == LC_ENTER_MACRO); } /* If LOCATION is the locus of a token in a replacement-list of a macro expansion return the location of the macro expansion point. Read the comments of struct line_map and struct line_map_macro in line-map.h to understand what a macro expansion point is. */ static source_location linemap_macro_map_loc_to_exp_point (const line_map_macro *map, source_location location ATTRIBUTE_UNUSED) { linemap_assert (linemap_macro_expansion_map_p (map) && location >= MAP_START_LOCATION (map)); /* Make sure LOCATION is correct. */ linemap_assert ((location - MAP_START_LOCATION (map)) < MACRO_MAP_NUM_MACRO_TOKENS (map)); return MACRO_MAP_EXPANSION_POINT_LOCATION (map); } /* LOCATION is the source location of a token that belongs to a macro replacement-list as part of the macro expansion denoted by MAP. Return the location of the token at the definition point of the macro. */ static source_location linemap_macro_map_loc_to_def_point (const line_map_macro *map, source_location location) { unsigned token_no; linemap_assert (linemap_macro_expansion_map_p (map) && location >= MAP_START_LOCATION (map)); linemap_assert (location >= RESERVED_LOCATION_COUNT); token_no = location - MAP_START_LOCATION (map); linemap_assert (token_no < MACRO_MAP_NUM_MACRO_TOKENS (map)); location = MACRO_MAP_LOCATIONS (map)[2 * token_no + 1]; return location; } /* If LOCATION is the locus of a token that is an argument of a function-like macro M and appears in the expansion of M, return the locus of that argument in the context of the caller of M. In other words, this returns the xI location presented in the comments of line_map_macro above. */ source_location linemap_macro_map_loc_unwind_toward_spelling (line_maps *set, const line_map_macro* map, source_location location) { unsigned token_no; if (IS_ADHOC_LOC (location)) location = get_location_from_adhoc_loc (set, location); linemap_assert (linemap_macro_expansion_map_p (map) && location >= MAP_START_LOCATION (map)); linemap_assert (location >= RESERVED_LOCATION_COUNT); linemap_assert (!IS_ADHOC_LOC (location)); token_no = location - MAP_START_LOCATION (map); linemap_assert (token_no < MACRO_MAP_NUM_MACRO_TOKENS (map)); location = MACRO_MAP_LOCATIONS (map)[2 * token_no]; return location; } /* Return the source line number corresponding to source location LOCATION. SET is the line map set LOCATION comes from. If LOCATION is the source location of token that is part of the replacement-list of a macro expansion return the line number of the macro expansion point. */ int linemap_get_expansion_line (struct line_maps *set, source_location location) { const line_map_ordinary *map = NULL; if (IS_ADHOC_LOC (location)) location = set->location_adhoc_data_map.data[location & MAX_SOURCE_LOCATION].locus; if (location < RESERVED_LOCATION_COUNT) return 0; location = linemap_macro_loc_to_exp_point (set, location, &map); return SOURCE_LINE (map, location); } /* Return the path of the file corresponding to source code location LOCATION. If LOCATION is the source location of token that is part of the replacement-list of a macro expansion return the file path of the macro expansion point. SET is the line map set LOCATION comes from. */ const char* linemap_get_expansion_filename (struct line_maps *set, source_location location) { const struct line_map_ordinary *map = NULL; if (IS_ADHOC_LOC (location)) location = set->location_adhoc_data_map.data[location & MAX_SOURCE_LOCATION].locus; if (location < RESERVED_LOCATION_COUNT) return NULL; location = linemap_macro_loc_to_exp_point (set, location, &map); return LINEMAP_FILE (map); } /* Return the name of the macro associated to MACRO_MAP. */ const char* linemap_map_get_macro_name (const line_map_macro *macro_map) { linemap_assert (macro_map && linemap_macro_expansion_map_p (macro_map)); return (const char*) NODE_NAME (MACRO_MAP_MACRO (macro_map)); } /* Return a positive value if LOCATION is the locus of a token that is located in a system header, O otherwise. It returns 1 if LOCATION is the locus of a token that is located in a system header, and 2 if LOCATION is the locus of a token located in a C system header that therefore needs to be extern "C" protected in C++. Note that this function returns 1 if LOCATION belongs to a token that is part of a macro replacement-list defined in a system header, but expanded in a non-system file. */ int linemap_location_in_system_header_p (struct line_maps *set, source_location location) { const struct line_map *map = NULL; if (IS_ADHOC_LOC (location)) location = set->location_adhoc_data_map.data[location & MAX_SOURCE_LOCATION].locus; if (location < RESERVED_LOCATION_COUNT) return false; /* Let's look at where the token for LOCATION comes from. */ while (true) { map = linemap_lookup (set, location); if (map != NULL) { if (!linemap_macro_expansion_map_p (map)) /* It's a normal token. */ return LINEMAP_SYSP (linemap_check_ordinary (map)); else { const line_map_macro *macro_map = linemap_check_macro (map); /* It's a token resulting from a macro expansion. */ source_location loc = linemap_macro_map_loc_unwind_toward_spelling (set, macro_map, location); if (loc < RESERVED_LOCATION_COUNT) /* This token might come from a built-in macro. Let's look at where that macro got expanded. */ location = linemap_macro_map_loc_to_exp_point (macro_map, location); else location = loc; } } else break; } return false; } /* Return TRUE if LOCATION is a source code location of a token coming from a macro replacement-list at a macro expansion point, FALSE otherwise. */ bool linemap_location_from_macro_expansion_p (const struct line_maps *set, source_location location) { if (IS_ADHOC_LOC (location)) location = set->location_adhoc_data_map.data[location & MAX_SOURCE_LOCATION].locus; linemap_assert (location <= MAX_SOURCE_LOCATION && (set->highest_location < LINEMAPS_MACRO_LOWEST_LOCATION (set))); if (set == NULL) return false; return (location > set->highest_location); } /* Given two virtual locations *LOC0 and *LOC1, return the first common macro map in their macro expansion histories. Return NULL if no common macro was found. *LOC0 (resp. *LOC1) is set to the virtual location of the token inside the resulting macro. */ static const struct line_map* first_map_in_common_1 (struct line_maps *set, source_location *loc0, source_location *loc1) { source_location l0 = *loc0, l1 = *loc1; const struct line_map *map0 = linemap_lookup (set, l0), *map1 = linemap_lookup (set, l1); while (linemap_macro_expansion_map_p (map0) && linemap_macro_expansion_map_p (map1) && (map0 != map1)) { if (MAP_START_LOCATION (map0) < MAP_START_LOCATION (map1)) { l0 = linemap_macro_map_loc_to_exp_point (linemap_check_macro (map0), l0); map0 = linemap_lookup (set, l0); } else { l1 = linemap_macro_map_loc_to_exp_point (linemap_check_macro (map1), l1); map1 = linemap_lookup (set, l1); } } if (map0 == map1) { *loc0 = l0; *loc1 = l1; return map0; } return NULL; } /* Given two virtual locations LOC0 and LOC1, return the first common macro map in their macro expansion histories. Return NULL if no common macro was found. *RES_LOC0 (resp. *RES_LOC1) is set to the virtual location of the token inside the resulting macro, upon return of a non-NULL result. */ static const struct line_map* first_map_in_common (struct line_maps *set, source_location loc0, source_location loc1, source_location *res_loc0, source_location *res_loc1) { *res_loc0 = loc0; *res_loc1 = loc1; return first_map_in_common_1 (set, res_loc0, res_loc1); } /* Return a positive value if PRE denotes the location of a token that comes before the token of POST, 0 if PRE denotes the location of the same token as the token for POST, and a negative value otherwise. */ int linemap_compare_locations (struct line_maps *set, source_location pre, source_location post) { bool pre_virtual_p, post_virtual_p; source_location l0 = pre, l1 = post; if (IS_ADHOC_LOC (l0)) l0 = get_location_from_adhoc_loc (set, l0); if (IS_ADHOC_LOC (l1)) l1 = get_location_from_adhoc_loc (set, l1); if (l0 == l1) return 0; if ((pre_virtual_p = linemap_location_from_macro_expansion_p (set, l0))) l0 = linemap_resolve_location (set, l0, LRK_MACRO_EXPANSION_POINT, NULL); if ((post_virtual_p = linemap_location_from_macro_expansion_p (set, l1))) l1 = linemap_resolve_location (set, l1, LRK_MACRO_EXPANSION_POINT, NULL); if (l0 == l1 && pre_virtual_p && post_virtual_p) { /* So pre and post represent two tokens that are present in a same macro expansion. Let's see if the token for pre was before the token for post in that expansion. */ unsigned i0, i1; const struct line_map *map = first_map_in_common (set, pre, post, &l0, &l1); if (map == NULL) /* This should not be possible. */ abort (); i0 = l0 - MAP_START_LOCATION (map); i1 = l1 - MAP_START_LOCATION (map); return i1 - i0; } if (IS_ADHOC_LOC (l0)) l0 = get_location_from_adhoc_loc (set, l0); if (IS_ADHOC_LOC (l1)) l1 = get_location_from_adhoc_loc (set, l1); return l1 - l0; } /* Print an include trace, for e.g. the -H option of the preprocessor. */ static void trace_include (const struct line_maps *set, const line_map_ordinary *map) { unsigned int i = set->depth; while (--i) putc ('.', stderr); fprintf (stderr, " %s\n", ORDINARY_MAP_FILE_NAME (map)); } /* Return the spelling location of the token wherever it comes from, whether part of a macro definition or not. This is a subroutine for linemap_resolve_location. */ static source_location linemap_macro_loc_to_spelling_point (struct line_maps *set, source_location location, const line_map_ordinary **original_map) { struct line_map *map; linemap_assert (set && location >= RESERVED_LOCATION_COUNT); while (true) { map = const_cast <line_map *> (linemap_lookup (set, location)); if (!linemap_macro_expansion_map_p (map)) break; location = linemap_macro_map_loc_unwind_toward_spelling (set, linemap_check_macro (map), location); } if (original_map) *original_map = linemap_check_ordinary (map); return location; } /* If LOCATION is the source location of a token that belongs to a macro replacement-list -- as part of a macro expansion -- then return the location of the token at the definition point of the macro. Otherwise, return LOCATION. SET is the set of maps location come from. ORIGINAL_MAP is an output parm. If non NULL, the function sets *ORIGINAL_MAP to the ordinary (non-macro) map the returned location comes from. This is a subroutine of linemap_resolve_location. */ static source_location linemap_macro_loc_to_def_point (struct line_maps *set, source_location location, const line_map_ordinary **original_map) { struct line_map *map; if (IS_ADHOC_LOC (location)) location = set->location_adhoc_data_map.data[location & MAX_SOURCE_LOCATION].locus; linemap_assert (set && location >= RESERVED_LOCATION_COUNT); while (true) { map = const_cast <line_map *> (linemap_lookup (set, location)); if (!linemap_macro_expansion_map_p (map)) break; location = linemap_macro_map_loc_to_def_point (linemap_check_macro (map), location); } if (original_map) *original_map = linemap_check_ordinary (map); return location; } /* If LOCATION is the source location of a token that belongs to a macro replacement-list -- at a macro expansion point -- then return the location of the topmost expansion point of the macro. We say topmost because if we are in the context of a nested macro expansion, the function returns the source location of the first macro expansion that triggered the nested expansions. Otherwise, return LOCATION. SET is the set of maps location come from. ORIGINAL_MAP is an output parm. If non NULL, the function sets *ORIGINAL_MAP to the ordinary (non-macro) map the returned location comes from. This is a subroutine of linemap_resolve_location. */ static source_location linemap_macro_loc_to_exp_point (struct line_maps *set, source_location location, const line_map_ordinary **original_map) { struct line_map *map; if (IS_ADHOC_LOC (location)) location = set->location_adhoc_data_map.data[location & MAX_SOURCE_LOCATION].locus; linemap_assert (set && location >= RESERVED_LOCATION_COUNT); while (true) { map = const_cast <line_map *> (linemap_lookup (set, location)); if (!linemap_macro_expansion_map_p (map)) break; location = linemap_macro_map_loc_to_exp_point (linemap_check_macro (map), location); } if (original_map) *original_map = linemap_check_ordinary (map); return location; } /* Resolve a virtual location into either a spelling location, an expansion point location or a token argument replacement point location. Return the map that encodes the virtual location as well as the resolved location. If LOC is *NOT* the location of a token resulting from the expansion of a macro, then the parameter LRK (which stands for Location Resolution Kind) is ignored and the resulting location just equals the one given in argument. Now if LOC *IS* the location of a token resulting from the expansion of a macro, this is what happens. * If LRK is set to LRK_MACRO_EXPANSION_POINT ------------------------------- The virtual location is resolved to the first macro expansion point that led to this macro expansion. * If LRK is set to LRK_SPELLING_LOCATION ------------------------------------- The virtual location is resolved to the locus where the token has been spelled in the source. This can follow through all the macro expansions that led to the token. * If LRK is set to LRK_MACRO_DEFINITION_LOCATION -------------------------------------- The virtual location is resolved to the locus of the token in the context of the macro definition. If LOC is the locus of a token that is an argument of a function-like macro [replacing a parameter in the replacement list of the macro] the virtual location is resolved to the locus of the parameter that is replaced, in the context of the definition of the macro. If LOC is the locus of a token that is not an argument of a function-like macro, then the function behaves as if LRK was set to LRK_SPELLING_LOCATION. If MAP is not NULL, *MAP is set to the map encoding the returned location. Note that if the returned location wasn't originally encoded by a map, then *MAP is set to NULL. This can happen if LOC resolves to a location reserved for the client code, like UNKNOWN_LOCATION or BUILTINS_LOCATION in GCC. */ source_location linemap_resolve_location (struct line_maps *set, source_location loc, enum location_resolution_kind lrk, const line_map_ordinary **map) { source_location locus = loc; if (IS_ADHOC_LOC (loc)) locus = set->location_adhoc_data_map.data[loc & MAX_SOURCE_LOCATION].locus; if (locus < RESERVED_LOCATION_COUNT) { /* A reserved location wasn't encoded in a map. Let's return a NULL map here, just like what linemap_ordinary_map_lookup does. */ if (map) *map = NULL; return loc; } switch (lrk) { case LRK_MACRO_EXPANSION_POINT: loc = linemap_macro_loc_to_exp_point (set, loc, map); break; case LRK_SPELLING_LOCATION: loc = linemap_macro_loc_to_spelling_point (set, loc, map); break; case LRK_MACRO_DEFINITION_LOCATION: loc = linemap_macro_loc_to_def_point (set, loc, map); break; default: abort (); } return loc; } /* Suppose that LOC is the virtual location of a token T coming from the expansion of a macro M. This function then steps up to get the location L of the point where M got expanded. If L is a spelling location inside a macro expansion M', then this function returns the locus of the point where M' was expanded. Said otherwise, this function returns the location of T in the context that triggered the expansion of M. *LOC_MAP must be set to the map of LOC. This function then sets it to the map of the returned location. */ source_location linemap_unwind_toward_expansion (struct line_maps *set, source_location loc, const struct line_map **map) { source_location resolved_location; const line_map_macro *macro_map = linemap_check_macro (*map); const struct line_map *resolved_map; if (IS_ADHOC_LOC (loc)) loc = set->location_adhoc_data_map.data[loc & MAX_SOURCE_LOCATION].locus; resolved_location = linemap_macro_map_loc_unwind_toward_spelling (set, macro_map, loc); resolved_map = linemap_lookup (set, resolved_location); if (!linemap_macro_expansion_map_p (resolved_map)) { resolved_location = linemap_macro_map_loc_to_exp_point (macro_map, loc); resolved_map = linemap_lookup (set, resolved_location); } *map = resolved_map; return resolved_location; } /* If LOC is the virtual location of a token coming from the expansion of a macro M and if its spelling location is reserved (e.g, a location for a built-in token), then this function unwinds (using linemap_unwind_toward_expansion) the location until a location that is not reserved and is not in a system header is reached. In other words, this unwinds the reserved location until a location that is in real source code is reached. Otherwise, if the spelling location for LOC is not reserved or if LOC doesn't come from the expansion of a macro, the function returns LOC as is and *MAP is not touched. *MAP is set to the map of the returned location if the later is different from LOC. */ source_location linemap_unwind_to_first_non_reserved_loc (struct line_maps *set, source_location loc, const struct line_map **map) { source_location resolved_loc; const struct line_map *map0 = NULL; const line_map_ordinary *map1 = NULL; if (IS_ADHOC_LOC (loc)) loc = set->location_adhoc_data_map.data[loc & MAX_SOURCE_LOCATION].locus; map0 = linemap_lookup (set, loc); if (!linemap_macro_expansion_map_p (map0)) return loc; resolved_loc = linemap_resolve_location (set, loc, LRK_SPELLING_LOCATION, &map1); if (resolved_loc >= RESERVED_LOCATION_COUNT && !LINEMAP_SYSP (map1)) return loc; while (linemap_macro_expansion_map_p (map0) && (resolved_loc < RESERVED_LOCATION_COUNT || LINEMAP_SYSP (map1))) { loc = linemap_unwind_toward_expansion (set, loc, &map0); resolved_loc = linemap_resolve_location (set, loc, LRK_SPELLING_LOCATION, &map1); } if (map != NULL) *map = map0; return loc; } /* Expand source code location LOC and return a user readable source code location. LOC must be a spelling (non-virtual) location. If it's a location < RESERVED_LOCATION_COUNT a zeroed expanded source location is returned. */ expanded_location linemap_expand_location (struct line_maps *set, const struct line_map *map, source_location loc) { expanded_location xloc; memset (&xloc, 0, sizeof (xloc)); if (IS_ADHOC_LOC (loc)) { xloc.data = set->location_adhoc_data_map.data[loc & MAX_SOURCE_LOCATION].data; loc = set->location_adhoc_data_map.data[loc & MAX_SOURCE_LOCATION].locus; } if (loc < RESERVED_LOCATION_COUNT) /* The location for this token wasn't generated from a line map. It was probably a location for a builtin token, chosen by some client code. Let's not try to expand the location in that case. */; else if (map == NULL) /* We shouldn't be getting a NULL map with a location that is not reserved by the client code. */ abort (); else { /* MAP must be an ordinary map and LOC must be non-virtual, encoded into this map, obviously; the accessors used on MAP below ensure it is ordinary. Let's just assert the non-virtualness of LOC here. */ if (linemap_location_from_macro_expansion_p (set, loc)) abort (); const line_map_ordinary *ord_map = linemap_check_ordinary (map); xloc.file = LINEMAP_FILE (ord_map); xloc.line = SOURCE_LINE (ord_map, loc); xloc.column = SOURCE_COLUMN (ord_map, loc); xloc.sysp = LINEMAP_SYSP (ord_map) != 0; } return xloc; } /* Dump line map at index IX in line table SET to STREAM. If STREAM is NULL, use stderr. IS_MACRO is true if the caller wants to dump a macro map, false otherwise. */ void linemap_dump (FILE *stream, struct line_maps *set, unsigned ix, bool is_macro) { const char *lc_reasons_v[LC_ENTER_MACRO + 1] = { "LC_ENTER", "LC_LEAVE", "LC_RENAME", "LC_RENAME_VERBATIM", "LC_ENTER_MACRO" }; const char *reason; const line_map *map; if (stream == NULL) stream = stderr; if (!is_macro) map = LINEMAPS_ORDINARY_MAP_AT (set, ix); else map = LINEMAPS_MACRO_MAP_AT (set, ix); reason = (map->reason <= LC_ENTER_MACRO) ? lc_reasons_v[map->reason] : "???"; fprintf (stream, "Map #%u [%p] - LOC: %u - REASON: %s - SYSP: %s\n", ix, (void *) map, map->start_location, reason, ((!is_macro && ORDINARY_MAP_IN_SYSTEM_HEADER_P (linemap_check_ordinary (map))) ? "yes" : "no")); if (!is_macro) { const line_map_ordinary *ord_map = linemap_check_ordinary (map); unsigned includer_ix; const line_map_ordinary *includer_map; includer_ix = ORDINARY_MAP_INCLUDER_FILE_INDEX (ord_map); includer_map = includer_ix < LINEMAPS_ORDINARY_USED (set) ? LINEMAPS_ORDINARY_MAP_AT (set, includer_ix) : NULL; fprintf (stream, "File: %s:%d\n", ORDINARY_MAP_FILE_NAME (ord_map), ORDINARY_MAP_STARTING_LINE_NUMBER (ord_map)); fprintf (stream, "Included from: [%d] %s\n", includer_ix, includer_map ? ORDINARY_MAP_FILE_NAME (includer_map) : "None"); } else { const line_map_macro *macro_map = linemap_check_macro (map); fprintf (stream, "Macro: %s (%u tokens)\n", linemap_map_get_macro_name (macro_map), MACRO_MAP_NUM_MACRO_TOKENS (macro_map)); } fprintf (stream, "\n"); } /* Dump debugging information about source location LOC into the file stream STREAM. SET is the line map set LOC comes from. */ void linemap_dump_location (struct line_maps *set, source_location loc, FILE *stream) { const line_map_ordinary *map; source_location location; const char *path = "", *from = ""; int l = -1, c = -1, s = -1, e = -1; if (IS_ADHOC_LOC (loc)) loc = set->location_adhoc_data_map.data[loc & MAX_SOURCE_LOCATION].locus; if (loc == 0) return; location = linemap_resolve_location (set, loc, LRK_MACRO_DEFINITION_LOCATION, &map); if (map == NULL) /* Only reserved locations can be tolerated in this case. */ linemap_assert (location < RESERVED_LOCATION_COUNT); else { path = LINEMAP_FILE (map); l = SOURCE_LINE (map, location); c = SOURCE_COLUMN (map, location); s = LINEMAP_SYSP (map) != 0; e = location != loc; if (e) from = "N/A"; else from = (INCLUDED_FROM (set, map)) ? LINEMAP_FILE (INCLUDED_FROM (set, map)) : "<NULL>"; } /* P: path, L: line, C: column, S: in-system-header, M: map address, E: macro expansion?, LOC: original location, R: resolved location */ fprintf (stream, "{P:%s;F:%s;L:%d;C:%d;S:%d;M:%p;E:%d,LOC:%d,R:%d}", path, from, l, c, s, (void*)map, e, loc, location); } /* Return the highest location emitted for a given file for which there is a line map in SET. FILE_NAME is the file name to consider. If the function returns TRUE, *LOC is set to the highest location emitted for that file. */ bool linemap_get_file_highest_location (struct line_maps *set, const char *file_name, source_location *loc) { /* If the set is empty or no ordinary map has been created then there is no file to look for ... */ if (set == NULL || set->info_ordinary.used == 0) return false; /* Now look for the last ordinary map created for FILE_NAME. */ int i; for (i = set->info_ordinary.used - 1; i >= 0; --i) { const char *fname = set->info_ordinary.maps[i].to_file; if (fname && !filename_cmp (fname, file_name)) break; } if (i < 0) return false; /* The highest location for a given map is either the starting location of the next map minus one, or -- if the map is the latest one -- the highest location of the set. */ source_location result; if (i == (int) set->info_ordinary.used - 1) result = set->highest_location; else result = set->info_ordinary.maps[i + 1].start_location - 1; *loc = result; return true; } /* Compute and return statistics about the memory consumption of some parts of the line table SET. */ void linemap_get_statistics (struct line_maps *set, struct linemap_stats *s) { long ordinary_maps_allocated_size, ordinary_maps_used_size, macro_maps_allocated_size, macro_maps_used_size, macro_maps_locations_size = 0, duplicated_macro_maps_locations_size = 0; const line_map_macro *cur_map; ordinary_maps_allocated_size = LINEMAPS_ORDINARY_ALLOCATED (set) * sizeof (struct line_map_ordinary); ordinary_maps_used_size = LINEMAPS_ORDINARY_USED (set) * sizeof (struct line_map_ordinary); macro_maps_allocated_size = LINEMAPS_MACRO_ALLOCATED (set) * sizeof (struct line_map_macro); for (cur_map = LINEMAPS_MACRO_MAPS (set); cur_map && cur_map <= LINEMAPS_LAST_MACRO_MAP (set); ++cur_map) { unsigned i; linemap_assert (linemap_macro_expansion_map_p (cur_map)); macro_maps_locations_size += 2 * MACRO_MAP_NUM_MACRO_TOKENS (cur_map) * sizeof (source_location); for (i = 0; i < 2 * MACRO_MAP_NUM_MACRO_TOKENS (cur_map); i += 2) { if (MACRO_MAP_LOCATIONS (cur_map)[i] == MACRO_MAP_LOCATIONS (cur_map)[i + 1]) duplicated_macro_maps_locations_size += sizeof (source_location); } } macro_maps_used_size = LINEMAPS_MACRO_USED (set) * sizeof (struct line_map_macro); s->num_ordinary_maps_allocated = LINEMAPS_ORDINARY_ALLOCATED (set); s->num_ordinary_maps_used = LINEMAPS_ORDINARY_USED (set); s->ordinary_maps_allocated_size = ordinary_maps_allocated_size; s->ordinary_maps_used_size = ordinary_maps_used_size; s->num_expanded_macros = num_expanded_macros_counter; s->num_macro_tokens = num_macro_tokens_counter; s->num_macro_maps_used = LINEMAPS_MACRO_USED (set); s->macro_maps_allocated_size = macro_maps_allocated_size; s->macro_maps_locations_size = macro_maps_locations_size; s->macro_maps_used_size = macro_maps_used_size; s->duplicated_macro_maps_locations_size = duplicated_macro_maps_locations_size; s->adhoc_table_size = (set->location_adhoc_data_map.allocated * sizeof (struct location_adhoc_data)); s->adhoc_table_entries_used = set->location_adhoc_data_map.curr_loc; } /* Dump line table SET to STREAM. If STREAM is NULL, stderr is used. NUM_ORDINARY specifies how many ordinary maps to dump. NUM_MACRO specifies how many macro maps to dump. */ void line_table_dump (FILE *stream, struct line_maps *set, unsigned int num_ordinary, unsigned int num_macro) { unsigned int i; if (set == NULL) return; if (stream == NULL) stream = stderr; fprintf (stream, "# of ordinary maps: %d\n", LINEMAPS_ORDINARY_USED (set)); fprintf (stream, "# of macro maps: %d\n", LINEMAPS_MACRO_USED (set)); fprintf (stream, "Include stack depth: %d\n", set->depth); fprintf (stream, "Highest location: %u\n", set->highest_location); if (num_ordinary) { fprintf (stream, "\nOrdinary line maps\n"); for (i = 0; i < num_ordinary && i < LINEMAPS_ORDINARY_USED (set); i++) linemap_dump (stream, set, i, false); fprintf (stream, "\n"); } if (num_macro) { fprintf (stream, "\nMacro line maps\n"); for (i = 0; i < num_macro && i < LINEMAPS_MACRO_USED (set); i++) linemap_dump (stream, set, i, true); fprintf (stream, "\n"); } } /* struct source_range. */ /* Is there any part of this range on the given line? */ bool source_range::intersects_line_p (const char *file, int line) const { expanded_location exploc_start = linemap_client_expand_location_to_spelling_point (m_start); if (file != exploc_start.file) return false; if (line < exploc_start.line) return false; expanded_location exploc_finish = linemap_client_expand_location_to_spelling_point (m_finish); if (file != exploc_finish.file) return false; if (line > exploc_finish.line) return false; return true; } /* class rich_location. */ /* Construct a rich_location with location LOC as its initial range. */ rich_location::rich_location (line_maps *set, source_location loc) : m_loc (loc), m_num_ranges (0), m_have_expanded_location (false), m_num_fixit_hints (0) { /* Set up the 0th range, extracting any range from LOC. */ source_range src_range = get_range_from_loc (set, loc); add_range (src_range, true); m_ranges[0].m_caret = lazily_expand_location (); } /* Construct a rich_location with source_range SRC_RANGE as its initial range. */ rich_location::rich_location (source_range src_range) : m_loc (src_range.m_start), m_num_ranges (0), m_have_expanded_location (false), m_num_fixit_hints (0) { /* Set up the 0th range: */ add_range (src_range, true); } /* The destructor for class rich_location. */ rich_location::~rich_location () { for (unsigned int i = 0; i < m_num_fixit_hints; i++) delete m_fixit_hints[i]; } /* Get an expanded_location for this rich_location's primary location. */ expanded_location rich_location::lazily_expand_location () { if (!m_have_expanded_location) { m_expanded_location = linemap_client_expand_location_to_spelling_point (m_loc); m_have_expanded_location = true; } return m_expanded_location; } /* Set the column of the primary location. This can only be called for rich_location instances for which the primary location has caret==start==finish. */ void rich_location::override_column (int column) { lazily_expand_location (); gcc_assert (m_ranges[0].m_show_caret_p); gcc_assert (m_ranges[0].m_caret.column == m_expanded_location.column); gcc_assert (m_ranges[0].m_start.column == m_expanded_location.column); gcc_assert (m_ranges[0].m_finish.column == m_expanded_location.column); m_expanded_location.column = column; m_ranges[0].m_caret.column = column; m_ranges[0].m_start.column = column; m_ranges[0].m_finish.column = column; } /* Add the given range. */ void rich_location::add_range (source_location start, source_location finish, bool show_caret_p) { linemap_assert (m_num_ranges < MAX_RANGES); location_range *range = &m_ranges[m_num_ranges++]; range->m_start = linemap_client_expand_location_to_spelling_point (start); range->m_finish = linemap_client_expand_location_to_spelling_point (finish); range->m_caret = range->m_start; range->m_show_caret_p = show_caret_p; } /* Add the given range. */ void rich_location::add_range (source_range src_range, bool show_caret_p) { linemap_assert (m_num_ranges < MAX_RANGES); add_range (src_range.m_start, src_range.m_finish, show_caret_p); } void rich_location::add_range (location_range *src_range) { linemap_assert (m_num_ranges < MAX_RANGES); m_ranges[m_num_ranges++] = *src_range; } /* Add or overwrite the location given by IDX, setting its location to LOC, and setting its "should my caret be printed" flag to SHOW_CARET_P. It must either overwrite an existing location, or add one *exactly* on the end of the array. This is primarily for use by gcc when implementing diagnostic format decoders e.g. - the "+" in the C/C++ frontends, for handling format codes like "%q+D" (which writes the source location of a tree back into location 0 of the rich_location), and - the "%C" and "%L" format codes in the Fortran frontend. */ void rich_location::set_range (line_maps *set, unsigned int idx, source_location loc, bool show_caret_p) { linemap_assert (idx < MAX_RANGES); /* We can either overwrite an existing range, or add one exactly on the end of the array. */ linemap_assert (idx <= m_num_ranges); source_range src_range = get_range_from_loc (set, loc); location_range *locrange = &m_ranges[idx]; locrange->m_start = linemap_client_expand_location_to_spelling_point (src_range.m_start); locrange->m_finish = linemap_client_expand_location_to_spelling_point (src_range.m_finish); locrange->m_show_caret_p = show_caret_p; locrange->m_caret = linemap_client_expand_location_to_spelling_point (loc); /* Are we adding a range onto the end? */ if (idx == m_num_ranges) m_num_ranges = idx + 1; if (idx == 0) { m_loc = loc; /* Mark any cached value here as dirty. */ m_have_expanded_location = false; } } /* Add a fixit-hint, suggesting insertion of NEW_CONTENT at WHERE. */ void rich_location::add_fixit_insert (source_location where, const char *new_content) { linemap_assert (m_num_fixit_hints < MAX_FIXIT_HINTS); m_fixit_hints[m_num_fixit_hints++] = new fixit_insert (where, new_content); } /* Add a fixit-hint, suggesting removal of the content at SRC_RANGE. */ void rich_location::add_fixit_remove (source_range src_range) { linemap_assert (m_num_fixit_hints < MAX_FIXIT_HINTS); m_fixit_hints[m_num_fixit_hints++] = new fixit_remove (src_range); } /* Add a fixit-hint, suggesting replacement of the content at SRC_RANGE with NEW_CONTENT. */ void rich_location::add_fixit_replace (source_range src_range, const char *new_content) { linemap_assert (m_num_fixit_hints < MAX_FIXIT_HINTS); m_fixit_hints[m_num_fixit_hints++] = new fixit_replace (src_range, new_content); } /* class fixit_insert. */ fixit_insert::fixit_insert (source_location where, const char *new_content) : m_where (where), m_bytes (xstrdup (new_content)), m_len (strlen (new_content)) { } fixit_insert::~fixit_insert () { free (m_bytes); } /* Implementation of fixit_hint::affects_line_p for fixit_insert. */ bool fixit_insert::affects_line_p (const char *file, int line) { expanded_location exploc = linemap_client_expand_location_to_spelling_point (m_where); if (file == exploc.file) if (line == exploc.line) return true; return false; } /* class fixit_remove. */ fixit_remove::fixit_remove (source_range src_range) : m_src_range (src_range) { } /* Implementation of fixit_hint::affects_line_p for fixit_remove. */ bool fixit_remove::affects_line_p (const char *file, int line) { return m_src_range.intersects_line_p (file, line); } /* class fixit_replace. */ fixit_replace::fixit_replace (source_range src_range, const char *new_content) : m_src_range (src_range), m_bytes (xstrdup (new_content)), m_len (strlen (new_content)) { } fixit_replace::~fixit_replace () { free (m_bytes); } /* Implementation of fixit_hint::affects_line_p for fixit_replace. */ bool fixit_replace::affects_line_p (const char *file, int line) { return m_src_range.intersects_line_p (file, line); }
h4ck3rm1k3/gcc-1
libcpp/line-map.c
C
gpl-2.0
71,107
#include "Card.h" #include "Game.h" #include <iostream> #include <array> #include <string> #include <vector> #include <algorithm> #include <random> #include <cstdlib> #include <ctime> using namespace std; using namespace zks::game::card; int test_deck() { CardDeck deck(1); CardDeck d1, d2; deck.shuffle(); cout << "deck: " << deck.str() << endl; cout << "d1: " << d1.str() << endl; cout << "d2: " << d2.str() << endl; cout << "\nget from back:\n"; for (auto i = 0; i<10; ++i) { d1.put_card(deck.get_card()); cout << d1.str() << endl; } cout << "\nget from front:\n"; for (auto i = 0; i<10; ++i) { d2.put_card(deck.get_card(false)); cout << d2.str() << endl; } cout << "\n"; cout << "deck: " << deck.str() << endl; return 0; } int main() { Game g; cout << "game: \n" << g.str() << endl; g.prepare(); cout << "game: \n" << g.str() << endl; g.play(); cout << "game: \n" << g.str() << endl; g.post(); cout << "game: \n" << g.str() << endl; return 0; } int test_suite() { for (const auto& s : Suite()) { cout << to_string(s) << ", "; } cout << endl; return 0; } int test_number() { for (const auto& n : Number()) { cout << to_string(n) << ", "; } cout << endl; return 0; } int test_card() { vector<Card> deck; for (auto s = begin(Suite()); s<Suite::JOKER; ++s) { for (const auto& n : Number()) { deck.emplace_back(s, n); } } cout << "\n"; for (auto const& c : deck) { cout << to_string(c) << ", "; } cout << "\n"; std::srand(std::time(0)); std::array<int, std::mt19937::state_size> seed_data; std::generate(seed_data.begin(), seed_data.end(), std::rand); std::seed_seq seq(seed_data.begin(), seed_data.end()); std::mt19937 g(seq); std::shuffle(deck.begin(), deck.end(), g); cout << "\n"; for (auto const& c : deck) { cout << to_string(c) << ", "; } cout << "\n"; return 0; }
jimzshi/game
src/card/main.cpp
C++
gpl-2.0
1,866
/* This file defines the control system */ /* Dependencies - Serial */ #ifndef MICAV_CONTROLLER #define MICAV_CONTROLLER #include "config.h" #include "drivers.h" #include "PID.h" #include <stdint.h> #define MAX_DYAW 100 #define MIN_DYAW -100 #define MAX_DPITCH 100 #define MIN_DPITCH -100 #define MAX_DROLL 100 #define MIN_DROLL -100 #define MAX_DYAW 100 #define MIN_DYAW -100 #define MAX_DPITCH 100 #define MIN_DPITCH -100 #define MAX_ROLL 150 #define MIN_ROLL -150 /*Degrees*10*/ void update_input(); void update_state(float []); //void update_control(); //void update_output(); void write_output(); #endif /* MICAV_CONTROLLER */
micavdtu/MICAV
mav_pilot/controller.h
C
gpl-2.0
643
CREATE TABLE IF NOT EXISTS `#__rsfirewall_exceptions` ( `id` int(11) NOT NULL AUTO_INCREMENT, `type` varchar(4) NOT NULL, `regex` tinyint(1) NOT NULL, `match` text NOT NULL, `php` tinyint(1) NOT NULL, `sql` tinyint(1) NOT NULL, `js` tinyint(1) NOT NULL, `uploads` tinyint(1) NOT NULL, `reason` text NOT NULL, `date` datetime NOT NULL, `published` tinyint(1) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
trungjc/caravancountry
administrator/components/com_rsfirewall/sql/mysql/exceptions.sql
SQL
gpl-2.0
448
<?php /* * This file is part of Respect/Validation. * * (c) Alexandre Gomes Gaigalas <[email protected]> * * For the full copyright and license information, please view the "LICENSE.md" * file that was distributed with this source code. */ namespace Respect\Validation\Rules\SubdivisionCode; use Respect\Validation\Rules\AbstractSearcher; /** * Validator for Turks and Caicos Islands subdivision code. * * ISO 3166-1 alpha-2: TC * * @link https://salsa.debian.org/iso-codes-team/iso-codes */ class TcSubdivisionCode extends AbstractSearcher { public $haystack = [ 'AC', // Ambergris Cays 'DC', // Dellis Cay 'EC', // East Caicos 'FC', // French Cay 'GT', // Grand Turk 'LW', // Little Water Cay 'MC', // Middle Caicos 'NC', // North Caicos 'PN', // Pine Cay 'PR', // Providenciales 'RC', // Parrot Cay 'SC', // South Caicos 'SL', // Salt Cay 'WC', // West Caicos ]; public $compareIdentical = true; }
PaymentHighway/woocommerce-gateway-paymenthighway
includes/vendor/respect/validation/library/Rules/SubdivisionCode/TcSubdivisionCode.php
PHP
gpl-2.0
1,048
<?php /* @particles/assets.html.twig */ class __TwigTemplate_299c183811cc71a2e64a3daab6e1f6fca93d29687649f11bd1c1431814d9f4f7 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); // line 1 $this->parent = $this->loadTemplate("@nucleus/partials/particle.html.twig", "@particles/assets.html.twig", 1); $this->blocks = array( 'stylesheets' => array($this, 'block_stylesheets'), 'javascript' => array($this, 'block_javascript'), 'javascript_footer' => array($this, 'block_javascript_footer'), ); } protected function doGetParent(array $context) { return "@nucleus/partials/particle.html.twig"; } protected function doDisplay(array $context, array $blocks = array()) { $this->parent->display($context, array_merge($this->blocks, $blocks)); } // line 3 public function block_stylesheets($context, array $blocks = array()) { // line 4 echo " "; if ($this->getAttribute((isset($context["particle"]) ? $context["particle"] : null), "enabled", array())) { // line 5 echo " "; $context['_parent'] = $context; $context['_seq'] = twig_ensure_traversable($this->getAttribute((isset($context["particle"]) ? $context["particle"] : null), "css", array())); foreach ($context['_seq'] as $context["_key"] => $context["css"]) { // line 6 echo " "; $context["attr_extra"] = ""; // line 7 echo " "; if ($this->getAttribute($context["css"], "extra", array())) { // line 8 echo " "; $context['_parent'] = $context; $context['_seq'] = twig_ensure_traversable($this->getAttribute($context["css"], "extra", array())); foreach ($context['_seq'] as $context["_key"] => $context["attributes"]) { // line 9 echo " "; $context['_parent'] = $context; $context['_seq'] = twig_ensure_traversable($context["attributes"]); foreach ($context['_seq'] as $context["key"] => $context["value"]) { // line 10 echo " "; $context["attr_extra"] = ((((((isset($context["attr_extra"]) ? $context["attr_extra"] : null) . " ") . twig_escape_filter($this->env, $context["key"])) . "=\"") . twig_escape_filter($this->env, $context["value"], "html_attr")) . "\""); // line 11 echo " "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['key'], $context['value'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 12 echo " "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['_key'], $context['attributes'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 13 echo " "; } // line 14 echo " "; // line 15 if ($this->getAttribute($context["css"], "location", array())) { // line 16 echo " <link rel=\"stylesheet\" href=\""; echo twig_escape_filter($this->env, $this->env->getExtension('GantryTwig')->urlFunc($this->getAttribute($context["css"], "location", array())), "html", null, true); echo "\" type=\"text/css\""; echo (isset($context["attr_extra"]) ? $context["attr_extra"] : null); echo " /> "; } // line 18 echo " "; // line 19 if ($this->getAttribute($context["css"], "inline", array())) { // line 20 echo " <style type=\"text/css\""; echo (isset($context["attr_extra"]) ? $context["attr_extra"] : null); echo ">"; echo $this->getAttribute($context["css"], "inline", array()); echo "</style> "; } // line 22 echo " "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['_key'], $context['css'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 23 echo " "; } } // line 26 public function block_javascript($context, array $blocks = array()) { // line 27 echo " "; if ($this->getAttribute((isset($context["particle"]) ? $context["particle"] : null), "enabled", array())) { // line 28 echo " "; $context['_parent'] = $context; $context['_seq'] = twig_ensure_traversable($this->getAttribute((isset($context["particle"]) ? $context["particle"] : null), "javascript", array())); foreach ($context['_seq'] as $context["_key"] => $context["script"]) { // line 29 echo " "; if (($this->getAttribute($context["script"], "in_footer", array()) == false)) { // line 30 echo " "; $context["attr_extra"] = ""; // line 31 echo " "; if ($this->getAttribute($context["script"], "extra", array())) { // line 32 echo " "; $context['_parent'] = $context; $context['_seq'] = twig_ensure_traversable($this->getAttribute($context["script"], "extra", array())); foreach ($context['_seq'] as $context["_key"] => $context["attributes"]) { // line 33 echo " "; $context['_parent'] = $context; $context['_seq'] = twig_ensure_traversable($context["attributes"]); foreach ($context['_seq'] as $context["key"] => $context["value"]) { // line 34 echo " "; $context["attr_extra"] = ((((((isset($context["attr_extra"]) ? $context["attr_extra"] : null) . " ") . twig_escape_filter($this->env, $context["key"])) . "=\"") . twig_escape_filter($this->env, $context["value"], "html_attr")) . "\""); // line 35 echo " "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['key'], $context['value'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 36 echo " "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['_key'], $context['attributes'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 37 echo " "; } // line 38 echo " "; // line 39 if ($this->getAttribute($context["script"], "location", array())) { // line 40 echo " <script src=\""; echo twig_escape_filter($this->env, $this->env->getExtension('GantryTwig')->urlFunc($this->getAttribute($context["script"], "location", array())), "html", null, true); echo "\" type=\"text/javascript\""; echo (isset($context["attr_extra"]) ? $context["attr_extra"] : null); echo "></script> "; } // line 42 echo " "; // line 43 if ($this->getAttribute($context["script"], "inline", array())) { // line 44 echo " <script type=\"text/javascript\""; echo (isset($context["attr_extra"]) ? $context["attr_extra"] : null); echo ">"; echo $this->getAttribute($context["script"], "inline", array()); echo "</script> "; } // line 46 echo " "; } // line 47 echo " "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['_key'], $context['script'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 48 echo " "; } } // line 51 public function block_javascript_footer($context, array $blocks = array()) { // line 52 echo " "; if ($this->getAttribute((isset($context["particle"]) ? $context["particle"] : null), "enabled", array())) { // line 53 echo " "; $context['_parent'] = $context; $context['_seq'] = twig_ensure_traversable($this->getAttribute((isset($context["particle"]) ? $context["particle"] : null), "javascript", array())); foreach ($context['_seq'] as $context["_key"] => $context["script"]) { // line 54 echo " "; if (($this->getAttribute($context["script"], "in_footer", array()) == true)) { // line 55 echo " "; $context["attr_extra"] = ""; // line 56 echo " "; // line 57 if ($this->getAttribute($context["script"], "extra", array())) { // line 58 echo " "; $context['_parent'] = $context; $context['_seq'] = twig_ensure_traversable($this->getAttribute($context["script"], "extra", array())); foreach ($context['_seq'] as $context["_key"] => $context["attributes"]) { // line 59 echo " "; $context['_parent'] = $context; $context['_seq'] = twig_ensure_traversable($context["attributes"]); foreach ($context['_seq'] as $context["key"] => $context["value"]) { // line 60 echo " "; $context["attr_extra"] = ((((((isset($context["attr_extra"]) ? $context["attr_extra"] : null) . " ") . twig_escape_filter($this->env, $context["key"])) . "=\"") . twig_escape_filter($this->env, $context["value"], "html_attr")) . "\""); // line 61 echo " "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['key'], $context['value'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 62 echo " "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['_key'], $context['attributes'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 63 echo " "; } // line 64 echo " "; // line 65 if ($this->getAttribute($context["script"], "location", array())) { // line 66 echo " <script src=\""; echo twig_escape_filter($this->env, $this->env->getExtension('GantryTwig')->urlFunc($this->getAttribute($context["script"], "location", array())), "html", null, true); echo "\" type=\"text/javascript\""; echo (isset($context["attr_extra"]) ? $context["attr_extra"] : null); echo "></script> "; } // line 68 echo " "; // line 69 if ($this->getAttribute($context["script"], "inline", array())) { // line 70 echo " <script type=\"text/javascript\""; echo (isset($context["attr_extra"]) ? $context["attr_extra"] : null); echo ">"; echo $this->getAttribute($context["script"], "inline", array()); echo "</script> "; } // line 72 echo " "; } // line 73 echo " "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['_key'], $context['script'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 74 echo " "; } } public function getTemplateName() { return "@particles/assets.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 285 => 74, 279 => 73, 276 => 72, 268 => 70, 266 => 69, 263 => 68, 255 => 66, 253 => 65, 250 => 64, 247 => 63, 241 => 62, 235 => 61, 232 => 60, 227 => 59, 222 => 58, 220 => 57, 217 => 56, 214 => 55, 211 => 54, 206 => 53, 203 => 52, 200 => 51, 195 => 48, 189 => 47, 186 => 46, 178 => 44, 176 => 43, 173 => 42, 165 => 40, 163 => 39, 160 => 38, 157 => 37, 151 => 36, 145 => 35, 142 => 34, 137 => 33, 132 => 32, 129 => 31, 126 => 30, 123 => 29, 118 => 28, 115 => 27, 112 => 26, 107 => 23, 101 => 22, 93 => 20, 91 => 19, 88 => 18, 80 => 16, 78 => 15, 75 => 14, 72 => 13, 66 => 12, 60 => 11, 57 => 10, 52 => 9, 47 => 8, 44 => 7, 41 => 6, 36 => 5, 33 => 4, 30 => 3, 11 => 1,); } } /* {% extends '@nucleus/partials/particle.html.twig' %}*/ /* */ /* {% block stylesheets %}*/ /* {% if (particle.enabled) %}*/ /* {% for css in particle.css %}*/ /* {% set attr_extra = '' %}*/ /* {% if css.extra %}*/ /* {% for attributes in css.extra %}*/ /* {% for key, value in attributes %}*/ /* {% set attr_extra = attr_extra ~ ' ' ~ key|e ~ '="' ~ value|e('html_attr') ~ '"' %}*/ /* {% endfor %}*/ /* {% endfor %}*/ /* {% endif %}*/ /* */ /* {% if css.location %}*/ /* <link rel="stylesheet" href="{{ url(css.location) }}" type="text/css"{{ attr_extra|raw }} />*/ /* {% endif %}*/ /* */ /* {% if css.inline %}*/ /* <style type="text/css"{{ attr_extra|raw }}>{{ css.inline|raw }}</style>*/ /* {% endif %}*/ /* {% endfor %}*/ /* {% endif %}*/ /* {% endblock %}*/ /* */ /* {% block javascript %}*/ /* {% if particle.enabled %}*/ /* {% for script in particle.javascript %}*/ /* {% if script.in_footer == false %}*/ /* {% set attr_extra = '' %}*/ /* {% if script.extra %}*/ /* {% for attributes in script.extra %}*/ /* {% for key, value in attributes %}*/ /* {% set attr_extra = attr_extra ~ ' ' ~ key|e ~ '="' ~ value|e('html_attr') ~ '"' %}*/ /* {% endfor %}*/ /* {% endfor %}*/ /* {% endif %}*/ /* */ /* {% if script.location %}*/ /* <script src="{{ url(script.location) }}" type="text/javascript"{{ attr_extra|raw }}></script>*/ /* {% endif %}*/ /* */ /* {% if script.inline %}*/ /* <script type="text/javascript"{{ attr_extra|raw }}>{{ script.inline|raw }}</script>*/ /* {% endif %}*/ /* {% endif %}*/ /* {% endfor %}*/ /* {% endif %}*/ /* {% endblock %}*/ /* */ /* {% block javascript_footer %}*/ /* {% if particle.enabled %}*/ /* {% for script in particle.javascript %}*/ /* {% if script.in_footer == true %}*/ /* {% set attr_extra = '' %}*/ /* */ /* {% if script.extra %}*/ /* {% for attributes in script.extra %}*/ /* {% for key, value in attributes %}*/ /* {% set attr_extra = attr_extra ~ ' ' ~ key|e ~ '="' ~ value|e('html_attr') ~ '"' %}*/ /* {% endfor %}*/ /* {% endfor %}*/ /* {% endif %}*/ /* */ /* {% if script.location %}*/ /* <script src="{{ url(script.location) }}" type="text/javascript"{{ attr_extra|raw }}></script>*/ /* {% endif %}*/ /* */ /* {% if script.inline %}*/ /* <script type="text/javascript"{{ attr_extra|raw }}>{{ script.inline|raw }}</script>*/ /* {% endif %}*/ /* {% endif %}*/ /* {% endfor %}*/ /* {% endif %}*/ /* {% endblock %}*/ /* */ /* */
JozefAB/neoacu
cache/gantry5/g5_hydrogen/twig/f3/f36bf52c1bc96552cfcecedfc074a62f36b34d410df8d972a61f3bb3c60d3ea1.php
PHP
gpl-2.0
19,381
/* * libquicktime yuv4 encoder * * Copyright (c) 2011 Carl Eugen Hoyos * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "avcodec.h" #include "internal.h" static av_cold int yuv4_encode_init(AVCodecContext *avctx) { avctx->coded_frame = av_frame_alloc(); if (!avctx->coded_frame) { av_log(avctx, AV_LOG_ERROR, "Could not allocate frame.\n"); return AVERROR(ENOMEM); } return 0; } static int yuv4_encode_frame(AVCodecContext *avctx, AVPacket *pkt, const AVFrame *pic, int *got_packet) { uint8_t *dst; uint8_t *y, *u, *v; int i, j, ret; if ((ret = ff_alloc_packet2(avctx, pkt, 6 * (avctx->width + 1 >> 1) * (avctx->height + 1 >> 1))) < 0) return ret; dst = pkt->data; avctx->coded_frame->key_frame = 1; avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I; y = pic->data[0]; u = pic->data[1]; v = pic->data[2]; for (i = 0; i < avctx->height + 1 >> 1; i++) { for (j = 0; j < avctx->width + 1 >> 1; j++) { *dst++ = u[j] ^ 0x80; *dst++ = v[j] ^ 0x80; *dst++ = y[ 2 * j ]; *dst++ = y[ 2 * j + 1]; *dst++ = y[pic->linesize[0] + 2 * j ]; *dst++ = y[pic->linesize[0] + 2 * j + 1]; } y += 2 * pic->linesize[0]; u += pic->linesize[1]; v += pic->linesize[2]; } pkt->flags |= AV_PKT_FLAG_KEY; *got_packet = 1; return 0; } static av_cold int yuv4_encode_close(AVCodecContext *avctx) { av_freep(&avctx->coded_frame); return 0; } AVCodec ff_yuv4_encoder = { .name = "yuv4", .long_name = NULL_IF_CONFIG_SMALL("Uncompressed packed 4:2:0"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_YUV4, .init = yuv4_encode_init, .encode2 = yuv4_encode_frame, .close = yuv4_encode_close, .pix_fmts = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE }, };
tojo9900/vice
src/lib/libffmpeg/libavcodec/yuv4enc.c
C
gpl-2.0
2,758
/* * Copyright (C) 2005-2012 MaNGOS <http://getmangos.com/> * * 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 */ #ifndef MANGOSSERVER_PATH_H #define MANGOSSERVER_PATH_H #include "Common.h" #include <vector> struct SimplePathNode { float x,y,z; }; template<typename PathElem, typename PathNode = PathElem> class Path { public: size_t size() const { return i_nodes.size(); } bool empty() const { return i_nodes.empty(); } void resize(unsigned int sz) { i_nodes.resize(sz); } void clear() { i_nodes.clear(); } void erase(uint32 idx) { i_nodes.erase(i_nodes.begin()+idx); } float GetTotalLength(uint32 start, uint32 end) const { float len = 0.0f; for(unsigned int idx=start+1; idx < end; ++idx) { PathNode const& node = i_nodes[idx]; PathNode const& prev = i_nodes[idx-1]; float xd = node.x - prev.x; float yd = node.y - prev.y; float zd = node.z - prev.z; len += sqrtf( xd*xd + yd*yd + zd*zd ); } return len; } float GetTotalLength() const { return GetTotalLength(0,size()); } float GetPassedLength(uint32 curnode, float x, float y, float z) const { float len = GetTotalLength(0,curnode); if (curnode > 0) { PathNode const& node = i_nodes[curnode-1]; float xd = x - node.x; float yd = y - node.y; float zd = z - node.z; len += sqrtf( xd*xd + yd*yd + zd*zd ); } return len; } PathNode& operator[](size_t idx) { return i_nodes[idx]; } PathNode const& operator[](size_t idx) const { return i_nodes[idx]; } void set(size_t idx, PathElem elem) { i_nodes[idx] = elem; } protected: std::vector<PathElem> i_nodes; }; typedef Path<SimplePathNode> SimplePath; #endif
wongya/mangos
src/game/Path.h
C
gpl-2.0
2,672
/* ** Copyright (c) 2007-2012 by Silicon Laboratories ** ** $Id: si3226x_intf.h 3713 2012-12-18 17:30:28Z cdp $ ** ** Si3226x_Intf.h ** Si3226x ProSLIC interface header file ** ** Author(s): ** laj ** ** Distributed by: ** Silicon Laboratories, Inc ** ** This file contains proprietary information. ** No dissemination allowed without prior written permission from ** Silicon Laboratories, Inc. ** ** File Description: ** This is the header file for the ProSLIC driver. ** ** Dependancies: ** proslic_datatypes.h, Si3226x_registers.h, ProSLIC.h ** */ #ifndef SI3226X_INTF_H #define SI3226X_INTF_H /* ** ** Si3226x General Constants ** */ #define SI3226X_REVA 0 #define SI3226X_REVB 1 #define SI3226X_REVC 3 /* This is revC bug - shows revD revision code */ #define DEVICE_KEY_MIN 0x64 #define DEVICE_KEY_MAX 0x6D /* ** Calibration Constants */ #define SI3226X_CAL_STD_CALR1 0xC0 /* FF */ #define SI3226X_CAL_STD_CALR2 0x18 /* F8 */ /* Timeouts in 10s of ms */ #define SI3226X_TIMEOUT_DCDC_UP 200 #define SI3226X_TIMEOUT_DCDC_DOWN 200 /* ** ** PROSLIC INITIALIZATION FUNCTIONS ** */ /* ** Function: PROSLIC_Reset ** ** Description: ** Resets the ProSLIC ** ** Input Parameters: ** pProslic: pointer to PROSLIC object ** ** Return: ** none */ int Si3226x_Reset (proslicChanType_ptr hProslic); /* ** Function: PROSLIC_ShutdownChannel ** ** Description: ** Safely shutdown channel w/o interruption to ** other active channels ** ** Input Parameters: ** pProslic: pointer to PROSLIC object ** ** Return: ** none */ int Si3226x_ShutdownChannel (proslicChanType_ptr hProslic); /* ** Function: PROSLIC_Init_MultiBOM ** ** Description: ** Initializes the ProSLIC w/ selected general parameters ** ** Input Parameters: ** pProslic: pointer to PROSLIC object ** size: number of channels ** preset: general configuration preset ** ** Return: ** none */ int Si3226x_Init_MultiBOM (proslicChanType_ptr *hProslic,int size,int preset); /* ** Function: PROSLIC_Init ** ** Description: ** Initializes the ProSLIC ** ** Input Parameters: ** pProslic: pointer to PROSLIC object ** ** Return: ** none */ int Si3226x_Init (proslicChanType_ptr *hProslic,int size); /* ** Function: PROSLIC_Reinit ** ** Description: ** Soft reset and initialization ** ** Input Parameters: ** pProslic: pointer to PROSLIC object ** ** Return: ** none */ int Si3226x_Reinit (proslicChanType_ptr hProslic,int size); /* ** Function: PROSLIC_VerifyControlInterface ** ** Description: ** Verify SPI port read capabilities ** ** Input Parameters: ** pProslic: pointer to PROSLIC object ** ** Return: ** none */ int Si3226x_VerifyControlInterface (proslicChanType_ptr hProslic); uInt8 Si3226x_ReadReg (proslicChanType_ptr hProslic,uInt8 addr); int Si3226x_WriteReg (proslicChanType_ptr hProslic,uInt8 addr,uInt8 data); ramData Si3226x_ReadRAM (proslicChanType_ptr hProslic,uInt16 addr); int Si3226x_WriteRAM (proslicChanType_ptr hProslic,uInt16 addr, ramData data); /* ** Function: ProSLIC_PrintDebugData ** ** Description: ** Register and RAM dump utility ** ** Input Parameters: ** pProslic: pointer to PROSLIC object ** ** Return: ** none */ int Si3226x_PrintDebugData (proslicChanType_ptr hProslic); /* ** Function: ProSLIC_PrintDebugReg ** ** Description: ** Register dump utility ** ** Input Parameters: ** pProslic: pointer to PROSLIC object ** ** Return: ** none */ int Si3226x_PrintDebugReg (proslicChanType_ptr hProslic); /* ** Function: ProSLIC_PrintDebugRAM ** ** Description: ** RAM dump utility ** ** Input Parameters: ** pProslic: pointer to PROSLIC object ** ** Return: ** none */ int Si3226x_PrintDebugRAM (proslicChanType_ptr hProslic); /* ** Function: Si3226x_PowerUpConverter ** ** Description: ** Powers all DC/DC converters sequentially with delay to minimize ** peak power draw on VDC. ** ** Returns: ** int (error) ** */ int Si3226x_PowerUpConverter(proslicChanType_ptr hProslic); /* ** Function: Si3226x_PowerDownConverter ** ** Description: ** Power down DCDC converter (selected channel only) ** ** Returns: ** int (error) ** */ int Si3226x_PowerDownConverter(proslicChanType_ptr hProslic); /* ** Function: Si3226x_Calibrate ** ** Description: ** Generic calibration function for Si3226x ** ** Input Parameters: ** pProslic: pointer to PROSLIC object, ** size: maximum number of channels ** calr: array of CALRx register values ** maxTime: cal timeout (in ms) ** ** Return: ** int */ int Si3226x_Calibrate (proslicChanType_ptr *hProslic, int size, uInt8 *calr, int maxTime); /* ** Function: PROSLIC_Cal ** ** Description: ** Calibrates the ProSLIC ** ** Input Parameters: ** pProslic: pointer to PROSLIC object ** ** Return: ** none */ int Si3226x_Cal (proslicChanType_ptr *hProslic, int size); /* ** Function: PROSLIC_LoadRegTables ** ** Description: ** Loads registers and ram in the ProSLIC ** ** Input Parameters: ** pProslic: pointer to PROSLIC object ** pRamTable: pointer to ram values to load ** pRegTable: pointer to register values to load ** ** ** Return: ** none */ int Si3226x_LoadRegTables (proslicChanType_ptr *hProslic, ProslicRAMInit *pRamTable, ProslicRegInit *pRegTable,int size); /* ** Function: PROSLIC_LoadPatch ** ** Description: ** Loads patch to the ProSLIC ** ** Input Parameters: ** pProslic: pointer to PROSLIC object ** pPatch: pointer to patch data ** ** Return: ** none */ int Si3226x_LoadPatch (proslicChanType_ptr hProslic, const proslicPatch *pPatch); /* ** Function: PROSLIC_VerifyPatch ** ** Description: ** Verifies patch to the ProSLIC ** ** Input Parameters: ** pProslic: pointer to PROSLIC object ** pPatch: pointer to patch data ** ** Return: ** none */ int Si3226x_VerifyPatch (proslicChanType_ptr hProslic, const proslicPatch *pPatch); /* ** Function: PROSLIC_EnableInterrupts ** ** Description: ** Enables interrupts ** ** Input Parameters: ** hProslic: pointer to Proslic object ** ** Return: ** */ int Si3226x_EnableInterrupts (proslicChanType_ptr hProslic); int Si3226x_DisableInterrupts (proslicChanType_ptr hProslic); /* ** Function: PROSLIC_SetLoopbackMode ** ** Description: ** Set loopback test mode ** ** Input Parameters: ** hProslic: pointer to Proslic object ** ** Return: ** */ int Si3226x_SetLoopbackMode (proslicChanType_ptr hProslic, ProslicLoopbackModes newMode); /* ** Function: PROSLIC_SetMuteStatus ** ** Description: ** Set mute(s) ** ** Input Parameters: ** hProslic: pointer to Proslic object ** ** Return: ** */ int Si3226x_SetMuteStatus (proslicChanType_ptr hProslic, ProslicMuteModes muteEn); /* ** ** PROSLIC CONFIGURATION FUNCTIONS ** */ /* ** Function: PROSLIC_RingSetup ** ** Description: ** configure ringing ** ** Input Parameters: ** pProslic: pointer to Proslic object ** pRingSetup: pointer to ringing config structure ** ** Return: ** none */ int Si3226x_RingSetup (proslicChanType *pProslic, int preset); /* ** Function: PROSLIC_ToneGenSetup ** ** Description: ** configure tone generators ** ** Input Parameters: ** pProslic: pointer to Proslic object ** pTone: pointer to tones config structure ** ** Return: ** none */ int Si3226x_ToneGenSetup (proslicChanType *pProslic, int preset); /* ** Function: PROSLIC_FSKSetup ** ** Description: ** configure fsk ** ** Input Parameters: ** pProslic: pointer to Proslic object ** pFsk: pointer to fsk config structure ** ** Return: ** none */ int Si3226x_FSKSetup (proslicChanType *pProslic, int preset); /* * Function: Si3226x_ModifyStartBits * * Description: To change the FSK start/stop bits field. * Returns RC_NONE if OK. */ int Si3226x_ModifyCIDStartBits(proslicChanType_ptr pProslic, uInt8 enable_startStop); /* ** Function: PROSLIC_DTMFDecodeSetup ** ** Description: ** configure dtmf decode ** ** Input Parameters: ** pProslic: pointer to Proslic object ** pDTMFDec: pointer to dtmf decoder config structure ** ** Return: ** none */ int Si3226x_DTMFDecodeSetup (proslicChanType *pProslic, int preset); /* ** Function: PROSLIC_SetProfile ** ** Description: ** set country profile of the proslic ** ** Input Parameters: ** pProslic: pointer to Proslic object ** pCountryData: pointer to country config structure ** ** Return: ** none */ int Si3226x_SetProfile (proslicChanType *pProslic, int preset); /* ** Function: PROSLIC_ZsynthSetup ** ** Description: ** configure impedence synthesis ** ** Input Parameters: ** pProslic: pointer to Proslic object ** pZynth: pointer to zsynth config structure ** ** Return: ** none */ int Si3226x_ZsynthSetup (proslicChanType *pProslic, int preset); /* ** Function: PROSLIC_GciCISetup ** ** Description: ** configure CI bits (GCI mode) ** ** Input Parameters: ** pProslic: pointer to Proslic object ** pCI: pointer to ringing config structure ** ** Return: ** none */ int Si3226x_GciCISetup (proslicChanType *pProslic, int preset); /* ** Function: PROSLIC_ModemDetSetup ** ** Description: ** configure modem detector ** ** Input Parameters: ** pProslic: pointer to Proslic object ** pModemDet: pointer to modem det config structure ** ** Return: ** none */ int Si3226x_ModemDetSetup (proslicChanType *pProslic, int preset); /* ** Function: PROSLIC_AudioGainSetup ** ** Description: ** configure audio gains ** ** Input Parameters: ** pProslic: pointer to Proslic object ** pAudio: pointer to audio gains config structure ** ** Return: ** none */ int Si3226x_TXAudioGainSetup (proslicChanType *pProslic, int preset); int Si3226x_RXAudioGainSetup (proslicChanType *pProslic, int preset); #define Si3226x_AudioGainSetup ProSLIC_AudioGainSetup int Si3226x_TXAudioGainScale (proslicChanType *pProslic, int preset, uInt32 pga_scale, uInt32 eq_scale); int Si3226x_RXAudioGainScale (proslicChanType *pProslic, int preset, uInt32 pga_scale, uInt32 eq_scale); /* ** Function: PROSLIC_HybridSetup ** ** Description: ** configure Proslic hybrid ** ** Input Parameters: ** pProslic: pointer to Proslic object ** pHybridCfg: pointer to ringing config structure ** ** Return: ** none */ int Si3226x_HybridSetup (proslicChanType *pProslic, int preset); /* ** Function: PROSLIC_AudioEQSetup ** ** Description: ** configure audio equalizers ** ** Input Parameters: ** pProslic: pointer to Proslic object ** pAudioEQ: pointer to ringing config structure ** ** Return: ** none */ int Si3226x_AudioEQSetup (proslicChanType *pProslic, int preset); /* ** Function: PROSLIC_DCFeedSetup ** ** Description: ** configure dc feed ** ** Input Parameters: ** pProslic: pointer to Proslic object ** pDcFeed: pointer to dc feed config structure ** ** Return: ** none */ int Si3226x_DCFeedSetup (proslicChanType *pProslic,int preset); int Si3226x_DCFeedSetupCfg (proslicChanType *pProslic,ProSLIC_DCfeed_Cfg *cfg,int preset); /* ** Function: PROSLIC_GPIOSetup ** ** Description: ** configure gpio ** ** Input Parameters: ** pProslic: pointer to Proslic object ** pGpio: pointer to gpio config structure ** ** Return: ** none */ int Si3226x_GPIOSetup (proslicChanType *pProslic); /* ** Function: PROSLIC_PCMSetup ** ** Description: ** configure pcm ** ** Input Parameters: ** pProslic: pointer to Proslic object ** pPcm: pointer to pcm config structure ** ** Return: ** none */ int Si3226x_PCMSetup (proslicChanType *pProslic, int preset); int Si3226x_PCMTimeSlotSetup (proslicChanType *pProslic, uInt16 rxcount, uInt16 txcount); /* ** ** PROSLIC CONTROL FUNCTIONS ** */ /* ** Function: PROSLIC_GetInterrupts ** ** Description: ** Enables interrupts ** ** Input Parameters: ** hProslic: pointer to Proslic object ** pIntData: pointer to interrupt info retrieved ** ** Return: ** */ int Si3226x_GetInterrupts (proslicChanType_ptr hProslic, proslicIntType *pIntData); /* ** Function: PROSLIC_ReadHookStatus ** ** Description: ** Determine hook status ** ** Input Parameters: ** pProslic: pointer to Proslic object ** pHookStat: current hook status ** ** Return: ** none */ int Si3226x_ReadHookStatus (proslicChanType *pProslic,uInt8 *pHookStat); /* ** Function: PROSLIC_WriteLinefeed ** ** Description: ** Sets linefeed state ** ** Input Parameters: ** pProslic: pointer to Proslic object ** newLinefeed: new linefeed state ** ** Return: ** none */ int Si3226x_SetLinefeedStatus (proslicChanType *pProslic,uInt8 newLinefeed); /* ** Function: PROSLIC_SetLinefeedBroadcast ** ** Description: ** Sets linefeed state ** ** Input Parameters: ** pProslic: pointer to Proslic object ** newLinefeed: new linefeed state ** ** Return: ** none */ int Si3226x_SetLinefeedStatusBroadcast (proslicChanType *pProslic, uInt8 newLinefeed); /* ** Function: PROSLIC_PolRev ** ** Description: ** Sets polarity reversal state ** ** Input Parameters: ** pProslic: pointer to Proslic object ** abrupt: set this to 1 for abrupt pol rev ** newPolRevState: new pol rev state ** ** Return: ** none */ int Si3226x_PolRev (proslicChanType *pProslic,uInt8 abrupt, uInt8 newPolRevState); /* ** Function: PROSLIC_GPIOControl ** ** Description: ** Sets gpio of the proslic ** ** Input Parameters: ** pProslic: pointer to Proslic object ** pGpioData: pointer to gpio status ** read: set to 1 to read status, 0 to write ** ** Return: ** none */ int Si3226x_GPIOControl (proslicChanType *pProslic,uInt8 *pGpioData, uInt8 read); /* ** Function: ProSLIC_MWISetup ** ** Description: ** Modify default MWI amplitude and switch debounce parameters ** ** Input Parameters: ** pProslic: pointer to Proslic object ** vpk_mag: peak flash voltgage (vpk) - passing a 0 results ** in no change to VBATH_NEON ** lcmrmask_mwi: LCR mask time (ms) after MWI state switch - passing ** a 0 results in no change to LCRMASK_MWI ** ** Return: ** none */ int Si3226x_MWISetup (proslicChanType *pProslic,uInt16 vpk_mag,uInt16 lcrmask_mwi); /* ** Function: ProSLIC_MWIEnable ** ** Description: ** Enable MWI feature ** ** Input Parameters: ** pProslic: pointer to Proslic object ** ** Return: ** none */ int Si3226x_MWIEnable (proslicChanType *pProslic); /* ** Function: ProSLIC_MWIDisable ** ** Description: ** Disable MWI feature ** ** Input Parameters: ** pProslic: pointer to Proslic object ** ** Return: ** none */ int Si3226x_MWIDisable (proslicChanType *pProslic); /* ** Function: ProSLIC_SetMWIState ** ** Description: ** Set MWI state ** ** Input Parameters: ** pProslic: pointer to Proslic object ** flash_on: 0 = low, 1 = high (VBATH_NEON) ** ** Return: ** none */ int Si3226x_SetMWIState (proslicChanType *pProslic,uInt8 flash_on); /* ** Function: ProSLIC_GetMWIState ** ** Description: ** Read MWI state ** ** Input Parameters: ** pProslic: pointer to Proslic object ** ** Return: ** 0 - Flash OFF, 1 - Flash ON, RC_MWI_NOT_ENABLED */ int Si3226x_GetMWIState (proslicChanType *pProslic); /* ** Function: ProSLIC_MWI ** ** Description: ** implements message waiting indicator ** ** Input Parameters: ** pProslic: pointer to Proslic object ** lampOn: 0 = turn lamp off, 1 = turn lamp on ** ** Return: ** none ** ** Use Deprecated. */ int Si3226x_MWI (proslicChanType *pProslic,uInt8 lampOn); /* ** Function: PROSLIC_StartGenericTone ** ** Description: ** Initializes and start tone generators ** ** Input Parameters: ** pProslic: pointer to Proslic object ** timerEn: specifies whether to enable the tone generator timers ** ** Return: ** none */ int Si3226x_ToneGenStart (proslicChanType *pProslic, uInt8 timerEn); /* ** Function: PROSLIC_StopTone ** ** Description: ** Stops tone generators ** ** Input Parameters: ** pProslic: pointer to Proslic object ** ** Return: ** none */ int Si3226x_ToneGenStop (proslicChanType *pProslic); /* ** Function: PROSLIC_StartRing ** ** Description: ** Initializes and start ring generator ** ** Input Parameters: ** pProslic: pointer to Proslic object ** ** Return: ** none */ int Si3226x_RingStart (proslicChanType *pProslic); /* ** Function: PROSLIC_StopRing ** ** Description: ** Stops ring generator ** ** Input Parameters: ** pProslic: pointer to Proslic object ** ** Return: ** none */ int Si3226x_RingStop (proslicChanType *pProslic); /* ** Function: PROSLIC_EnableCID ** ** Description: ** enable fsk ** ** Input Parameters: ** pProslic: pointer to Proslic object ** ** Return: ** none */ int Si3226x_EnableCID (proslicChanType *pProslic); /* ** Function: PROSLIC_DisableCID ** ** Description: ** disable fsk ** ** Input Parameters: ** pProslic: pointer to Proslic object ** ** Return: ** none */ int Si3226x_DisableCID (proslicChanType *pProslic); /* ** Function: PROSLIC_SendCID ** ** Description: ** send fsk data ** ** Input Parameters: ** pProslic: pointer to Proslic object ** buffer: buffer to send ** numBytes: num of bytes in the buffer ** ** Return: ** none */ int Si3226x_SendCID (proslicChanType *pProslic, uInt8 *buffer, uInt8 numBytes); int Si3226x_CheckCIDBuffer (proslicChanType *pProslic, uInt8 *fsk_buf_avail); /* ** Function: PROSLIC_StartPCM ** ** Description: ** Starts PCM ** ** Input Parameters: ** pProslic: pointer to Proslic object ** ** Return: ** none */ int Si3226x_PCMStart (proslicChanType *pProslic); /* ** Function: PROSLIC_StopPCM ** ** Description: ** Disables PCM ** ** Input Parameters: ** pProslic: pointer to Proslic object ** ** Return: ** none */ int Si3226x_PCMStop (proslicChanType *pProslic); /* ** Function: PROSLIC_ReadDTMFDigit ** ** Description: ** Read DTMF digit (would be called after DTMF interrupt to collect digit) ** ** Input Parameters: ** pProslic: pointer to Proslic object ** pDigit: digit read ** ** Return: ** none */ int Si3226x_DTMFReadDigit (proslicChanType *pProslic,uInt8 *pDigit); /* ** Function: PROSLIC_PLLFreeRunStart ** ** Description: ** initiates pll free run mode ** ** Input Parameters: ** pProslic: pointer to Proslic object ** ** Return: ** none */ int Si3226x_PLLFreeRunStart (proslicChanType *pProslic); /* ** Function: PROSLIC_PLLFreeRunStop ** ** Description: ** exit pll free run mode ** ** Input Parameters: ** pProslic: pointer to Proslic object ** ** Return: ** none */ int Si3226x_PLLFreeRunStop (proslicChanType *pProslic); /* ** Function: PROSLIC_PulseMeterSetup ** ** Description: ** configure pulse metering ** ** Input Parameters: ** pProslic: pointer to Proslic object ** pPulseCfg: pointer to pulse metering config structure ** ** Return: ** none */ int Si3226x_PulseMeterSetup (proslicChanType *pProslic, int preset); /* ** Function: PROSLIC_PulseMeterEnable ** ** Description: ** enable pulse meter generation ** ** Input Parameters: ** pProslic: pointer to Proslic object ** ** Return: ** none */ int Si3226x_PulseMeterEnable (proslicChanType *pProslic); /* ** Function: PROSLIC_PulseMeterDisable ** ** Description: ** disable pulse meter generation ** ** Input Parameters: ** pProslic: pointer to Proslic object ** ** Return: ** none */ int Si3226x_PulseMeterDisable (proslicChanType *pProslic); /* ** Function: PROSLIC_PulseMeterStart ** ** Description: ** start pulse meter tone ** ** Input Parameters: ** pProslic: pointer to Proslic object ** ** Return: ** none */ int Si3226x_PulseMeterStart (proslicChanType *pProslic); /* ** Function: PROSLIC_PulseMeterStop ** ** Description: ** stop pulse meter tone ** ** Input Parameters: ** pProslic: pointer to Proslic object ** ** Return: ** none */ int Si3226x_PulseMeterStop (proslicChanType *pProslic); /* ** Function: PROSLIC_LBCal ** ** Description: ** Execute longitudinal balance calibration ** ** Input Parameters: ** hProslic: pointer to array of Proslic objects ** ** Return: ** */ int Si3226x_LBCal (proslicChanType_ptr *pProslic, int size); int Si3226x_GetLBCalResult (proslicChanType *pProslic,int32 *result1,int32 *result2,int32 *result3,int32 *result4); int Si3226x_GetLBCalResultPacked (proslicChanType *pProslic,int32 *result); int Si3226x_LoadPreviousLBCal (proslicChanType *pProslic,int32 result1,int32 result2,int32 result3,int32 result4); int Si3226x_LoadPreviousLBCalPacked (proslicChanType *pProslic,int32 *result); /* ** Function: PROSLIC_dbgSetDCFeed ** ** Description: ** provisionary function for setting up ** dcfeed given desired open circuit voltage ** and loop current. */ int Si3226x_dbgSetDCFeed (proslicChanType *pProslic, uInt32 v_vlim_val, uInt32 i_ilim_val, int32 preset); /* ** Function: PROSLIC_dbgSetDCFeedVopen ** ** Description: ** provisionary function for setting up ** dcfeed given desired open circuit voltage ** and loop current. */ int Si3226x_dbgSetDCFeedVopen (proslicChanType *pProslic, uInt32 v_vlim_val, int32 preset); /* ** Function: PROSLIC_dbgSetDCFeedIloop ** ** Description: ** provisionary function for setting up ** dcfeed given desired open circuit voltage ** and loop current. */ int Si3226x_dbgSetDCFeedIloop (proslicChanType *pProslic, uInt32 i_ilim_val, int32 preset); /* ** Function: PROSLIC_dbgRingingSetup ** ** Description: ** Provisionary function for setting up ** Ring type, frequency, amplitude and dc offset. ** Main use will be by peek/poke applications. */ int Si3226x_dbgSetRinging (proslicChanType *pProslic, ProSLIC_dbgRingCfg *ringCfg, int preset); /* ** Function: PROSLIC_dbgSetRXGain ** ** Description: ** Provisionary function for setting up ** RX path gain. */ int Si3226x_dbgSetRXGain (proslicChanType *pProslic, int32 gain, int impedance_preset, int audio_gain_preset); /* ** Function: PROSLIC_dbgSetTXGain ** ** Description: ** Provisionary function for setting up ** TX path gain. */ int Si3226x_dbgSetTXGain (proslicChanType *pProslic, int32 gain, int impedance_preset, int audio_gain_preset); /* ** Function: PROSLIC_LineMonitor ** ** Description: ** Monitor line voltages and currents */ int Si3226x_LineMonitor(proslicChanType *pProslic, proslicMonitorType *monitor); /* ** Function: PROSLIC_PSTNCheck ** ** Description: ** Continuous monitor of ilong to detect hot pstn line */ int Si3226x_PSTNCheck(proslicChanType *pProslic, proslicPSTNCheckObjType *pstnCheckObj); /* ** Function: PROSLIC_DiffPSTNCheck ** ** Description: ** Detection of foreign PSTN */ int Si3226x_DiffPSTNCheck (proslicChanType *pProslic, proslicDiffPSTNCheckObjType *pPSTNCheck); /* ** Function: PROSLIC_SetPowersaveMode ** ** Description: ** Enable or Disable powersave mode */ int Si3226x_SetPowersaveMode(proslicChanType *pProslic, int pwrsave); /* ** Function: PROSLIC_ReadMADCScaled ** ** Description: ** ReadMADC (or other sensed voltage/currents) and ** return scaled value in int32 format */ int32 Si3226x_ReadMADCScaled(proslicChanType *pProslic, uInt16 addr, int32 scale); #endif
stas2z/linux-3.10-witi
drivers/char/pcm/proslic_api/inc/si3226x_intf.h
C
gpl-2.0
22,557
/* * arch/s390/kernel/sys_s390.c * * S390 version * Copyright (C) 1999,2000 IBM Deutschland Entwicklung GmbH, IBM Corporation * Author(s): Martin Schwidefsky ([email protected]), * Thomas Spatzier ([email protected]) * * Derived from "arch/i386/kernel/sys_i386.c" * * This file contains various random system calls that * have a non-standard calling sequence on the Linux/s390 * platform. */ #include <linux/errno.h> #include <linux/sched.h> #include <linux/mm.h> #include <linux/fs.h> #include <linux/smp.h> #include <linux/sem.h> #include <linux/msg.h> #include <linux/shm.h> #include <linux/stat.h> #include <linux/syscalls.h> #include <linux/mman.h> #include <linux/file.h> #include <linux/utsname.h> #include <linux/personality.h> #include <linux/unistd.h> #include <linux/ipc.h> #include <asm/uaccess.h> #include "entry.h" /* * Perform the mmap() system call. Linux for S/390 isn't able to handle more * than 5 system call parameters, so this system call uses a memory block * for parameter passing. */ struct s390_mmap_arg_struct { unsigned long addr; unsigned long len; unsigned long prot; unsigned long flags; unsigned long fd; unsigned long offset; }; SYSCALL_DEFINE1(mmap2, struct s390_mmap_arg_struct __user *, arg) { struct s390_mmap_arg_struct a; int error = -EFAULT; if (copy_from_user(&a, arg, sizeof(a))) goto out; error = sys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd, a.offset); out: return error; } /* * sys_ipc() is the de-multiplexer for the SysV IPC calls. */ SYSCALL_DEFINE5(s390_ipc, uint, call, int, first, unsigned long, second, unsigned long, third, void __user *, ptr) { if (call >> 16) return -EINVAL; /* The s390 sys_ipc variant has only five parameters instead of six * like the generic variant. The only difference is the handling of * the SEMTIMEDOP subcall where on s390 the third parameter is used * as a pointer to a struct timespec where the generic variant uses * the fifth parameter. * Therefore we can call the generic variant by simply passing the * third parameter also as fifth parameter. */ return sys_ipc(call, first, second, third, ptr, third); } #ifdef CONFIG_64BIT SYSCALL_DEFINE1(s390_personality, unsigned int, personality) { unsigned int ret; if (current->personality == PER_LINUX32 && personality == PER_LINUX) personality = PER_LINUX32; ret = sys_personality(personality); if (ret == PER_LINUX32) ret = PER_LINUX; return ret; } #endif /* CONFIG_64BIT */ /* * Wrapper function for sys_fadvise64/fadvise64_64 */ #ifndef CONFIG_64BIT SYSCALL_DEFINE5(s390_fadvise64, int, fd, u32, offset_high, u32, offset_low, size_t, len, int, advice) { return sys_fadvise64(fd, (u64) offset_high << 32 | offset_low, len, advice); } struct fadvise64_64_args { int fd; long long offset; long long len; int advice; }; SYSCALL_DEFINE1(s390_fadvise64_64, struct fadvise64_64_args __user *, args) { struct fadvise64_64_args a; if ( copy_from_user(&a, args, sizeof(a)) ) return -EFAULT; return sys_fadvise64_64(a.fd, a.offset, a.len, a.advice); } /* * This is a wrapper to call sys_fallocate(). For 31 bit s390 the last * 64 bit argument "len" is split into the upper and lower 32 bits. The * system call wrapper in the user space loads the value to %r6/%r7. * The code in entry.S keeps the values in %r2 - %r6 where they are and * stores %r7 to 96(%r15). But the standard C linkage requires that * the whole 64 bit value for len is stored on the stack and doesn't * use %r6 at all. So s390_fallocate has to convert the arguments from * %r2: fd, %r3: mode, %r4/%r5: offset, %r6/96(%r15)-99(%r15): len * to * %r2: fd, %r3: mode, %r4/%r5: offset, 96(%r15)-103(%r15): len */ SYSCALL_DEFINE(s390_fallocate)(int fd, int mode, loff_t offset, u32 len_high, u32 len_low) { return sys_fallocate(fd, mode, offset, ((u64)len_high << 32) | len_low); } #ifdef CONFIG_HAVE_SYSCALL_WRAPPERS asmlinkage long SyS_s390_fallocate(long fd, long mode, loff_t offset, long len_high, long len_low) { return SYSC_s390_fallocate((int) fd, (int) mode, offset, (u32) len_high, (u32) len_low); } SYSCALL_ALIAS(sys_s390_fallocate, SyS_s390_fallocate); #endif #endif
Jackeagle/android_kernel_sony_c2305
arch/s390/kernel/sys_s390.c
C
gpl-2.0
4,389
# Game_Idle_TheLostLand 放置类单机游戏 ## 基本描述 - Engine : [Phaser](https://github.com/photonstorm/phaser). 2.4.4 - Develop enviorment: IntelliJ IDEA 2016 ## 依赖库 ### RS GUI Phaser的UI库 ### Phaser-Debug Phaser Debug调试器 ### Phaser-Inspector Phaser 性能监视器 ### Juicy 简易特效支持 * 摄像机震动 * 闪屏 * 对象拖尾 * 精灵的果冻缩放效果 * 过度缩放等 ### ColorHarmony 进行颜色混合调整的一个库 ###newgroundsio.min.js 使用NewGrounds的API接口
duzhi5368/duzhi5368.github.io
OLDPAGE/Games/Game_Idle_TheLostLand/README.md
Markdown
gpl-2.0
532
# -*- coding: utf-8 -*- # from rest_framework import viewsets from rest_framework.decorators import action from rest_framework.exceptions import MethodNotAllowed from rest_framework.response import Response from common.const.http import POST, PUT from common.mixins.api import CommonApiMixin from common.permissions import IsValidUser, IsOrgAdmin from tickets import serializers from tickets.models import Ticket from tickets.permissions.ticket import IsAssignee, IsAssigneeOrApplicant, NotClosed __all__ = ['TicketViewSet'] class TicketViewSet(CommonApiMixin, viewsets.ModelViewSet): permission_classes = (IsValidUser,) serializer_class = serializers.TicketDisplaySerializer serializer_classes = { 'open': serializers.TicketApplySerializer, 'approve': serializers.TicketApproveSerializer, } filterset_fields = [ 'id', 'title', 'type', 'action', 'status', 'applicant', 'applicant_display', 'processor', 'processor_display', 'assignees__id' ] search_fields = [ 'title', 'action', 'type', 'status', 'applicant_display', 'processor_display' ] def create(self, request, *args, **kwargs): raise MethodNotAllowed(self.action) def update(self, request, *args, **kwargs): raise MethodNotAllowed(self.action) def destroy(self, request, *args, **kwargs): raise MethodNotAllowed(self.action) def get_queryset(self): queryset = Ticket.get_user_related_tickets(self.request.user) return queryset def perform_create(self, serializer): instance = serializer.save() instance.open(applicant=self.request.user) @action(detail=False, methods=[POST], permission_classes=[IsValidUser, ]) def open(self, request, *args, **kwargs): return super().create(request, *args, **kwargs) @action(detail=True, methods=[PUT], permission_classes=[IsOrgAdmin, IsAssignee, NotClosed]) def approve(self, request, *args, **kwargs): response = super().update(request, *args, **kwargs) instance = self.get_object() instance.approve(processor=self.request.user) return response @action(detail=True, methods=[PUT], permission_classes=[IsOrgAdmin, IsAssignee, NotClosed]) def reject(self, request, *args, **kwargs): instance = self.get_object() serializer = self.get_serializer(instance) instance.reject(processor=request.user) return Response(serializer.data) @action(detail=True, methods=[PUT], permission_classes=[IsAssigneeOrApplicant, NotClosed]) def close(self, request, *args, **kwargs): instance = self.get_object() serializer = self.get_serializer(instance) instance.close(processor=request.user) return Response(serializer.data)
skyoo/jumpserver
apps/tickets/api/ticket.py
Python
gpl-2.0
2,796
/* * GIT - The information manager from hell * * Copyright (C) Linus Torvalds, 2005 * Copyright (C) Johannes Schindelin, 2005 * */ #include "cache.h" #include "exec_cmd.h" #include "strbuf.h" #include "quote.h" typedef struct config_file { struct config_file *prev; FILE *f; const char *name; int linenr; int eof; struct strbuf value; struct strbuf var; } config_file; static config_file *cf; static int zlib_compression_seen; #define MAX_INCLUDE_DEPTH 10 static const char include_depth_advice[] = "exceeded maximum include depth (%d) while including\n" " %s\n" "from\n" " %s\n" "Do you have circular includes?"; static int handle_path_include(const char *path, struct config_include_data *inc) { int ret = 0; struct strbuf buf = STRBUF_INIT; char *expanded = expand_user_path(path); if (!expanded) return error("Could not expand include path '%s'", path); path = expanded; /* * Use an absolute path as-is, but interpret relative paths * based on the including config file. */ if (!is_absolute_path(path)) { char *slash; if (!cf || !cf->name) return error("relative config includes must come from files"); slash = find_last_dir_sep(cf->name); if (slash) strbuf_add(&buf, cf->name, slash - cf->name + 1); strbuf_addstr(&buf, path); path = buf.buf; } if (!access_or_die(path, R_OK)) { if (++inc->depth > MAX_INCLUDE_DEPTH) die(include_depth_advice, MAX_INCLUDE_DEPTH, path, cf && cf->name ? cf->name : "the command line"); ret = git_config_from_file(git_config_include, path, inc); inc->depth--; } strbuf_release(&buf); free(expanded); return ret; } int git_config_include(const char *var, const char *value, void *data) { struct config_include_data *inc = data; const char *type; int ret; /* * Pass along all values, including "include" directives; this makes it * possible to query information on the includes themselves. */ ret = inc->fn(var, value, inc->data); if (ret < 0) return ret; type = skip_prefix(var, "include."); if (!type) return ret; if (!strcmp(type, "path")) ret = handle_path_include(value, inc); return ret; } static void lowercase(char *p) { for (; *p; p++) *p = tolower(*p); } void git_config_push_parameter(const char *text) { struct strbuf env = STRBUF_INIT; const char *old = getenv(CONFIG_DATA_ENVIRONMENT); if (old) { strbuf_addstr(&env, old); strbuf_addch(&env, ' '); } sq_quote_buf(&env, text); setenv(CONFIG_DATA_ENVIRONMENT, env.buf, 1); strbuf_release(&env); } int git_config_parse_parameter(const char *text, config_fn_t fn, void *data) { struct strbuf **pair; pair = strbuf_split_str(text, '=', 2); if (!pair[0]) return error("bogus config parameter: %s", text); if (pair[0]->len && pair[0]->buf[pair[0]->len - 1] == '=') strbuf_setlen(pair[0], pair[0]->len - 1); strbuf_trim(pair[0]); if (!pair[0]->len) { strbuf_list_free(pair); return error("bogus config parameter: %s", text); } lowercase(pair[0]->buf); if (fn(pair[0]->buf, pair[1] ? pair[1]->buf : NULL, data) < 0) { strbuf_list_free(pair); return -1; } strbuf_list_free(pair); return 0; } int git_config_from_parameters(config_fn_t fn, void *data) { const char *env = getenv(CONFIG_DATA_ENVIRONMENT); char *envw; const char **argv = NULL; int nr = 0, alloc = 0; int i; if (!env) return 0; /* sq_dequote will write over it */ envw = xstrdup(env); if (sq_dequote_to_argv(envw, &argv, &nr, &alloc) < 0) { free(envw); return error("bogus format in " CONFIG_DATA_ENVIRONMENT); } for (i = 0; i < nr; i++) { if (git_config_parse_parameter(argv[i], fn, data) < 0) { free(argv); free(envw); return -1; } } free(argv); free(envw); return nr > 0; } static int get_next_char(void) { int c; FILE *f; c = '\n'; if (cf && ((f = cf->f) != NULL)) { c = fgetc(f); if (c == '\r') { /* DOS like systems */ c = fgetc(f); if (c != '\n') { ungetc(c, f); c = '\r'; } } if (c == '\n') cf->linenr++; if (c == EOF) { cf->eof = 1; c = '\n'; } } return c; } static char *parse_value(void) { int quote = 0, comment = 0, space = 0; strbuf_reset(&cf->value); for (;;) { int c = get_next_char(); if (c == '\n') { if (quote) { cf->linenr--; return NULL; } return cf->value.buf; } if (comment) continue; if (isspace(c) && !quote) { if (cf->value.len) space++; continue; } if (!quote) { if (c == ';' || c == '#') { comment = 1; continue; } } for (; space; space--) strbuf_addch(&cf->value, ' '); if (c == '\\') { c = get_next_char(); switch (c) { case '\n': continue; case 't': c = '\t'; break; case 'b': c = '\b'; break; case 'n': c = '\n'; break; /* Some characters escape as themselves */ case '\\': case '"': break; /* Reject unknown escape sequences */ default: return NULL; } strbuf_addch(&cf->value, c); continue; } if (c == '"') { quote = 1-quote; continue; } strbuf_addch(&cf->value, c); } } static inline int iskeychar(int c) { return isalnum(c) || c == '-'; } static int get_value(config_fn_t fn, void *data, struct strbuf *name) { int c; char *value; /* Get the full name */ for (;;) { c = get_next_char(); if (cf->eof) break; if (!iskeychar(c)) break; strbuf_addch(name, tolower(c)); } while (c == ' ' || c == '\t') c = get_next_char(); value = NULL; if (c != '\n') { if (c != '=') return -1; value = parse_value(); if (!value) return -1; } return fn(name->buf, value, data); } static int get_extended_base_var(struct strbuf *name, int c) { do { if (c == '\n') goto error_incomplete_line; c = get_next_char(); } while (isspace(c)); /* We require the format to be '[base "extension"]' */ if (c != '"') return -1; strbuf_addch(name, '.'); for (;;) { int c = get_next_char(); if (c == '\n') goto error_incomplete_line; if (c == '"') break; if (c == '\\') { c = get_next_char(); if (c == '\n') goto error_incomplete_line; } strbuf_addch(name, c); } /* Final ']' */ if (get_next_char() != ']') return -1; return 0; error_incomplete_line: cf->linenr--; return -1; } static int get_base_var(struct strbuf *name) { for (;;) { int c = get_next_char(); if (cf->eof) return -1; if (c == ']') return 0; if (isspace(c)) return get_extended_base_var(name, c); if (!iskeychar(c) && c != '.') return -1; strbuf_addch(name, tolower(c)); } } static int git_parse_file(config_fn_t fn, void *data) { int comment = 0; int baselen = 0; struct strbuf *var = &cf->var; /* U+FEFF Byte Order Mark in UTF8 */ static const unsigned char *utf8_bom = (unsigned char *) "\xef\xbb\xbf"; const unsigned char *bomptr = utf8_bom; for (;;) { int c = get_next_char(); if (bomptr && *bomptr) { /* We are at the file beginning; skip UTF8-encoded BOM * if present. Sane editors won't put this in on their * own, but e.g. Windows Notepad will do it happily. */ if ((unsigned char) c == *bomptr) { bomptr++; continue; } else { /* Do not tolerate partial BOM. */ if (bomptr != utf8_bom) break; /* No BOM at file beginning. Cool. */ bomptr = NULL; } } if (c == '\n') { if (cf->eof) return 0; comment = 0; continue; } if (comment || isspace(c)) continue; if (c == '#' || c == ';') { comment = 1; continue; } if (c == '[') { /* Reset prior to determining a new stem */ strbuf_reset(var); if (get_base_var(var) < 0 || var->len < 1) break; strbuf_addch(var, '.'); baselen = var->len; continue; } if (!isalpha(c)) break; /* * Truncate the var name back to the section header * stem prior to grabbing the suffix part of the name * and the value. */ strbuf_setlen(var, baselen); strbuf_addch(var, tolower(c)); if (get_value(fn, data, var) < 0) break; } die("bad config file line %d in %s", cf->linenr, cf->name); } static int parse_unit_factor(const char *end, uintmax_t *val) { if (!*end) return 1; else if (!strcasecmp(end, "k")) { *val *= 1024; return 1; } else if (!strcasecmp(end, "m")) { *val *= 1024 * 1024; return 1; } else if (!strcasecmp(end, "g")) { *val *= 1024 * 1024 * 1024; return 1; } return 0; } static int git_parse_long(const char *value, long *ret) { if (value && *value) { char *end; intmax_t val; uintmax_t uval; uintmax_t factor = 1; errno = 0; val = strtoimax(value, &end, 0); if (errno == ERANGE) return 0; if (!parse_unit_factor(end, &factor)) return 0; uval = abs(val); uval *= factor; if ((uval > maximum_signed_value_of_type(long)) || (abs(val) > uval)) return 0; val *= factor; *ret = val; return 1; } return 0; } int git_parse_ulong(const char *value, unsigned long *ret) { if (value && *value) { char *end; uintmax_t val; uintmax_t oldval; errno = 0; val = strtoumax(value, &end, 0); if (errno == ERANGE) return 0; oldval = val; if (!parse_unit_factor(end, &val)) return 0; if ((val > maximum_unsigned_value_of_type(long)) || (oldval > val)) return 0; *ret = val; return 1; } return 0; } static void die_bad_config(const char *name) { if (cf && cf->name) die("bad config value for '%s' in %s", name, cf->name); die("bad config value for '%s'", name); } int git_config_int(const char *name, const char *value) { long ret = 0; if (!git_parse_long(value, &ret)) die_bad_config(name); return ret; } unsigned long git_config_ulong(const char *name, const char *value) { unsigned long ret; if (!git_parse_ulong(value, &ret)) die_bad_config(name); return ret; } static int git_config_maybe_bool_text(const char *name, const char *value) { if (!value) return 1; if (!*value) return 0; if (!strcasecmp(value, "true") || !strcasecmp(value, "yes") || !strcasecmp(value, "on")) return 1; if (!strcasecmp(value, "false") || !strcasecmp(value, "no") || !strcasecmp(value, "off")) return 0; return -1; } int git_config_maybe_bool(const char *name, const char *value) { long v = git_config_maybe_bool_text(name, value); if (0 <= v) return v; if (git_parse_long(value, &v)) return !!v; return -1; } int git_config_bool_or_int(const char *name, const char *value, int *is_bool) { int v = git_config_maybe_bool_text(name, value); if (0 <= v) { *is_bool = 1; return v; } *is_bool = 0; return git_config_int(name, value); } int git_config_bool(const char *name, const char *value) { int discard; return !!git_config_bool_or_int(name, value, &discard); } int git_config_string(const char **dest, const char *var, const char *value) { if (!value) return config_error_nonbool(var); *dest = xstrdup(value); return 0; } int git_config_pathname(const char **dest, const char *var, const char *value) { if (!value) return config_error_nonbool(var); *dest = expand_user_path(value); if (!*dest) die("Failed to expand user dir in: '%s'", value); return 0; } static int git_default_core_config(const char *var, const char *value) { /* This needs a better name */ if (!strcmp(var, "core.filemode")) { trust_executable_bit = git_config_bool(var, value); return 0; } if (!strcmp(var, "core.trustctime")) { trust_ctime = git_config_bool(var, value); return 0; } if (!strcmp(var, "core.statinfo")) { if (!strcasecmp(value, "default")) check_stat = 1; else if (!strcasecmp(value, "minimal")) check_stat = 0; } if (!strcmp(var, "core.quotepath")) { quote_path_fully = git_config_bool(var, value); return 0; } if (!strcmp(var, "core.symlinks")) { has_symlinks = git_config_bool(var, value); return 0; } if (!strcmp(var, "core.ignorecase")) { ignore_case = git_config_bool(var, value); return 0; } if (!strcmp(var, "core.attributesfile")) return git_config_pathname(&git_attributes_file, var, value); if (!strcmp(var, "core.bare")) { is_bare_repository_cfg = git_config_bool(var, value); return 0; } if (!strcmp(var, "core.ignorestat")) { assume_unchanged = git_config_bool(var, value); return 0; } if (!strcmp(var, "core.prefersymlinkrefs")) { prefer_symlink_refs = git_config_bool(var, value); return 0; } if (!strcmp(var, "core.logallrefupdates")) { log_all_ref_updates = git_config_bool(var, value); return 0; } if (!strcmp(var, "core.warnambiguousrefs")) { warn_ambiguous_refs = git_config_bool(var, value); return 0; } if (!strcmp(var, "core.abbrev")) { int abbrev = git_config_int(var, value); if (abbrev < minimum_abbrev || abbrev > 40) return -1; default_abbrev = abbrev; return 0; } if (!strcmp(var, "core.loosecompression")) { int level = git_config_int(var, value); if (level == -1) level = Z_DEFAULT_COMPRESSION; else if (level < 0 || level > Z_BEST_COMPRESSION) die("bad zlib compression level %d", level); zlib_compression_level = level; zlib_compression_seen = 1; return 0; } if (!strcmp(var, "core.compression")) { int level = git_config_int(var, value); if (level == -1) level = Z_DEFAULT_COMPRESSION; else if (level < 0 || level > Z_BEST_COMPRESSION) die("bad zlib compression level %d", level); core_compression_level = level; core_compression_seen = 1; if (!zlib_compression_seen) zlib_compression_level = level; return 0; } if (!strcmp(var, "core.packedgitwindowsize")) { int pgsz_x2 = getpagesize() * 2; packed_git_window_size = git_config_ulong(var, value); /* This value must be multiple of (pagesize * 2) */ packed_git_window_size /= pgsz_x2; if (packed_git_window_size < 1) packed_git_window_size = 1; packed_git_window_size *= pgsz_x2; return 0; } if (!strcmp(var, "core.bigfilethreshold")) { big_file_threshold = git_config_ulong(var, value); return 0; } if (!strcmp(var, "core.packedgitlimit")) { packed_git_limit = git_config_ulong(var, value); return 0; } if (!strcmp(var, "core.deltabasecachelimit")) { delta_base_cache_limit = git_config_ulong(var, value); return 0; } if (!strcmp(var, "core.logpackaccess")) return git_config_string(&log_pack_access, var, value); if (!strcmp(var, "core.autocrlf")) { if (value && !strcasecmp(value, "input")) { if (core_eol == EOL_CRLF) return error("core.autocrlf=input conflicts with core.eol=crlf"); auto_crlf = AUTO_CRLF_INPUT; return 0; } auto_crlf = git_config_bool(var, value); return 0; } if (!strcmp(var, "core.safecrlf")) { if (value && !strcasecmp(value, "warn")) { safe_crlf = SAFE_CRLF_WARN; return 0; } safe_crlf = git_config_bool(var, value); return 0; } if (!strcmp(var, "core.eol")) { if (value && !strcasecmp(value, "lf")) core_eol = EOL_LF; else if (value && !strcasecmp(value, "crlf")) core_eol = EOL_CRLF; else if (value && !strcasecmp(value, "native")) core_eol = EOL_NATIVE; else core_eol = EOL_UNSET; if (core_eol == EOL_CRLF && auto_crlf == AUTO_CRLF_INPUT) return error("core.autocrlf=input conflicts with core.eol=crlf"); return 0; } if (!strcmp(var, "core.notesref")) { notes_ref_name = xstrdup(value); return 0; } if (!strcmp(var, "core.pager")) return git_config_string(&pager_program, var, value); if (!strcmp(var, "core.editor")) return git_config_string(&editor_program, var, value); if (!strcmp(var, "core.commentchar")) { const char *comment; int ret = git_config_string(&comment, var, value); if (!ret) comment_line_char = comment[0]; return ret; } if (!strcmp(var, "core.askpass")) return git_config_string(&askpass_program, var, value); if (!strcmp(var, "core.excludesfile")) return git_config_pathname(&excludes_file, var, value); if (!strcmp(var, "core.whitespace")) { if (!value) return config_error_nonbool(var); whitespace_rule_cfg = parse_whitespace_rule(value); return 0; } if (!strcmp(var, "core.fsyncobjectfiles")) { fsync_object_files = git_config_bool(var, value); return 0; } if (!strcmp(var, "core.preloadindex")) { core_preload_index = git_config_bool(var, value); return 0; } if (!strcmp(var, "core.createobject")) { if (!strcmp(value, "rename")) object_creation_mode = OBJECT_CREATION_USES_RENAMES; else if (!strcmp(value, "link")) object_creation_mode = OBJECT_CREATION_USES_HARDLINKS; else die("Invalid mode for object creation: %s", value); return 0; } if (!strcmp(var, "core.sparsecheckout")) { core_apply_sparse_checkout = git_config_bool(var, value); return 0; } if (!strcmp(var, "core.precomposeunicode")) { precomposed_unicode = git_config_bool(var, value); return 0; } if (!strcmp(var, "core.hidedotfiles")) { if (value && !strcasecmp(value, "dotgitonly")) { hide_dotfiles = HIDE_DOTFILES_DOTGITONLY; return 0; } hide_dotfiles = git_config_bool(var, value); return 0; } /* Add other config variables here and to Documentation/config.txt. */ return 0; } static int git_default_i18n_config(const char *var, const char *value) { if (!strcmp(var, "i18n.commitencoding")) return git_config_string(&git_commit_encoding, var, value); if (!strcmp(var, "i18n.logoutputencoding")) return git_config_string(&git_log_output_encoding, var, value); /* Add other config variables here and to Documentation/config.txt. */ return 0; } static int git_default_branch_config(const char *var, const char *value) { if (!strcmp(var, "branch.autosetupmerge")) { if (value && !strcasecmp(value, "always")) { git_branch_track = BRANCH_TRACK_ALWAYS; return 0; } git_branch_track = git_config_bool(var, value); return 0; } if (!strcmp(var, "branch.autosetuprebase")) { if (!value) return config_error_nonbool(var); else if (!strcmp(value, "never")) autorebase = AUTOREBASE_NEVER; else if (!strcmp(value, "local")) autorebase = AUTOREBASE_LOCAL; else if (!strcmp(value, "remote")) autorebase = AUTOREBASE_REMOTE; else if (!strcmp(value, "always")) autorebase = AUTOREBASE_ALWAYS; else return error("Malformed value for %s", var); return 0; } /* Add other config variables here and to Documentation/config.txt. */ return 0; } static int git_default_push_config(const char *var, const char *value) { if (!strcmp(var, "push.default")) { if (!value) return config_error_nonbool(var); else if (!strcmp(value, "nothing")) push_default = PUSH_DEFAULT_NOTHING; else if (!strcmp(value, "matching")) push_default = PUSH_DEFAULT_MATCHING; else if (!strcmp(value, "simple")) push_default = PUSH_DEFAULT_SIMPLE; else if (!strcmp(value, "upstream")) push_default = PUSH_DEFAULT_UPSTREAM; else if (!strcmp(value, "tracking")) /* deprecated */ push_default = PUSH_DEFAULT_UPSTREAM; else if (!strcmp(value, "current")) push_default = PUSH_DEFAULT_CURRENT; else { error("Malformed value for %s: %s", var, value); return error("Must be one of nothing, matching, simple, " "upstream or current."); } return 0; } /* Add other config variables here and to Documentation/config.txt. */ return 0; } static int git_default_mailmap_config(const char *var, const char *value) { if (!strcmp(var, "mailmap.file")) return git_config_string(&git_mailmap_file, var, value); if (!strcmp(var, "mailmap.blob")) return git_config_string(&git_mailmap_blob, var, value); /* Add other config variables here and to Documentation/config.txt. */ return 0; } int git_default_config(const char *var, const char *value, void *dummy) { if (!prefixcmp(var, "core.")) return git_default_core_config(var, value); if (!prefixcmp(var, "user.")) return git_ident_config(var, value, dummy); if (!prefixcmp(var, "i18n.")) return git_default_i18n_config(var, value); if (!prefixcmp(var, "branch.")) return git_default_branch_config(var, value); if (!prefixcmp(var, "push.")) return git_default_push_config(var, value); if (!prefixcmp(var, "mailmap.")) return git_default_mailmap_config(var, value); if (!prefixcmp(var, "advice.")) return git_default_advice_config(var, value); if (!strcmp(var, "pager.color") || !strcmp(var, "color.pager")) { pager_use_color = git_config_bool(var,value); return 0; } if (!strcmp(var, "pack.packsizelimit")) { pack_size_limit_cfg = git_config_ulong(var, value); return 0; } /* Add other config variables here and to Documentation/config.txt. */ return 0; } int git_config_from_file(config_fn_t fn, const char *filename, void *data) { int ret; FILE *f = fopen(filename, "r"); ret = -1; if (f) { config_file top; /* push config-file parsing state stack */ top.prev = cf; top.f = f; top.name = filename; top.linenr = 1; top.eof = 0; strbuf_init(&top.value, 1024); strbuf_init(&top.var, 1024); cf = &top; ret = git_parse_file(fn, data); /* pop config-file parsing state stack */ strbuf_release(&top.value); strbuf_release(&top.var); cf = top.prev; fclose(f); } return ret; } const char *git_etc_gitconfig(void) { static const char *system_wide; if (!system_wide) system_wide = system_path(ETC_GITCONFIG); return system_wide; } int git_env_bool(const char *k, int def) { const char *v = getenv(k); return v ? git_config_bool(k, v) : def; } int git_config_system(void) { return !git_env_bool("GIT_CONFIG_NOSYSTEM", 0); } int git_config_early(config_fn_t fn, void *data, const char *repo_config) { int ret = 0, found = 0; char *xdg_config = NULL; char *user_config = NULL; home_config_paths(&user_config, &xdg_config, "config"); if (git_config_system() && !access_or_die(git_etc_gitconfig(), R_OK)) { ret += git_config_from_file(fn, git_etc_gitconfig(), data); found += 1; } if (xdg_config && !access_or_die(xdg_config, R_OK)) { ret += git_config_from_file(fn, xdg_config, data); found += 1; } if (user_config && !access_or_die(user_config, R_OK)) { ret += git_config_from_file(fn, user_config, data); found += 1; } if (repo_config && !access_or_die(repo_config, R_OK)) { ret += git_config_from_file(fn, repo_config, data); found += 1; } switch (git_config_from_parameters(fn, data)) { case -1: /* error */ die("unable to parse command-line config"); break; case 0: /* found nothing */ break; default: /* found at least one item */ found++; break; } free(xdg_config); free(user_config); return ret == 0 ? found : ret; } int git_config_with_options(config_fn_t fn, void *data, const char *filename, int respect_includes) { char *repo_config = NULL; int ret; struct config_include_data inc = CONFIG_INCLUDE_INIT; if (respect_includes) { inc.fn = fn; inc.data = data; fn = git_config_include; data = &inc; } /* * If we have a specific filename, use it. Otherwise, follow the * regular lookup sequence. */ if (filename) return git_config_from_file(fn, filename, data); repo_config = git_pathdup("config"); ret = git_config_early(fn, data, repo_config); if (repo_config) free(repo_config); return ret; } int git_config(config_fn_t fn, void *data) { return git_config_with_options(fn, data, NULL, 1); } /* * Find all the stuff for git_config_set() below. */ #define MAX_MATCHES 512 static struct { int baselen; char *key; int do_not_match; regex_t *value_regex; int multi_replace; size_t offset[MAX_MATCHES]; enum { START, SECTION_SEEN, SECTION_END_SEEN, KEY_SEEN } state; int seen; } store; static int matches(const char *key, const char *value) { return !strcmp(key, store.key) && (store.value_regex == NULL || (store.do_not_match ^ !regexec(store.value_regex, value, 0, NULL, 0))); } static int store_aux(const char *key, const char *value, void *cb) { const char *ep; size_t section_len; FILE *f = cf->f; switch (store.state) { case KEY_SEEN: if (matches(key, value)) { if (store.seen == 1 && store.multi_replace == 0) { warning("%s has multiple values", key); } else if (store.seen >= MAX_MATCHES) { error("too many matches for %s", key); return 1; } store.offset[store.seen] = ftell(f); store.seen++; } break; case SECTION_SEEN: /* * What we are looking for is in store.key (both * section and var), and its section part is baselen * long. We found key (again, both section and var). * We would want to know if this key is in the same * section as what we are looking for. We already * know we are in the same section as what should * hold store.key. */ ep = strrchr(key, '.'); section_len = ep - key; if ((section_len != store.baselen) || memcmp(key, store.key, section_len+1)) { store.state = SECTION_END_SEEN; break; } /* * Do not increment matches: this is no match, but we * just made sure we are in the desired section. */ store.offset[store.seen] = ftell(f); /* fallthru */ case SECTION_END_SEEN: case START: if (matches(key, value)) { store.offset[store.seen] = ftell(f); store.state = KEY_SEEN; store.seen++; } else { if (strrchr(key, '.') - key == store.baselen && !strncmp(key, store.key, store.baselen)) { store.state = SECTION_SEEN; store.offset[store.seen] = ftell(f); } } } return 0; } static int write_error(const char *filename) { error("failed to write new configuration file %s", filename); /* Same error code as "failed to rename". */ return 4; } static int store_write_section(int fd, const char *key) { const char *dot; int i, success; struct strbuf sb = STRBUF_INIT; dot = memchr(key, '.', store.baselen); if (dot) { strbuf_addf(&sb, "[%.*s \"", (int)(dot - key), key); for (i = dot - key + 1; i < store.baselen; i++) { if (key[i] == '"' || key[i] == '\\') strbuf_addch(&sb, '\\'); strbuf_addch(&sb, key[i]); } strbuf_addstr(&sb, "\"]\n"); } else { strbuf_addf(&sb, "[%.*s]\n", store.baselen, key); } success = write_in_full(fd, sb.buf, sb.len) == sb.len; strbuf_release(&sb); return success; } static int store_write_pair(int fd, const char *key, const char *value) { int i, success; int length = strlen(key + store.baselen + 1); const char *quote = ""; struct strbuf sb = STRBUF_INIT; /* * Check to see if the value needs to be surrounded with a dq pair. * Note that problematic characters are always backslash-quoted; this * check is about not losing leading or trailing SP and strings that * follow beginning-of-comment characters (i.e. ';' and '#') by the * configuration parser. */ if (value[0] == ' ') quote = "\""; for (i = 0; value[i]; i++) if (value[i] == ';' || value[i] == '#') quote = "\""; if (i && value[i - 1] == ' ') quote = "\""; strbuf_addf(&sb, "\t%.*s = %s", length, key + store.baselen + 1, quote); for (i = 0; value[i]; i++) switch (value[i]) { case '\n': strbuf_addstr(&sb, "\\n"); break; case '\t': strbuf_addstr(&sb, "\\t"); break; case '"': case '\\': strbuf_addch(&sb, '\\'); default: strbuf_addch(&sb, value[i]); break; } strbuf_addf(&sb, "%s\n", quote); success = write_in_full(fd, sb.buf, sb.len) == sb.len; strbuf_release(&sb); return success; } static ssize_t find_beginning_of_line(const char *contents, size_t size, size_t offset_, int *found_bracket) { size_t equal_offset = size, bracket_offset = size; ssize_t offset; contline: for (offset = offset_-2; offset > 0 && contents[offset] != '\n'; offset--) switch (contents[offset]) { case '=': equal_offset = offset; break; case ']': bracket_offset = offset; break; } if (offset > 0 && contents[offset-1] == '\\') { offset_ = offset; goto contline; } if (bracket_offset < equal_offset) { *found_bracket = 1; offset = bracket_offset+1; } else offset++; return offset; } int git_config_set_in_file(const char *config_filename, const char *key, const char *value) { return git_config_set_multivar_in_file(config_filename, key, value, NULL, 0); } int git_config_set(const char *key, const char *value) { return git_config_set_multivar(key, value, NULL, 0); } /* * Auxiliary function to sanity-check and split the key into the section * identifier and variable name. * * Returns 0 on success, -1 when there is an invalid character in the key and * -2 if there is no section name in the key. * * store_key - pointer to char* which will hold a copy of the key with * lowercase section and variable name * baselen - pointer to int which will hold the length of the * section + subsection part, can be NULL */ int git_config_parse_key(const char *key, char **store_key, int *baselen_) { int i, dot, baselen; const char *last_dot = strrchr(key, '.'); /* * Since "key" actually contains the section name and the real * key name separated by a dot, we have to know where the dot is. */ if (last_dot == NULL || last_dot == key) { error("key does not contain a section: %s", key); return -CONFIG_NO_SECTION_OR_NAME; } if (!last_dot[1]) { error("key does not contain variable name: %s", key); return -CONFIG_NO_SECTION_OR_NAME; } baselen = last_dot - key; if (baselen_) *baselen_ = baselen; /* * Validate the key and while at it, lower case it for matching. */ *store_key = xmalloc(strlen(key) + 1); dot = 0; for (i = 0; key[i]; i++) { unsigned char c = key[i]; if (c == '.') dot = 1; /* Leave the extended basename untouched.. */ if (!dot || i > baselen) { if (!iskeychar(c) || (i == baselen + 1 && !isalpha(c))) { error("invalid key: %s", key); goto out_free_ret_1; } c = tolower(c); } else if (c == '\n') { error("invalid key (newline): %s", key); goto out_free_ret_1; } (*store_key)[i] = c; } (*store_key)[i] = 0; return 0; out_free_ret_1: free(*store_key); *store_key = NULL; return -CONFIG_INVALID_KEY; } /* * If value==NULL, unset in (remove from) config, * if value_regex!=NULL, disregard key/value pairs where value does not match. * if multi_replace==0, nothing, or only one matching key/value is replaced, * else all matching key/values (regardless how many) are removed, * before the new pair is written. * * Returns 0 on success. * * This function does this: * * - it locks the config file by creating ".git/config.lock" * * - it then parses the config using store_aux() as validator to find * the position on the key/value pair to replace. If it is to be unset, * it must be found exactly once. * * - the config file is mmap()ed and the part before the match (if any) is * written to the lock file, then the changed part and the rest. * * - the config file is removed and the lock file rename()d to it. * */ int git_config_set_multivar_in_file(const char *config_filename, const char *key, const char *value, const char *value_regex, int multi_replace) { int fd = -1, in_fd; int ret; struct lock_file *lock = NULL; char *filename_buf = NULL; /* parse-key returns negative; flip the sign to feed exit(3) */ ret = 0 - git_config_parse_key(key, &store.key, &store.baselen); if (ret) goto out_free; store.multi_replace = multi_replace; if (!config_filename) config_filename = filename_buf = git_pathdup("config"); /* * The lock serves a purpose in addition to locking: the new * contents of .git/config will be written into it. */ lock = xcalloc(sizeof(struct lock_file), 1); fd = hold_lock_file_for_update(lock, config_filename, 0); if (fd < 0) { error("could not lock config file %s: %s", config_filename, strerror(errno)); free(store.key); ret = CONFIG_NO_LOCK; goto out_free; } /* * If .git/config does not exist yet, write a minimal version. */ in_fd = open(config_filename, O_RDONLY); if ( in_fd < 0 ) { free(store.key); if ( ENOENT != errno ) { error("opening %s: %s", config_filename, strerror(errno)); ret = CONFIG_INVALID_FILE; /* same as "invalid config file" */ goto out_free; } /* if nothing to unset, error out */ if (value == NULL) { ret = CONFIG_NOTHING_SET; goto out_free; } store.key = (char *)key; if (!store_write_section(fd, key) || !store_write_pair(fd, key, value)) goto write_err_out; } else { struct stat st; char *contents; size_t contents_sz, copy_begin, copy_end; int i, new_line = 0; if (value_regex == NULL) store.value_regex = NULL; else { if (value_regex[0] == '!') { store.do_not_match = 1; value_regex++; } else store.do_not_match = 0; store.value_regex = (regex_t*)xmalloc(sizeof(regex_t)); if (regcomp(store.value_regex, value_regex, REG_EXTENDED)) { error("invalid pattern: %s", value_regex); free(store.value_regex); ret = CONFIG_INVALID_PATTERN; goto out_free; } } store.offset[0] = 0; store.state = START; store.seen = 0; /* * After this, store.offset will contain the *end* offset * of the last match, or remain at 0 if no match was found. * As a side effect, we make sure to transform only a valid * existing config file. */ if (git_config_from_file(store_aux, config_filename, NULL)) { error("invalid config file %s", config_filename); free(store.key); if (store.value_regex != NULL) { regfree(store.value_regex); free(store.value_regex); } ret = CONFIG_INVALID_FILE; goto out_free; } free(store.key); if (store.value_regex != NULL) { regfree(store.value_regex); free(store.value_regex); } /* if nothing to unset, or too many matches, error out */ if ((store.seen == 0 && value == NULL) || (store.seen > 1 && multi_replace == 0)) { ret = CONFIG_NOTHING_SET; goto out_free; } fstat(in_fd, &st); contents_sz = xsize_t(st.st_size); contents = xmmap(NULL, contents_sz, PROT_READ, MAP_PRIVATE, in_fd, 0); close(in_fd); if (store.seen == 0) store.seen = 1; for (i = 0, copy_begin = 0; i < store.seen; i++) { if (store.offset[i] == 0) { store.offset[i] = copy_end = contents_sz; } else if (store.state != KEY_SEEN) { copy_end = store.offset[i]; } else copy_end = find_beginning_of_line( contents, contents_sz, store.offset[i]-2, &new_line); if (copy_end > 0 && contents[copy_end-1] != '\n') new_line = 1; /* write the first part of the config */ if (copy_end > copy_begin) { if (write_in_full(fd, contents + copy_begin, copy_end - copy_begin) < copy_end - copy_begin) goto write_err_out; if (new_line && write_str_in_full(fd, "\n") != 1) goto write_err_out; } copy_begin = store.offset[i]; } /* write the pair (value == NULL means unset) */ if (value != NULL) { if (store.state == START) { if (!store_write_section(fd, key)) goto write_err_out; } if (!store_write_pair(fd, key, value)) goto write_err_out; } /* write the rest of the config */ if (copy_begin < contents_sz) if (write_in_full(fd, contents + copy_begin, contents_sz - copy_begin) < contents_sz - copy_begin) goto write_err_out; munmap(contents, contents_sz); } if (commit_lock_file(lock) < 0) { error("could not commit config file %s", config_filename); ret = CONFIG_NO_WRITE; goto out_free; } /* * lock is committed, so don't try to roll it back below. * NOTE: Since lockfile.c keeps a linked list of all created * lock_file structures, it isn't safe to free(lock). It's * better to just leave it hanging around. */ lock = NULL; ret = 0; out_free: if (lock) rollback_lock_file(lock); free(filename_buf); return ret; write_err_out: ret = write_error(lock->filename); goto out_free; } int git_config_set_multivar(const char *key, const char *value, const char *value_regex, int multi_replace) { return git_config_set_multivar_in_file(NULL, key, value, value_regex, multi_replace); } static int section_name_match (const char *buf, const char *name) { int i = 0, j = 0, dot = 0; if (buf[i] != '[') return 0; for (i = 1; buf[i] && buf[i] != ']'; i++) { if (!dot && isspace(buf[i])) { dot = 1; if (name[j++] != '.') break; for (i++; isspace(buf[i]); i++) ; /* do nothing */ if (buf[i] != '"') break; continue; } if (buf[i] == '\\' && dot) i++; else if (buf[i] == '"' && dot) { for (i++; isspace(buf[i]); i++) ; /* do_nothing */ break; } if (buf[i] != name[j++]) break; } if (buf[i] == ']' && name[j] == 0) { /* * We match, now just find the right length offset by * gobbling up any whitespace after it, as well */ i++; for (; buf[i] && isspace(buf[i]); i++) ; /* do nothing */ return i; } return 0; } static int section_name_is_ok(const char *name) { /* Empty section names are bogus. */ if (!*name) return 0; /* * Before a dot, we must be alphanumeric or dash. After the first dot, * anything goes, so we can stop checking. */ for (; *name && *name != '.'; name++) if (*name != '-' && !isalnum(*name)) return 0; return 1; } /* if new_name == NULL, the section is removed instead */ int git_config_rename_section_in_file(const char *config_filename, const char *old_name, const char *new_name) { int ret = 0, remove = 0; char *filename_buf = NULL; struct lock_file *lock; int out_fd; char buf[1024]; FILE *config_file; if (new_name && !section_name_is_ok(new_name)) { ret = error("invalid section name: %s", new_name); goto out; } if (!config_filename) config_filename = filename_buf = git_pathdup("config"); lock = xcalloc(sizeof(struct lock_file), 1); out_fd = hold_lock_file_for_update(lock, config_filename, 0); if (out_fd < 0) { ret = error("could not lock config file %s", config_filename); goto out; } if (!(config_file = fopen(config_filename, "rb"))) { /* no config file means nothing to rename, no error */ goto unlock_and_out; } while (fgets(buf, sizeof(buf), config_file)) { int i; int length; char *output = buf; for (i = 0; buf[i] && isspace(buf[i]); i++) ; /* do nothing */ if (buf[i] == '[') { /* it's a section */ int offset = section_name_match(&buf[i], old_name); if (offset > 0) { ret++; if (new_name == NULL) { remove = 1; continue; } store.baselen = strlen(new_name); if (!store_write_section(out_fd, new_name)) { ret = write_error(lock->filename); goto out; } /* * We wrote out the new section, with * a newline, now skip the old * section's length */ output += offset + i; if (strlen(output) > 0) { /* * More content means there's * a declaration to put on the * next line; indent with a * tab */ output -= 1; output[0] = '\t'; } } remove = 0; } if (remove) continue; length = strlen(output); if (write_in_full(out_fd, output, length) != length) { ret = write_error(lock->filename); goto out; } } fclose(config_file); unlock_and_out: if (commit_lock_file(lock) < 0) ret = error("could not commit config file %s", config_filename); out: free(filename_buf); return ret; } int git_config_rename_section(const char *old_name, const char *new_name) { return git_config_rename_section_in_file(NULL, old_name, new_name); } /* * Call this to report error for your variable that should not * get a boolean value (i.e. "[my] var" means "true"). */ #undef config_error_nonbool int config_error_nonbool(const char *var) { return error("Missing value for '%s'", var); } int parse_config_key(const char *var, const char *section, const char **subsection, int *subsection_len, const char **key) { int section_len = strlen(section); const char *dot; /* Does it start with "section." ? */ if (prefixcmp(var, section) || var[section_len] != '.') return -1; /* * Find the key; we don't know yet if we have a subsection, but we must * parse backwards from the end, since the subsection may have dots in * it, too. */ dot = strrchr(var, '.'); *key = dot + 1; /* Did we have a subsection at all? */ if (dot == var + section_len) { *subsection = NULL; *subsection_len = 0; } else { *subsection = var + section_len + 1; *subsection_len = dot - *subsection; } return 0; }
Devindik/origin
config.c
C
gpl-2.0
40,138
/*---- license ----*/ /*------------------------------------------------------------------------- Coco.ATG -- Attributed Grammar Compiler Generator Coco/R, Copyright (c) 1990, 2004 Hanspeter Moessenboeck, University of Linz extended by M. Loeberbauer & A. Woess, Univ. of Linz with improvements by Pat Terry, Rhodes University. ported to C by Charles Wang <[email protected]> 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, 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. As an exception, it is allowed to write an extension of Coco/R that is used as a plugin in non-free software. If not otherwise stated, any source code generated by Coco/R (other than Coco/R itself) does not fall under the GNU General Public License. -------------------------------------------------------------------------*/ /*---- enable ----*/ #ifndef COCO_CcsXmlParser_H #define COCO_CcsXmlParser_H #ifndef COCO_ERRORPOOL_H #include "c/ErrorPool.h" #endif #ifndef COCO_CcsXmlScanner_H #include "Scanner.h" #endif /*---- hIncludes ----*/ #ifndef COCO_GLOBALS_H #include "Globals.h" #endif /*---- enable ----*/ EXTC_BEGIN /*---- SynDefines ----*/ #define CcsXmlParser_WEAK_USED /*---- enable ----*/ typedef struct CcsXmlParser_s CcsXmlParser_t; struct CcsXmlParser_s { CcsErrorPool_t errpool; CcsXmlScanner_t scanner; CcsToken_t * t; CcsToken_t * la; int maxT; /*---- members ----*/ CcGlobals_t globals; /* Shortcut pointers */ CcSymbolTable_t * symtab; CcXmlSpecMap_t * xmlspecmap; CcSyntax_t * syntax; /*---- enable ----*/ }; CcsXmlParser_t * CcsXmlParser(CcsXmlParser_t * self, FILE * infp, FILE * errfp); CcsXmlParser_t * CcsXmlParser_ByName(CcsXmlParser_t * self, const char * infn, FILE * errfp); void CcsXmlParser_Destruct(CcsXmlParser_t * self); void CcsXmlParser_Parse(CcsXmlParser_t * self); void CcsXmlParser_SemErr(CcsXmlParser_t * self, const CcsToken_t * token, const char * format, ...); void CcsXmlParser_SemErrT(CcsXmlParser_t * self, const char * format, ...); EXTC_END #endif /* COCO_PARSER_H */
charlesw1234/cocoxml
schemes/cxml/Parser.h
C
gpl-2.0
2,793
import FWCore.ParameterSet.Config as cms maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) ) readFiles = cms.untracked.vstring() secFiles = cms.untracked.vstring() source = cms.Source ("PoolSource",fileNames = readFiles, secondaryFileNames = secFiles) readFiles.extend( [ '/store/mc/Spring14miniaod/QCD_Pt-80to120_MuEnrichedPt5_Tune4C_13TeV_pythia8/MINIAODSIM/PU20bx25_POSTLS170_V5-v1/00000/0A2744F9-FA05-E411-BD0C-00259073E36C.root', '/store/mc/Spring14miniaod/QCD_Pt-80to120_MuEnrichedPt5_Tune4C_13TeV_pythia8/MINIAODSIM/PU20bx25_POSTLS170_V5-v1/00000/0E936434-FD05-E411-81BF-F4CE46B27A1A.root', '/store/mc/Spring14miniaod/QCD_Pt-80to120_MuEnrichedPt5_Tune4C_13TeV_pythia8/MINIAODSIM/PU20bx25_POSTLS170_V5-v1/00000/32E07232-FD05-E411-897C-00259073E522.root', '/store/mc/Spring14miniaod/QCD_Pt-80to120_MuEnrichedPt5_Tune4C_13TeV_pythia8/MINIAODSIM/PU20bx25_POSTLS170_V5-v1/00000/3CE2B535-FB05-E411-919A-20CF307C98DC.root', '/store/mc/Spring14miniaod/QCD_Pt-80to120_MuEnrichedPt5_Tune4C_13TeV_pythia8/MINIAODSIM/PU20bx25_POSTLS170_V5-v1/00000/48093276-FC05-E411-9EEE-001F296564C6.root', '/store/mc/Spring14miniaod/QCD_Pt-80to120_MuEnrichedPt5_Tune4C_13TeV_pythia8/MINIAODSIM/PU20bx25_POSTLS170_V5-v1/00000/50B66FF3-FA05-E411-A937-001F296564C6.root', '/store/mc/Spring14miniaod/QCD_Pt-80to120_MuEnrichedPt5_Tune4C_13TeV_pythia8/MINIAODSIM/PU20bx25_POSTLS170_V5-v1/00000/544B2DF7-FA05-E411-B91F-001F2965F296.root', '/store/mc/Spring14miniaod/QCD_Pt-80to120_MuEnrichedPt5_Tune4C_13TeV_pythia8/MINIAODSIM/PU20bx25_POSTLS170_V5-v1/00000/54DB2FF7-FE05-E411-824B-00259073E522.root', '/store/mc/Spring14miniaod/QCD_Pt-80to120_MuEnrichedPt5_Tune4C_13TeV_pythia8/MINIAODSIM/PU20bx25_POSTLS170_V5-v1/00000/56D1BC32-FD05-E411-A512-20CF3027A5EB.root', '/store/mc/Spring14miniaod/QCD_Pt-80to120_MuEnrichedPt5_Tune4C_13TeV_pythia8/MINIAODSIM/PU20bx25_POSTLS170_V5-v1/00000/5AD70432-FC05-E411-906C-20CF3027A5CD.root', '/store/mc/Spring14miniaod/QCD_Pt-80to120_MuEnrichedPt5_Tune4C_13TeV_pythia8/MINIAODSIM/PU20bx25_POSTLS170_V5-v1/00000/5C4FBFF4-FA05-E411-9767-00259073E36C.root', '/store/mc/Spring14miniaod/QCD_Pt-80to120_MuEnrichedPt5_Tune4C_13TeV_pythia8/MINIAODSIM/PU20bx25_POSTLS170_V5-v1/00000/5CF748F8-FC05-E411-814B-20CF3027A5A2.root', '/store/mc/Spring14miniaod/QCD_Pt-80to120_MuEnrichedPt5_Tune4C_13TeV_pythia8/MINIAODSIM/PU20bx25_POSTLS170_V5-v1/00000/7806E24D-FC05-E411-8922-001F2965F296.root', '/store/mc/Spring14miniaod/QCD_Pt-80to120_MuEnrichedPt5_Tune4C_13TeV_pythia8/MINIAODSIM/PU20bx25_POSTLS170_V5-v1/00000/7C16B231-FD05-E411-8E00-20CF3027A5EB.root', '/store/mc/Spring14miniaod/QCD_Pt-80to120_MuEnrichedPt5_Tune4C_13TeV_pythia8/MINIAODSIM/PU20bx25_POSTLS170_V5-v1/00000/802452C1-FC05-E411-A969-00221983E092.root', '/store/mc/Spring14miniaod/QCD_Pt-80to120_MuEnrichedPt5_Tune4C_13TeV_pythia8/MINIAODSIM/PU20bx25_POSTLS170_V5-v1/00000/8217E3BD-FC05-E411-B8C2-0025907277CE.root', '/store/mc/Spring14miniaod/QCD_Pt-80to120_MuEnrichedPt5_Tune4C_13TeV_pythia8/MINIAODSIM/PU20bx25_POSTLS170_V5-v1/00000/8676BEF4-FA05-E411-B26A-00259073E36C.root', '/store/mc/Spring14miniaod/QCD_Pt-80to120_MuEnrichedPt5_Tune4C_13TeV_pythia8/MINIAODSIM/PU20bx25_POSTLS170_V5-v1/00000/8C1741F3-FA05-E411-B5B5-20CF3027A582.root', '/store/mc/Spring14miniaod/QCD_Pt-80to120_MuEnrichedPt5_Tune4C_13TeV_pythia8/MINIAODSIM/PU20bx25_POSTLS170_V5-v1/00000/8C915AB8-FC05-E411-9EAF-F4CE46B27A1A.root', '/store/mc/Spring14miniaod/QCD_Pt-80to120_MuEnrichedPt5_Tune4C_13TeV_pythia8/MINIAODSIM/PU20bx25_POSTLS170_V5-v1/00000/AA0FCBB0-FC05-E411-898D-00259073E36C.root', '/store/mc/Spring14miniaod/QCD_Pt-80to120_MuEnrichedPt5_Tune4C_13TeV_pythia8/MINIAODSIM/PU20bx25_POSTLS170_V5-v1/00000/B49383BA-FC05-E411-9914-F4CE46B27A1A.root', '/store/mc/Spring14miniaod/QCD_Pt-80to120_MuEnrichedPt5_Tune4C_13TeV_pythia8/MINIAODSIM/PU20bx25_POSTLS170_V5-v1/00000/B6DAEFDD-FB05-E411-9851-20CF3027A5CD.root', '/store/mc/Spring14miniaod/QCD_Pt-80to120_MuEnrichedPt5_Tune4C_13TeV_pythia8/MINIAODSIM/PU20bx25_POSTLS170_V5-v1/00000/C6F5C44F-FD05-E411-B86F-D48564592B02.root', '/store/mc/Spring14miniaod/QCD_Pt-80to120_MuEnrichedPt5_Tune4C_13TeV_pythia8/MINIAODSIM/PU20bx25_POSTLS170_V5-v1/00000/C83B6B6C-FC05-E411-BAFD-D48564599CAA.root', '/store/mc/Spring14miniaod/QCD_Pt-80to120_MuEnrichedPt5_Tune4C_13TeV_pythia8/MINIAODSIM/PU20bx25_POSTLS170_V5-v1/00000/CEF64C64-FD05-E411-A799-001F2965648A.root', '/store/mc/Spring14miniaod/QCD_Pt-80to120_MuEnrichedPt5_Tune4C_13TeV_pythia8/MINIAODSIM/PU20bx25_POSTLS170_V5-v1/00000/D6C305FC-FA05-E411-9AF5-00259073E522.root', '/store/mc/Spring14miniaod/QCD_Pt-80to120_MuEnrichedPt5_Tune4C_13TeV_pythia8/MINIAODSIM/PU20bx25_POSTLS170_V5-v1/00000/DE0FC6A4-FC05-E411-A2F9-00259073E36C.root', '/store/mc/Spring14miniaod/QCD_Pt-80to120_MuEnrichedPt5_Tune4C_13TeV_pythia8/MINIAODSIM/PU20bx25_POSTLS170_V5-v1/00000/E2D5AD33-FD05-E411-868A-D48564594F36.root', '/store/mc/Spring14miniaod/QCD_Pt-80to120_MuEnrichedPt5_Tune4C_13TeV_pythia8/MINIAODSIM/PU20bx25_POSTLS170_V5-v1/00000/E63BCC43-FB05-E411-834E-D48564599CEE.root', '/store/mc/Spring14miniaod/QCD_Pt-80to120_MuEnrichedPt5_Tune4C_13TeV_pythia8/MINIAODSIM/PU20bx25_POSTLS170_V5-v1/00000/EAD01F32-FD05-E411-91E4-20CF3027A5F4.root', '/store/mc/Spring14miniaod/QCD_Pt-80to120_MuEnrichedPt5_Tune4C_13TeV_pythia8/MINIAODSIM/PU20bx25_POSTLS170_V5-v1/00000/F0A18D25-FC05-E411-8DFC-20CF3027A582.root', '/store/mc/Spring14miniaod/QCD_Pt-80to120_MuEnrichedPt5_Tune4C_13TeV_pythia8/MINIAODSIM/PU20bx25_POSTLS170_V5-v1/00000/F0B8E6B6-FA05-E411-9DAE-20CF3027A5CD.root', '/store/mc/Spring14miniaod/QCD_Pt-80to120_MuEnrichedPt5_Tune4C_13TeV_pythia8/MINIAODSIM/PU20bx25_POSTLS170_V5-v1/00000/F23A21C3-FD05-E411-9E29-A4BADB3D00FF.root' ] ); secFiles.extend( [ ] )
pfs/CSA14
python/csa14/QCD_80_120_MuEnriched_pythia8_cfi.py
Python
gpl-2.0
5,943
#ifndef BZS_DB_PROTOCOL_HS_HSCOMMANDEXECUTER_H #define BZS_DB_PROTOCOL_HS_HSCOMMANDEXECUTER_H /*================================================================= Copyright (C) 2013 BizStation Corp All rights reserved. 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 <bzs/db/engine/mysql/dbManager.h> #include <bzs/db/protocol/ICommandExecuter.h> #include <bzs/env/crosscompile.h> namespace bzs { namespace db { namespace protocol { namespace hs { #define HS_OP_READ 'R' #define HS_OP_OPEN 'P' #define HS_OP_AUTH 'A' #define HS_OP_INSERT '+' #define HS_OP_DELETE 'D' #define HS_OP_UPDATE 'U' #define HS_OP_UPDATE_INC '+' + 0xff #define HS_OP_UPDATE_DEC '-' #define HS_OP_QUIT 'Q' #define HS_LG_EQUAL '=' #define HS_LG_GREATER '>' #define HS_LG_LESS '<' #define HS_LG_NOTEQUAL '<' + 0xfe //<> #define HS_LG_GREATEROREQUAL '>' + 0xff //>= #define HS_LG_LESSOREQUAL '<' + 0xff //<= #define DEBNAME_SIZE 64 #define TABELNAME_SIZE 64 #define INDEXNAME_SIZE 64 #define HS_OP_RESULTBUFSIZE 64000 //----------------------------------------------------------------------- // result buffer //----------------------------------------------------------------------- class resultBuffer { char* m_ptr; char* m_cur; public: resultBuffer(char* ptr) : m_ptr(ptr), m_cur(m_ptr) {} void append(const char* ptr, size_t size) { const char* p = ptr; const char* end = ptr + size; for (; p < end; ++p) { if ((*p >= 0x00) && (*p <= 0x10)) { *m_cur = 0x01; *(++m_cur) = *p + 0x40; } else *m_cur = *p; ++m_cur; } } void append(const char* ptr) { const char* p = ptr; while (*p) { *m_cur = *p; ++p; ++m_cur; } } void append(int v) { char tmp[50]; sprintf_s(tmp, 50, "%d", v); append(tmp); } size_t size() { *m_ptr = 0x00; return m_cur - m_ptr; } const char* c_str() { return m_ptr; } }; //----------------------------------------------------------------------- // request //----------------------------------------------------------------------- struct request { short op; int handle; struct result { result() : limit(1), offset(0), returnBeforeValue(0){}; int limit; int offset; bool returnBeforeValue; } result; struct db { char name[DEBNAME_SIZE]; } db; struct table { table() : openMode(0) {} char name[TABELNAME_SIZE]; short openMode; struct key { key() : logical(0){}; char name[INDEXNAME_SIZE]; std::vector<std::string> values; short logical; } key; std::string fields; std::vector<std::string> values; struct in { in() : keypart(0) {} uint keypart; std::vector<std::string> values; } in; struct filter { filter() : type(0), logical(0), col(0) {} char type; short logical; short col; std::string value; }; typedef std::vector<filter> filters_type; filters_type filters; } table; request() : op(HS_OP_READ), handle(0) {} ha_rkey_function seekFlag(); bool naviForward(); bool naviSame(); }; //----------------------------------------------------------------------- // class dbExecuter //----------------------------------------------------------------------- /** Current, no support auth command . */ typedef int (*changeFunc)(request& req, engine::mysql::table* tb, int type); class dbExecuter : public engine::mysql::dbManager { void doRecordOperation(request& req, engine::mysql::table* tb, resultBuffer& buf, changeFunc func); inline int readAfter(request& req, engine::mysql::table* tb, resultBuffer& buf, changeFunc func); public: dbExecuter(netsvc::server::IAppModule* mod); int commandExec(std::vector<request>& requests, netsvc::server::netWriter* nw); int errorCode(int ha_error) { return 0; }; }; //----------------------------------------------------------------------- // class commandExecuter //----------------------------------------------------------------------- class commandExecuter : public ICommandExecuter, public engine::mysql::igetDatabases { boost::shared_ptr<dbExecuter> m_dbExec; mutable std::vector<request> m_requests; public: commandExecuter(netsvc::server::IAppModule* mod); ~commandExecuter(); size_t perseRequestEnd(const char* p, size_t size, bool& comp) const; size_t getAcceptMessage(char* message, size_t size) { return 0; }; bool parse(const char* p, size_t size); int execute(netsvc::server::netWriter* nw) { return m_dbExec->commandExec(m_requests, nw); } void cleanup(){}; bool isShutDown() { return m_dbExec->isShutDown(); } const engine::mysql::databases& dbs() const { return m_dbExec->dbs(); } boost::mutex& mutex() { return m_dbExec->mutex(); } }; } // namespace hs } // namespace protocol } // namespace db } // namespace bzs #endif // BZS_DB_PROTOCOL_HS_HSCOMMANDEXECUTER_H
bizstation/transactd
source/bzs/db/protocol/hs/hsCommandExecuter.h
C
gpl-2.0
6,401
/* * Copyright (C) 2014-2017 StormCore * * 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, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Boss_Twinemperors SD%Complete: 95 SDComment: SDCategory: Temple of Ahn'Qiraj EndScriptData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "temple_of_ahnqiraj.h" #include "WorldPacket.h" #include "Item.h" #include "Spell.h" enum Spells { SPELL_HEAL_BROTHER = 7393, SPELL_TWIN_TELEPORT = 800, // CTRA watches for this spell to start its teleport timer SPELL_TWIN_TELEPORT_VISUAL = 26638, // visual SPELL_EXPLODEBUG = 804, SPELL_MUTATE_BUG = 802, SPELL_BERSERK = 26662, SPELL_UPPERCUT = 26007, SPELL_UNBALANCING_STRIKE = 26613, SPELL_SHADOWBOLT = 26006, SPELL_BLIZZARD = 26607, SPELL_ARCANEBURST = 568, }; enum Sound { SOUND_VL_AGGRO = 8657, //8657 - Aggro - To Late SOUND_VL_KILL = 8658, //8658 - Kill - You will not SOUND_VL_DEATH = 8659, //8659 - Death SOUND_VN_DEATH = 8660, //8660 - Death - Feel SOUND_VN_AGGRO = 8661, //8661 - Aggro - Let none SOUND_VN_KILL = 8662, //8661 - Kill - your fate }; enum Misc { PULL_RANGE = 50, ABUSE_BUG_RANGE = 20, VEKLOR_DIST = 20, // VL will not come to melee when attacking TELEPORTTIME = 30000 }; struct boss_twinemperorsAI : public ScriptedAI { boss_twinemperorsAI(Creature* creature): ScriptedAI(creature) { Initialize(); instance = creature->GetInstanceScript(); } void Initialize() { Heal_Timer = 0; // first heal immediately when they get close together Teleport_Timer = TELEPORTTIME; AfterTeleport = false; tspellcast = false; AfterTeleportTimer = 0; Abuse_Bug_Timer = urand(10000, 17000); BugsTimer = 2000; DontYellWhenDead = false; EnrageTimer = 15 * 60000; } InstanceScript* instance; uint32 Heal_Timer; uint32 Teleport_Timer; bool AfterTeleport; uint32 AfterTeleportTimer; bool DontYellWhenDead; uint32 Abuse_Bug_Timer, BugsTimer; bool tspellcast; uint32 EnrageTimer; virtual bool IAmVeklor() = 0; virtual void Reset() override = 0; virtual void CastSpellOnBug(Creature* target) = 0; void TwinReset() { Initialize(); me->ClearUnitState(UNIT_STATE_STUNNED); } Creature* GetOtherBoss() { return ObjectAccessor::GetCreature(*me, instance->GetGuidData(IAmVeklor() ? DATA_VEKNILASH : DATA_VEKLOR)); } void DamageTaken(Unit* /*done_by*/, uint32 &damage) override { Unit* pOtherBoss = GetOtherBoss(); if (pOtherBoss) { float dPercent = ((float)damage) / ((float)me->GetMaxHealth()); int odmg = (int)(dPercent * ((float)pOtherBoss->GetMaxHealth())); int ohealth = pOtherBoss->GetHealth()-odmg; pOtherBoss->SetHealth(ohealth > 0 ? ohealth : 0); if (ohealth <= 0) { pOtherBoss->setDeathState(JUST_DIED); pOtherBoss->SetFlag(OBJECT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE); } } } void JustDied(Unit* /*killer*/) override { Creature* pOtherBoss = GetOtherBoss(); if (pOtherBoss) { pOtherBoss->SetHealth(0); pOtherBoss->setDeathState(JUST_DIED); pOtherBoss->SetFlag(OBJECT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE); ENSURE_AI(boss_twinemperorsAI, pOtherBoss->AI())->DontYellWhenDead = true; } if (!DontYellWhenDead) // I hope AI is not threaded DoPlaySoundToSet(me, IAmVeklor() ? SOUND_VL_DEATH : SOUND_VN_DEATH); } void KilledUnit(Unit* /*victim*/) override { DoPlaySoundToSet(me, IAmVeklor() ? SOUND_VL_KILL : SOUND_VN_KILL); } void EnterCombat(Unit* who) override { DoZoneInCombat(); Creature* pOtherBoss = GetOtherBoss(); if (pOtherBoss) { /// @todo we should activate the other boss location so he can start attackning even if nobody // is near I dont know how to do that if (!pOtherBoss->IsInCombat()) { ScriptedAI* otherAI = ENSURE_AI(ScriptedAI, pOtherBoss->AI()); DoPlaySoundToSet(me, IAmVeklor() ? SOUND_VL_AGGRO : SOUND_VN_AGGRO); otherAI->AttackStart(who); otherAI->DoZoneInCombat(); } } } void SpellHit(Unit* caster, const SpellInfo* entry) override { if (caster == me) return; Creature* pOtherBoss = GetOtherBoss(); if (entry->Id != SPELL_HEAL_BROTHER || !pOtherBoss) return; // add health so we keep same percentage for both brothers uint32 mytotal = me->GetMaxHealth(), histotal = pOtherBoss->GetMaxHealth(); float mult = ((float)mytotal) / ((float)histotal); if (mult < 1) mult = 1.0f/mult; #define HEAL_BROTHER_AMOUNT 30000.0f uint32 largerAmount = (uint32)((HEAL_BROTHER_AMOUNT * mult) - HEAL_BROTHER_AMOUNT); if (mytotal > histotal) { uint32 h = me->GetHealth()+largerAmount; me->SetHealth(std::min(mytotal, h)); } else { uint32 h = pOtherBoss->GetHealth()+largerAmount; pOtherBoss->SetHealth(std::min(histotal, h)); } } void TryHealBrother(uint32 diff) { if (IAmVeklor()) // this spell heals caster and the other brother so let VN cast it return; if (Heal_Timer <= diff) { Unit* pOtherBoss = GetOtherBoss(); if (pOtherBoss && pOtherBoss->IsWithinDist(me, 60)) { DoCast(pOtherBoss, SPELL_HEAL_BROTHER); Heal_Timer = 1000; } } else Heal_Timer -= diff; } void TeleportToMyBrother() { Teleport_Timer = TELEPORTTIME; if (IAmVeklor()) return; // mechanics handled by veknilash so they teleport exactly at the same time and to correct coordinates Creature* pOtherBoss = GetOtherBoss(); if (pOtherBoss) { //me->MonsterYell("Teleporting ...", LANG_UNIVERSAL, 0); Position thisPos; thisPos.Relocate(me); Position otherPos; otherPos.Relocate(pOtherBoss); pOtherBoss->SetPosition(thisPos); me->SetPosition(otherPos); SetAfterTeleport(); ENSURE_AI(boss_twinemperorsAI, pOtherBoss->AI())->SetAfterTeleport(); } } void SetAfterTeleport() { me->InterruptNonMeleeSpells(false); DoStopAttack(); DoResetThreat(); DoCast(me, SPELL_TWIN_TELEPORT_VISUAL); me->AddUnitState(UNIT_STATE_STUNNED); AfterTeleport = true; AfterTeleportTimer = 2000; tspellcast = false; } bool TryActivateAfterTTelep(uint32 diff) { if (AfterTeleport) { if (!tspellcast) { me->ClearUnitState(UNIT_STATE_STUNNED); DoCast(me, SPELL_TWIN_TELEPORT); me->AddUnitState(UNIT_STATE_STUNNED); } tspellcast = true; if (AfterTeleportTimer <= diff) { AfterTeleport = false; me->ClearUnitState(UNIT_STATE_STUNNED); if (Unit* nearu = me->SelectNearestTarget(100)) { //DoYell(nearu->GetName(), LANG_UNIVERSAL, 0); AttackStart(nearu); me->AddThreat(nearu, 10000); } return true; } else { AfterTeleportTimer -= diff; // update important timers which would otherwise get skipped if (EnrageTimer > diff) EnrageTimer -= diff; else EnrageTimer = 0; if (Teleport_Timer > diff) Teleport_Timer -= diff; else Teleport_Timer = 0; return false; } } else { return true; } } void MoveInLineOfSight(Unit* who) override { if (!who || me->GetVictim()) return; if (me->CanCreatureAttack(who)) { float attackRadius = me->GetAttackDistance(who); if (attackRadius < PULL_RANGE) attackRadius = PULL_RANGE; if (me->IsWithinDistInMap(who, attackRadius) && me->GetDistanceZ(who) <= /*CREATURE_Z_ATTACK_RANGE*/7 /*there are stairs*/) { //if (who->HasStealthAura()) // who->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH); AttackStart(who); } } } Creature* RespawnNearbyBugsAndGetOne() { std::list<Creature*> lUnitList; me->GetCreatureListWithEntryInGrid(lUnitList, 15316, 150.0f); me->GetCreatureListWithEntryInGrid(lUnitList, 15317, 150.0f); if (lUnitList.empty()) return NULL; Creature* nearb = NULL; for (std::list<Creature*>::const_iterator iter = lUnitList.begin(); iter != lUnitList.end(); ++iter) { Creature* c = *iter; if (c) { if (c->isDead()) { c->Respawn(); c->setFaction(7); c->RemoveAllAuras(); } if (c->IsWithinDistInMap(me, ABUSE_BUG_RANGE)) { if (!nearb || (rand32() % 4) == 0) nearb = c; } } } return nearb; } void HandleBugs(uint32 diff) { if (BugsTimer < diff || Abuse_Bug_Timer <= diff) { Creature* c = RespawnNearbyBugsAndGetOne(); if (Abuse_Bug_Timer <= diff) { if (c) { CastSpellOnBug(c); Abuse_Bug_Timer = urand(10000, 17000); } else { Abuse_Bug_Timer = 1000; } } else { Abuse_Bug_Timer -= diff; } BugsTimer = 2000; } else { BugsTimer -= diff; Abuse_Bug_Timer -= diff; } } void CheckEnrage(uint32 diff) { if (EnrageTimer <= diff) { if (!me->IsNonMeleeSpellCast(true)) { DoCast(me, SPELL_BERSERK); EnrageTimer = 60*60000; } else EnrageTimer = 0; } else EnrageTimer-=diff; } }; class boss_veknilash : public CreatureScript { public: boss_veknilash() : CreatureScript("boss_veknilash") { } CreatureAI* GetAI(Creature* creature) const override { return GetInstanceAI<boss_veknilashAI>(creature); } struct boss_veknilashAI : public boss_twinemperorsAI { bool IAmVeklor() override {return false;} boss_veknilashAI(Creature* creature) : boss_twinemperorsAI(creature) { Initialize(); } void Initialize() { UpperCut_Timer = urand(14000, 29000); UnbalancingStrike_Timer = urand(8000, 18000); Scarabs_Timer = urand(7000, 14000); } uint32 UpperCut_Timer; uint32 UnbalancingStrike_Timer; uint32 Scarabs_Timer; void Reset() override { TwinReset(); Initialize(); //Added. Can be removed if its included in DB. me->ApplySpellImmune(0, IMMUNITY_DAMAGE, SPELL_SCHOOL_MASK_MAGIC, true); } void CastSpellOnBug(Creature* target) override { target->setFaction(14); target->AI()->AttackStart(me->getThreatManager().getHostilTarget()); target->AddAura(SPELL_MUTATE_BUG, target); target->SetFullHealth(); } void UpdateAI(uint32 diff) override { //Return since we have no target if (!UpdateVictim()) return; if (!TryActivateAfterTTelep(diff)) return; //UnbalancingStrike_Timer if (UnbalancingStrike_Timer <= diff) { DoCastVictim(SPELL_UNBALANCING_STRIKE); UnbalancingStrike_Timer = 8000 + rand32() % 12000; } else UnbalancingStrike_Timer -= diff; if (UpperCut_Timer <= diff) { Unit* randomMelee = SelectTarget(SELECT_TARGET_RANDOM, 0, NOMINAL_MELEE_RANGE, true); if (randomMelee) DoCast(randomMelee, SPELL_UPPERCUT); UpperCut_Timer = 15000 + rand32() % 15000; } else UpperCut_Timer -= diff; HandleBugs(diff); //Heal brother when 60yrds close TryHealBrother(diff); //Teleporting to brother if (Teleport_Timer <= diff) { TeleportToMyBrother(); } else Teleport_Timer -= diff; CheckEnrage(diff); DoMeleeAttackIfReady(); } }; }; class boss_veklor : public CreatureScript { public: boss_veklor() : CreatureScript("boss_veklor") { } CreatureAI* GetAI(Creature* creature) const override { return GetInstanceAI<boss_veklorAI>(creature); } struct boss_veklorAI : public boss_twinemperorsAI { bool IAmVeklor() override {return true;} boss_veklorAI(Creature* creature) : boss_twinemperorsAI(creature) { Initialize(); } void Initialize() { ShadowBolt_Timer = 0; Blizzard_Timer = urand(15000, 20000); ArcaneBurst_Timer = 1000; Scorpions_Timer = urand(7000, 14000); } uint32 ShadowBolt_Timer; uint32 Blizzard_Timer; uint32 ArcaneBurst_Timer; uint32 Scorpions_Timer; void Reset() override { TwinReset(); Initialize(); //Added. Can be removed if its included in DB. me->ApplySpellImmune(0, IMMUNITY_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, true); } void CastSpellOnBug(Creature* target) override { target->setFaction(14); target->AddAura(SPELL_EXPLODEBUG, target); target->SetFullHealth(); } void UpdateAI(uint32 diff) override { //Return since we have no target if (!UpdateVictim()) return; // reset arcane burst after teleport - we need to do this because // when VL jumps to VN's location there will be a warrior who will get only 2s to run away // which is almost impossible if (AfterTeleport) ArcaneBurst_Timer = 5000; if (!TryActivateAfterTTelep(diff)) return; //ShadowBolt_Timer if (ShadowBolt_Timer <= diff) { if (!me->IsWithinDist(me->GetVictim(), 45.0f)) me->GetMotionMaster()->MoveChase(me->GetVictim(), VEKLOR_DIST, 0); else DoCastVictim(SPELL_SHADOWBOLT); ShadowBolt_Timer = 2000; } else ShadowBolt_Timer -= diff; //Blizzard_Timer if (Blizzard_Timer <= diff) { Unit* target = NULL; target = SelectTarget(SELECT_TARGET_RANDOM, 0, 45, true); if (target) DoCast(target, SPELL_BLIZZARD); Blizzard_Timer = 15000 + rand32() % 15000; } else Blizzard_Timer -= diff; if (ArcaneBurst_Timer <= diff) { if (Unit* mvic = SelectTarget(SELECT_TARGET_NEAREST, 0, NOMINAL_MELEE_RANGE, true)) { DoCast(mvic, SPELL_ARCANEBURST); ArcaneBurst_Timer = 5000; } } else ArcaneBurst_Timer -= diff; HandleBugs(diff); //Heal brother when 60yrds close TryHealBrother(diff); //Teleporting to brother if (Teleport_Timer <= diff) { TeleportToMyBrother(); } else Teleport_Timer -= diff; CheckEnrage(diff); //VL doesn't melee //DoMeleeAttackIfReady(); } void AttackStart(Unit* who) override { if (!who) return; if (who->isTargetableForAttack()) { // VL doesn't melee if (me->Attack(who, false)) { me->GetMotionMaster()->MoveChase(who, VEKLOR_DIST, 0); me->AddThreat(who, 0.0f); } } } }; }; void AddSC_boss_twinemperors() { new boss_veknilash(); new boss_veklor(); }
Ragebones/StormCore
src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_twinemperors.cpp
C++
gpl-2.0
18,489
/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef SCI_ENGINE_SELECTOR_H #define SCI_ENGINE_SELECTOR_H #include "common/scummsys.h" #include "sci/engine/vm_types.h" // for reg_t #include "sci/engine/vm.h" namespace Sci { /** Contains selector IDs for a few selected selectors */ struct SelectorCache { SelectorCache() { memset(this, 0, sizeof(*this)); } // Statically defined selectors, (almost the) same in all SCI versions Selector _info_; ///< Removed in SCI3 Selector y; Selector x; Selector view, loop, cel; ///< Description of a specific image Selector underBits; ///< Used by the graphics subroutines to store backupped BG pic data Selector nsTop, nsLeft, nsBottom, nsRight; ///< View boundaries ('now seen') Selector lsTop, lsLeft, lsBottom, lsRight; ///< Used by Animate() subfunctions and scroll list controls Selector signal; ///< Used by Animate() to control a view's behavior Selector illegalBits; ///< Used by CanBeHere Selector brTop, brLeft, brBottom, brRight; ///< Bounding Rectangle // name, key, time Selector text; ///< Used by controls Selector elements; ///< Used by SetSynonyms() // color, back Selector mode; ///< Used by text controls (-> DrawControl()) // style Selector state, font, type;///< Used by controls // window Selector cursor; ///< Used by EditControl Selector max; ///< Used by EditControl, removed in SCI3 Selector mark; //< Used by list controls (script internal, is needed by us for the QfG import rooms) Selector sort; //< Used by list controls (script internal, is needed by us for QfG3 import room) // who Selector message; ///< Used by GetEvent // edit Selector play; ///< Play function (first function to be called) Selector number; Selector handle; ///< Replaced by nodePtr in SCI1+ Selector nodePtr; ///< Replaces handle in SCI1+ Selector client; ///< The object that wants to be moved Selector dx, dy; ///< Deltas Selector b_movCnt, b_i1, b_i2, b_di, b_xAxis, b_incr; ///< Various Bresenham vars Selector xStep, yStep; ///< BR adjustments Selector xLast, yLast; ///< BR last position of client Selector moveSpeed; ///< Used for DoBresen Selector canBeHere; ///< Funcselector: Checks for movement validity in SCI0 Selector heading, mover; ///< Used in DoAvoider Selector doit; ///< Called (!) by the Animate() system call Selector isBlocked, looper; ///< Used in DoAvoider Selector priority; Selector modifiers; ///< Used by GetEvent Selector replay; ///< Replay function // setPri, at, next, done, width Selector wordFail, syntaxFail; ///< Used by Parse() // semanticFail, pragmaFail // said Selector claimed; ///< Used generally by the event mechanism // value, save, restore, title, button, icon, draw Selector delete_; ///< Called by Animate() to dispose a view object Selector z; // SCI1+ static selectors Selector parseLang; Selector printLang; ///< Used for i18n Selector subtitleLang; Selector size; Selector points; ///< Used by AvoidPath() Selector palette; ///< Used by the SCI0-SCI1.1 animate code, unused in SCI2-SCI2.1, removed in SCI3 Selector dataInc; ///< Used to sync music with animations, removed in SCI3 // handle (in SCI1) Selector min; ///< SMPTE time format Selector sec; Selector frame; Selector vol; Selector pri; // perform Selector moveDone; ///< used for DoBresen // SCI1 selectors which have been moved a bit in SCI1.1, but otherwise static Selector cantBeHere; ///< Checks for movement avoidance in SCI1+. Replaces canBeHere Selector topString; ///< SCI1 scroll lists use this instead of lsTop. Removed in SCI3 Selector flags; // SCI1+ audio sync related selectors, not static. They're used for lip syncing in // CD talkie games Selector syncCue; ///< Used by DoSync() Selector syncTime; // SCI1.1 specific selectors Selector scaleSignal; //< Used by kAnimate() for cel scaling (SCI1.1+) Selector scaleX, scaleY; ///< SCI1.1 view scaling Selector maxScale; ///< SCI1.1 view scaling, limit for cel, when using global scaling Selector vanishingX; ///< SCI1.1 view scaling, used by global scaling Selector vanishingY; ///< SCI1.1 view scaling, used by global scaling // Used for auto detection purposes Selector overlay; ///< Used to determine if a game is using old gfx functions or not // SCI1.1 Mac icon bar selectors Selector iconIndex; ///< Used to index icon bar objects Selector select; #ifdef ENABLE_SCI32 Selector data; // Used by Array()/String() Selector picture; // Used to hold the picture ID for SCI32 pictures Selector plane; Selector top; Selector left; Selector bottom; Selector right; Selector resX; Selector resY; Selector fore; Selector back; Selector dimmed; Selector fixPriority; Selector mirrored; Selector useInsetRect; Selector inTop, inLeft, inBottom, inRight; #endif }; /** * Map a selector name to a selector id. Shortcut for accessing the selector cache. */ #define SELECTOR(_slc_) (g_sci->getKernel()->_selectorCache._slc_) /** * Retrieves a selector from an object. * @param segMan the segment mananger * @param _obj_ the address of the object which the selector should be read from * @param _slc_ the selector to refad * @return the selector value as a reg_t * This macro halts on error. 'selector' must be a selector name registered in vm.h's * SelectorCache and mapped in script.cpp. */ reg_t readSelector(SegManager *segMan, reg_t object, Selector selectorId); #define readSelectorValue(segMan, _obj_, _slc_) (readSelector(segMan, _obj_, _slc_).offset) /** * Writes a selector value to an object. * @param segMan the segment mananger * @param _obj_ the address of the object which the selector should be written to * @param _slc_ the selector to read * @param _val_ the value to write * This macro halts on error. 'selector' must be a selector name registered in vm.h's * SelectorCache and mapped in script.cpp. */ void writeSelector(SegManager *segMan, reg_t object, Selector selectorId, reg_t value); #define writeSelectorValue(segMan, _obj_, _slc_, _val_) writeSelector(segMan, _obj_, _slc_, make_reg(0, _val_)) /** * Invokes a selector from an object. */ void invokeSelector(EngineState *s, reg_t object, int selectorId, int k_argc, StackPtr k_argp, int argc = 0, const reg_t *argv = 0); } // End of namespace Sci #endif // SCI_ENGINE_KERNEL_H
chrisws/scummvm
engines/sci/engine/selector.h
C
gpl-2.0
7,219
// This file is autogenerated by hidl-gen // then manualy edited for retrocompatiblity // Source: [email protected] // Root: android.hardware:hardware/interfaces #ifndef HIDL_GENERATED_ANDROID_HARDWARE_AUDIO_COMMON_V4_0_EXPORTED_CONSTANTS_H_ #define HIDL_GENERATED_ANDROID_HARDWARE_AUDIO_COMMON_V4_0_EXPORTED_CONSTANTS_H_ #ifdef __cplusplus extern "C" { #endif enum { AUDIO_IO_HANDLE_NONE = 0, AUDIO_MODULE_HANDLE_NONE = 0, AUDIO_PORT_HANDLE_NONE = 0, AUDIO_PATCH_HANDLE_NONE = 0, }; typedef enum { AUDIO_STREAM_DEFAULT = -1, // (-1) AUDIO_STREAM_MIN = 0, AUDIO_STREAM_VOICE_CALL = 0, AUDIO_STREAM_SYSTEM = 1, AUDIO_STREAM_RING = 2, AUDIO_STREAM_MUSIC = 3, AUDIO_STREAM_ALARM = 4, AUDIO_STREAM_NOTIFICATION = 5, AUDIO_STREAM_BLUETOOTH_SCO = 6, AUDIO_STREAM_ENFORCED_AUDIBLE = 7, AUDIO_STREAM_DTMF = 8, AUDIO_STREAM_TTS = 9, AUDIO_STREAM_ACCESSIBILITY = 10, #ifndef AUDIO_NO_SYSTEM_DECLARATIONS /** For dynamic policy output mixes. Only used by the audio policy */ AUDIO_STREAM_REROUTING = 11, /** For audio flinger tracks volume. Only used by the audioflinger */ AUDIO_STREAM_PATCH = 12, #endif // AUDIO_NO_SYSTEM_DECLARATIONS } audio_stream_type_t; typedef enum { AUDIO_SOURCE_DEFAULT = 0, AUDIO_SOURCE_MIC = 1, AUDIO_SOURCE_VOICE_UPLINK = 2, AUDIO_SOURCE_VOICE_DOWNLINK = 3, AUDIO_SOURCE_VOICE_CALL = 4, AUDIO_SOURCE_CAMCORDER = 5, AUDIO_SOURCE_VOICE_RECOGNITION = 6, AUDIO_SOURCE_VOICE_COMMUNICATION = 7, AUDIO_SOURCE_REMOTE_SUBMIX = 8, AUDIO_SOURCE_UNPROCESSED = 9, AUDIO_SOURCE_FM_TUNER = 1998, #ifndef AUDIO_NO_SYSTEM_DECLARATIONS /** * A low-priority, preemptible audio source for for background software * hotword detection. Same tuning as VOICE_RECOGNITION. * Used only internally by the framework. */ AUDIO_SOURCE_HOTWORD = 1999, #endif // AUDIO_NO_SYSTEM_DECLARATIONS } audio_source_t; typedef enum { AUDIO_SESSION_OUTPUT_STAGE = -1, // (-1) AUDIO_SESSION_OUTPUT_MIX = 0, AUDIO_SESSION_ALLOCATE = 0, AUDIO_SESSION_NONE = 0, } audio_session_t; typedef enum { AUDIO_FORMAT_INVALID = 0xFFFFFFFFu, AUDIO_FORMAT_DEFAULT = 0, AUDIO_FORMAT_PCM = 0x00000000u, AUDIO_FORMAT_MP3 = 0x01000000u, AUDIO_FORMAT_AMR_NB = 0x02000000u, AUDIO_FORMAT_AMR_WB = 0x03000000u, AUDIO_FORMAT_AAC = 0x04000000u, AUDIO_FORMAT_HE_AAC_V1 = 0x05000000u, AUDIO_FORMAT_HE_AAC_V2 = 0x06000000u, AUDIO_FORMAT_VORBIS = 0x07000000u, AUDIO_FORMAT_OPUS = 0x08000000u, AUDIO_FORMAT_AC3 = 0x09000000u, AUDIO_FORMAT_E_AC3 = 0x0A000000u, AUDIO_FORMAT_DTS = 0x0B000000u, AUDIO_FORMAT_DTS_HD = 0x0C000000u, AUDIO_FORMAT_IEC61937 = 0x0D000000u, AUDIO_FORMAT_DOLBY_TRUEHD = 0x0E000000u, AUDIO_FORMAT_EVRC = 0x10000000u, AUDIO_FORMAT_EVRCB = 0x11000000u, AUDIO_FORMAT_EVRCWB = 0x12000000u, AUDIO_FORMAT_EVRCNW = 0x13000000u, AUDIO_FORMAT_AAC_ADIF = 0x14000000u, AUDIO_FORMAT_WMA = 0x15000000u, AUDIO_FORMAT_WMA_PRO = 0x16000000u, AUDIO_FORMAT_AMR_WB_PLUS = 0x17000000u, AUDIO_FORMAT_MP2 = 0x18000000u, AUDIO_FORMAT_QCELP = 0x19000000u, AUDIO_FORMAT_DSD = 0x1A000000u, AUDIO_FORMAT_FLAC = 0x1B000000u, AUDIO_FORMAT_ALAC = 0x1C000000u, AUDIO_FORMAT_APE = 0x1D000000u, AUDIO_FORMAT_AAC_ADTS = 0x1E000000u, AUDIO_FORMAT_SBC = 0x1F000000u, AUDIO_FORMAT_APTX = 0x20000000u, AUDIO_FORMAT_APTX_HD = 0x21000000u, AUDIO_FORMAT_AC4 = 0x22000000u, AUDIO_FORMAT_LDAC = 0x23000000u, AUDIO_FORMAT_MAT = 0x24000000u, AUDIO_FORMAT_MAIN_MASK = 0xFF000000u, AUDIO_FORMAT_SUB_MASK = 0x00FFFFFFu, /* Subformats */ AUDIO_FORMAT_PCM_SUB_16_BIT = 0x1u, AUDIO_FORMAT_PCM_SUB_8_BIT = 0x2u, AUDIO_FORMAT_PCM_SUB_32_BIT = 0x3u, AUDIO_FORMAT_PCM_SUB_8_24_BIT = 0x4u, AUDIO_FORMAT_PCM_SUB_FLOAT = 0x5u, AUDIO_FORMAT_PCM_SUB_24_BIT_PACKED = 0x6u, AUDIO_FORMAT_MP3_SUB_NONE = 0x0u, AUDIO_FORMAT_AMR_SUB_NONE = 0x0u, AUDIO_FORMAT_AAC_SUB_MAIN = 0x1u, AUDIO_FORMAT_AAC_SUB_LC = 0x2u, AUDIO_FORMAT_AAC_SUB_SSR = 0x4u, AUDIO_FORMAT_AAC_SUB_LTP = 0x8u, AUDIO_FORMAT_AAC_SUB_HE_V1 = 0x10u, AUDIO_FORMAT_AAC_SUB_SCALABLE = 0x20u, AUDIO_FORMAT_AAC_SUB_ERLC = 0x40u, AUDIO_FORMAT_AAC_SUB_LD = 0x80u, AUDIO_FORMAT_AAC_SUB_HE_V2 = 0x100u, AUDIO_FORMAT_AAC_SUB_ELD = 0x200u, AUDIO_FORMAT_AAC_SUB_XHE = 0x300u, AUDIO_FORMAT_VORBIS_SUB_NONE = 0x0u, AUDIO_FORMAT_E_AC3_SUB_JOC = 0x1u, AUDIO_FORMAT_MAT_SUB_1_0 = 0x1u, AUDIO_FORMAT_MAT_SUB_2_0 = 0x2u, AUDIO_FORMAT_MAT_SUB_2_1 = 0x3u, /* Aliases */ AUDIO_FORMAT_PCM_16_BIT = 0x1u, // (PCM | PCM_SUB_16_BIT) AUDIO_FORMAT_PCM_8_BIT = 0x2u, // (PCM | PCM_SUB_8_BIT) AUDIO_FORMAT_PCM_32_BIT = 0x3u, // (PCM | PCM_SUB_32_BIT) AUDIO_FORMAT_PCM_8_24_BIT = 0x4u, // (PCM | PCM_SUB_8_24_BIT) AUDIO_FORMAT_PCM_FLOAT = 0x5u, // (PCM | PCM_SUB_FLOAT) AUDIO_FORMAT_PCM_24_BIT_PACKED = 0x6u, // (PCM | PCM_SUB_24_BIT_PACKED) AUDIO_FORMAT_AAC_MAIN = 0x4000001u, // (AAC | AAC_SUB_MAIN) AUDIO_FORMAT_AAC_LC = 0x4000002u, // (AAC | AAC_SUB_LC) AUDIO_FORMAT_AAC_SSR = 0x4000004u, // (AAC | AAC_SUB_SSR) AUDIO_FORMAT_AAC_LTP = 0x4000008u, // (AAC | AAC_SUB_LTP) AUDIO_FORMAT_AAC_HE_V1 = 0x4000010u, // (AAC | AAC_SUB_HE_V1) AUDIO_FORMAT_AAC_SCALABLE = 0x4000020u, // (AAC | AAC_SUB_SCALABLE) AUDIO_FORMAT_AAC_ERLC = 0x4000040u, // (AAC | AAC_SUB_ERLC) AUDIO_FORMAT_AAC_LD = 0x4000080u, // (AAC | AAC_SUB_LD) AUDIO_FORMAT_AAC_HE_V2 = 0x4000100u, // (AAC | AAC_SUB_HE_V2) AUDIO_FORMAT_AAC_ELD = 0x4000200u, // (AAC | AAC_SUB_ELD) AUDIO_FORMAT_AAC_XHE = 0x4000300u, // (AAC | AAC_SUB_XHE) AUDIO_FORMAT_AAC_ADTS_MAIN = 0x1e000001u, // (AAC_ADTS | AAC_SUB_MAIN) AUDIO_FORMAT_AAC_ADTS_LC = 0x1e000002u, // (AAC_ADTS | AAC_SUB_LC) AUDIO_FORMAT_AAC_ADTS_SSR = 0x1e000004u, // (AAC_ADTS | AAC_SUB_SSR) AUDIO_FORMAT_AAC_ADTS_LTP = 0x1e000008u, // (AAC_ADTS | AAC_SUB_LTP) AUDIO_FORMAT_AAC_ADTS_HE_V1 = 0x1e000010u, // (AAC_ADTS | AAC_SUB_HE_V1) AUDIO_FORMAT_AAC_ADTS_SCALABLE = 0x1e000020u, // (AAC_ADTS | AAC_SUB_SCALABLE) AUDIO_FORMAT_AAC_ADTS_ERLC = 0x1e000040u, // (AAC_ADTS | AAC_SUB_ERLC) AUDIO_FORMAT_AAC_ADTS_LD = 0x1e000080u, // (AAC_ADTS | AAC_SUB_LD) AUDIO_FORMAT_AAC_ADTS_HE_V2 = 0x1e000100u, // (AAC_ADTS | AAC_SUB_HE_V2) AUDIO_FORMAT_AAC_ADTS_ELD = 0x1e000200u, // (AAC_ADTS | AAC_SUB_ELD) AUDIO_FORMAT_AAC_ADTS_XHE = 0x1e000300u, // (AAC_ADTS | AAC_SUB_XHE) AUDIO_FORMAT_E_AC3_JOC = 0xA000001u, // (E_AC3 | E_AC3_SUB_JOC) AUDIO_FORMAT_MAT_1_0 = 0x24000001u, // (MAT | MAT_SUB_1_0) AUDIO_FORMAT_MAT_2_0 = 0x24000002u, // (MAT | MAT_SUB_2_0) AUDIO_FORMAT_MAT_2_1 = 0x24000003u, // (MAT | MAT_SUB_2_1) } audio_format_t; enum { FCC_2 = 2, FCC_8 = 8, }; enum { AUDIO_CHANNEL_REPRESENTATION_POSITION = 0x0u, AUDIO_CHANNEL_REPRESENTATION_INDEX = 0x2u, AUDIO_CHANNEL_NONE = 0x0u, AUDIO_CHANNEL_INVALID = 0xC0000000u, AUDIO_CHANNEL_OUT_FRONT_LEFT = 0x1u, AUDIO_CHANNEL_OUT_FRONT_RIGHT = 0x2u, AUDIO_CHANNEL_OUT_FRONT_CENTER = 0x4u, AUDIO_CHANNEL_OUT_LOW_FREQUENCY = 0x8u, AUDIO_CHANNEL_OUT_BACK_LEFT = 0x10u, AUDIO_CHANNEL_OUT_BACK_RIGHT = 0x20u, AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER = 0x40u, AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER = 0x80u, AUDIO_CHANNEL_OUT_BACK_CENTER = 0x100u, AUDIO_CHANNEL_OUT_SIDE_LEFT = 0x200u, AUDIO_CHANNEL_OUT_SIDE_RIGHT = 0x400u, AUDIO_CHANNEL_OUT_TOP_CENTER = 0x800u, AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT = 0x1000u, AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER = 0x2000u, AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT = 0x4000u, AUDIO_CHANNEL_OUT_TOP_BACK_LEFT = 0x8000u, AUDIO_CHANNEL_OUT_TOP_BACK_CENTER = 0x10000u, AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT = 0x20000u, AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT = 0x40000u, AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT = 0x80000u, AUDIO_CHANNEL_OUT_MONO = 0x1u, // OUT_FRONT_LEFT AUDIO_CHANNEL_OUT_STEREO = 0x3u, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT AUDIO_CHANNEL_OUT_2POINT1 = 0xBu, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_LOW_FREQUENCY AUDIO_CHANNEL_OUT_2POINT0POINT2 = 0xC0003u, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_TOP_SIDE_LEFT | OUT_TOP_SIDE_RIGHT AUDIO_CHANNEL_OUT_2POINT1POINT2 = 0xC000Bu, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_TOP_SIDE_LEFT | OUT_TOP_SIDE_RIGHT | OUT_LOW_FREQUENCY AUDIO_CHANNEL_OUT_3POINT0POINT2 = 0xC0007u, // OUT_FRONT_LEFT | OUT_FRONT_CENTER | OUT_FRONT_RIGHT | OUT_TOP_SIDE_LEFT | OUT_TOP_SIDE_RIGHT AUDIO_CHANNEL_OUT_3POINT1POINT2 = 0xC000Fu, // OUT_FRONT_LEFT | OUT_FRONT_CENTER | OUT_FRONT_RIGHT | OUT_TOP_SIDE_LEFT | OUT_TOP_SIDE_RIGHT | OUT_LOW_FREQUENCY AUDIO_CHANNEL_OUT_QUAD = 0x33u, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_BACK_LEFT | OUT_BACK_RIGHT AUDIO_CHANNEL_OUT_QUAD_BACK = 0x33u, // OUT_QUAD AUDIO_CHANNEL_OUT_QUAD_SIDE = 0x603u, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_SIDE_LEFT | OUT_SIDE_RIGHT AUDIO_CHANNEL_OUT_SURROUND = 0x107u, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_FRONT_CENTER | OUT_BACK_CENTER AUDIO_CHANNEL_OUT_PENTA = 0x37u, // OUT_QUAD | OUT_FRONT_CENTER AUDIO_CHANNEL_OUT_5POINT1 = 0x3Fu, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_FRONT_CENTER | OUT_LOW_FREQUENCY | OUT_BACK_LEFT | OUT_BACK_RIGHT AUDIO_CHANNEL_OUT_5POINT1_BACK = 0x3Fu, // OUT_5POINT1 AUDIO_CHANNEL_OUT_5POINT1_SIDE = 0x60Fu, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_FRONT_CENTER | OUT_LOW_FREQUENCY | OUT_SIDE_LEFT | OUT_SIDE_RIGHT AUDIO_CHANNEL_OUT_5POINT1POINT2 = 0xC003Fu, // OUT_5POINT1 | OUT_TOP_SIDE_LEFT | OUT_TOP_SIDE_RIGHT AUDIO_CHANNEL_OUT_5POINT1POINT4 = 0x2D03Fu, // OUT_5POINT1 | OUT_TOP_FRONT_LEFT | OUT_TOP_FRONT_RIGHT | OUT_TOP_BACK_LEFT | OUT_TOP_BACK_RIGHT AUDIO_CHANNEL_OUT_6POINT1 = 0x13Fu, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_FRONT_CENTER | OUT_LOW_FREQUENCY | OUT_BACK_LEFT | OUT_BACK_RIGHT | OUT_BACK_CENTER AUDIO_CHANNEL_OUT_7POINT1 = 0x63Fu, // OUT_FRONT_LEFT | OUT_FRONT_RIGHT | OUT_FRONT_CENTER | OUT_LOW_FREQUENCY | OUT_BACK_LEFT | OUT_BACK_RIGHT | OUT_SIDE_LEFT | OUT_SIDE_RIGHT AUDIO_CHANNEL_OUT_7POINT1POINT2 = 0xC063Fu, // OUT_7POINT1 | OUT_TOP_SIDE_LEFT | OUT_TOP_SIDE_RIGHT AUDIO_CHANNEL_OUT_7POINT1POINT4 = 0x2D63Fu, // OUT_7POINT1 | OUT_TOP_FRONT_LEFT | OUT_TOP_FRONT_RIGHT | OUT_TOP_BACK_LEFT | OUT_TOP_BACK_RIGHT AUDIO_CHANNEL_IN_LEFT = 0x4u, AUDIO_CHANNEL_IN_RIGHT = 0x8u, AUDIO_CHANNEL_IN_FRONT = 0x10u, AUDIO_CHANNEL_IN_BACK = 0x20u, AUDIO_CHANNEL_IN_LEFT_PROCESSED = 0x40u, AUDIO_CHANNEL_IN_RIGHT_PROCESSED = 0x80u, AUDIO_CHANNEL_IN_FRONT_PROCESSED = 0x100u, AUDIO_CHANNEL_IN_BACK_PROCESSED = 0x200u, AUDIO_CHANNEL_IN_PRESSURE = 0x400u, AUDIO_CHANNEL_IN_X_AXIS = 0x800u, AUDIO_CHANNEL_IN_Y_AXIS = 0x1000u, AUDIO_CHANNEL_IN_Z_AXIS = 0x2000u, AUDIO_CHANNEL_IN_BACK_LEFT = 0x10000u, AUDIO_CHANNEL_IN_BACK_RIGHT = 0x20000u, AUDIO_CHANNEL_IN_CENTER = 0x40000u, AUDIO_CHANNEL_IN_LOW_FREQUENCY = 0x100000u, AUDIO_CHANNEL_IN_TOP_LEFT = 0x200000u, AUDIO_CHANNEL_IN_TOP_RIGHT = 0x400000u, AUDIO_CHANNEL_IN_VOICE_UPLINK = 0x4000u, AUDIO_CHANNEL_IN_VOICE_DNLINK = 0x8000u, AUDIO_CHANNEL_IN_MONO = 0x10u, // IN_FRONT AUDIO_CHANNEL_IN_STEREO = 0xCu, // IN_LEFT | IN_RIGHT AUDIO_CHANNEL_IN_FRONT_BACK = 0x30u, // IN_FRONT | IN_BACK AUDIO_CHANNEL_IN_6 = 0xFCu, // IN_LEFT | IN_RIGHT | IN_FRONT | IN_BACK | IN_LEFT_PROCESSED | IN_RIGHT_PROCESSED AUDIO_CHANNEL_IN_2POINT0POINT2 = 0x60000Cu, // IN_LEFT | IN_RIGHT | IN_TOP_LEFT | IN_TOP_RIGHT AUDIO_CHANNEL_IN_2POINT1POINT2 = 0x70000Cu, // IN_LEFT | IN_RIGHT | IN_TOP_LEFT | IN_TOP_RIGHT | IN_LOW_FREQUENCY AUDIO_CHANNEL_IN_3POINT0POINT2 = 0x64000Cu, // IN_LEFT | IN_CENTER | IN_RIGHT | IN_TOP_LEFT | IN_TOP_RIGHT AUDIO_CHANNEL_IN_3POINT1POINT2 = 0x74000Cu, // IN_LEFT | IN_CENTER | IN_RIGHT | IN_TOP_LEFT | IN_TOP_RIGHT | IN_LOW_FREQUENCY AUDIO_CHANNEL_IN_5POINT1 = 0x17000Cu, // IN_LEFT | IN_CENTER | IN_RIGHT | IN_BACK_LEFT | IN_BACK_RIGHT | IN_LOW_FREQUENCY AUDIO_CHANNEL_IN_VOICE_UPLINK_MONO = 0x4010u, // IN_VOICE_UPLINK | IN_MONO AUDIO_CHANNEL_IN_VOICE_DNLINK_MONO = 0x8010u, // IN_VOICE_DNLINK | IN_MONO AUDIO_CHANNEL_IN_VOICE_CALL_MONO = 0xC010u, // IN_VOICE_UPLINK_MONO | IN_VOICE_DNLINK_MONO AUDIO_CHANNEL_COUNT_MAX = 30u, AUDIO_CHANNEL_INDEX_HDR = 0x80000000u, // REPRESENTATION_INDEX << COUNT_MAX AUDIO_CHANNEL_INDEX_MASK_1 = 0x80000001u, // INDEX_HDR | (1 << 1) - 1 AUDIO_CHANNEL_INDEX_MASK_2 = 0x80000003u, // INDEX_HDR | (1 << 2) - 1 AUDIO_CHANNEL_INDEX_MASK_3 = 0x80000007u, // INDEX_HDR | (1 << 3) - 1 AUDIO_CHANNEL_INDEX_MASK_4 = 0x8000000Fu, // INDEX_HDR | (1 << 4) - 1 AUDIO_CHANNEL_INDEX_MASK_5 = 0x8000001Fu, // INDEX_HDR | (1 << 5) - 1 AUDIO_CHANNEL_INDEX_MASK_6 = 0x8000003Fu, // INDEX_HDR | (1 << 6) - 1 AUDIO_CHANNEL_INDEX_MASK_7 = 0x8000007Fu, // INDEX_HDR | (1 << 7) - 1 AUDIO_CHANNEL_INDEX_MASK_8 = 0x800000FFu, // INDEX_HDR | (1 << 8) - 1 }; typedef enum { #ifndef AUDIO_NO_SYSTEM_DECLARATIONS AUDIO_MODE_INVALID = -2, // (-2) AUDIO_MODE_CURRENT = -1, // (-1) #endif // AUDIO_NO_SYSTEM_DECLARATIONS AUDIO_MODE_NORMAL = 0, AUDIO_MODE_RINGTONE = 1, AUDIO_MODE_IN_CALL = 2, AUDIO_MODE_IN_COMMUNICATION = 3, } audio_mode_t; enum { AUDIO_DEVICE_NONE = 0x0u, AUDIO_DEVICE_BIT_IN = 0x80000000u, AUDIO_DEVICE_BIT_DEFAULT = 0x40000000u, AUDIO_DEVICE_OUT_EARPIECE = 0x1u, AUDIO_DEVICE_OUT_SPEAKER = 0x2u, AUDIO_DEVICE_OUT_WIRED_HEADSET = 0x4u, AUDIO_DEVICE_OUT_WIRED_HEADPHONE = 0x8u, AUDIO_DEVICE_OUT_BLUETOOTH_SCO = 0x10u, AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET = 0x20u, AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT = 0x40u, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP = 0x80u, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES = 0x100u, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER = 0x200u, AUDIO_DEVICE_OUT_AUX_DIGITAL = 0x400u, AUDIO_DEVICE_OUT_HDMI = 0x400u, // OUT_AUX_DIGITAL AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET = 0x800u, AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET = 0x1000u, AUDIO_DEVICE_OUT_USB_ACCESSORY = 0x2000u, AUDIO_DEVICE_OUT_USB_DEVICE = 0x4000u, AUDIO_DEVICE_OUT_REMOTE_SUBMIX = 0x8000u, AUDIO_DEVICE_OUT_TELEPHONY_TX = 0x10000u, AUDIO_DEVICE_OUT_LINE = 0x20000u, AUDIO_DEVICE_OUT_HDMI_ARC = 0x40000u, AUDIO_DEVICE_OUT_SPDIF = 0x80000u, AUDIO_DEVICE_OUT_FM = 0x100000u, AUDIO_DEVICE_OUT_AUX_LINE = 0x200000u, AUDIO_DEVICE_OUT_SPEAKER_SAFE = 0x400000u, AUDIO_DEVICE_OUT_IP = 0x800000u, AUDIO_DEVICE_OUT_BUS = 0x1000000u, AUDIO_DEVICE_OUT_PROXY = 0x2000000u, AUDIO_DEVICE_OUT_USB_HEADSET = 0x4000000u, AUDIO_DEVICE_OUT_HEARING_AID = 0x8000000u, AUDIO_DEVICE_OUT_ECHO_CANCELLER = 0x10000000u, AUDIO_DEVICE_OUT_DEFAULT = 0x40000000u, // BIT_DEFAULT AUDIO_DEVICE_IN_COMMUNICATION = 0x80000001u, // BIT_IN | 0x1 AUDIO_DEVICE_IN_AMBIENT = 0x80000002u, // BIT_IN | 0x2 AUDIO_DEVICE_IN_BUILTIN_MIC = 0x80000004u, // BIT_IN | 0x4 AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET = 0x80000008u, // BIT_IN | 0x8 AUDIO_DEVICE_IN_WIRED_HEADSET = 0x80000010u, // BIT_IN | 0x10 AUDIO_DEVICE_IN_AUX_DIGITAL = 0x80000020u, // BIT_IN | 0x20 AUDIO_DEVICE_IN_HDMI = 0x80000020u, // IN_AUX_DIGITAL AUDIO_DEVICE_IN_VOICE_CALL = 0x80000040u, // BIT_IN | 0x40 AUDIO_DEVICE_IN_TELEPHONY_RX = 0x80000040u, // IN_VOICE_CALL AUDIO_DEVICE_IN_BACK_MIC = 0x80000080u, // BIT_IN | 0x80 AUDIO_DEVICE_IN_REMOTE_SUBMIX = 0x80000100u, // BIT_IN | 0x100 AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET = 0x80000200u, // BIT_IN | 0x200 AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET = 0x80000400u, // BIT_IN | 0x400 AUDIO_DEVICE_IN_USB_ACCESSORY = 0x80000800u, // BIT_IN | 0x800 AUDIO_DEVICE_IN_USB_DEVICE = 0x80001000u, // BIT_IN | 0x1000 AUDIO_DEVICE_IN_FM_TUNER = 0x80002000u, // BIT_IN | 0x2000 AUDIO_DEVICE_IN_TV_TUNER = 0x80004000u, // BIT_IN | 0x4000 AUDIO_DEVICE_IN_LINE = 0x80008000u, // BIT_IN | 0x8000 AUDIO_DEVICE_IN_SPDIF = 0x80010000u, // BIT_IN | 0x10000 AUDIO_DEVICE_IN_BLUETOOTH_A2DP = 0x80020000u, // BIT_IN | 0x20000 AUDIO_DEVICE_IN_LOOPBACK = 0x80040000u, // BIT_IN | 0x40000 AUDIO_DEVICE_IN_IP = 0x80080000u, // BIT_IN | 0x80000 AUDIO_DEVICE_IN_BUS = 0x80100000u, // BIT_IN | 0x100000 AUDIO_DEVICE_IN_PROXY = 0x81000000u, // BIT_IN | 0x1000000 AUDIO_DEVICE_IN_USB_HEADSET = 0x82000000u, // BIT_IN | 0x2000000 AUDIO_DEVICE_IN_BLUETOOTH_BLE = 0x84000000u, // BIT_IN | 0x4000000 AUDIO_DEVICE_IN_DEFAULT = 0xC0000000u, // BIT_IN | BIT_DEFAULT }; typedef enum { AUDIO_OUTPUT_FLAG_NONE = 0x0, AUDIO_OUTPUT_FLAG_DIRECT = 0x1, AUDIO_OUTPUT_FLAG_PRIMARY = 0x2, AUDIO_OUTPUT_FLAG_FAST = 0x4, AUDIO_OUTPUT_FLAG_DEEP_BUFFER = 0x8, AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD = 0x10, AUDIO_OUTPUT_FLAG_NON_BLOCKING = 0x20, AUDIO_OUTPUT_FLAG_HW_AV_SYNC = 0x40, AUDIO_OUTPUT_FLAG_TTS = 0x80, AUDIO_OUTPUT_FLAG_RAW = 0x100, AUDIO_OUTPUT_FLAG_SYNC = 0x200, AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO = 0x400, AUDIO_OUTPUT_FLAG_DIRECT_PCM = 0x2000, AUDIO_OUTPUT_FLAG_MMAP_NOIRQ = 0x4000, AUDIO_OUTPUT_FLAG_VOIP_RX = 0x8000, AUDIO_OUTPUT_FLAG_INCALL_MUSIC = 0x10000, } audio_output_flags_t; typedef enum { AUDIO_INPUT_FLAG_NONE = 0x0, AUDIO_INPUT_FLAG_FAST = 0x1, AUDIO_INPUT_FLAG_HW_HOTWORD = 0x2, AUDIO_INPUT_FLAG_RAW = 0x4, AUDIO_INPUT_FLAG_SYNC = 0x8, AUDIO_INPUT_FLAG_MMAP_NOIRQ = 0x10, AUDIO_INPUT_FLAG_VOIP_TX = 0x20, AUDIO_INPUT_FLAG_HW_AV_SYNC = 0x40, } audio_input_flags_t; typedef enum { AUDIO_USAGE_UNKNOWN = 0, AUDIO_USAGE_MEDIA = 1, AUDIO_USAGE_VOICE_COMMUNICATION = 2, AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING = 3, AUDIO_USAGE_ALARM = 4, AUDIO_USAGE_NOTIFICATION = 5, AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE = 6, #ifndef AUDIO_NO_SYSTEM_DECLARATIONS AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST = 7, AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT = 8, AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED = 9, AUDIO_USAGE_NOTIFICATION_EVENT = 10, #endif // AUDIO_NO_SYSTEM_DECLARATIONS AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY = 11, AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE = 12, AUDIO_USAGE_ASSISTANCE_SONIFICATION = 13, AUDIO_USAGE_GAME = 14, AUDIO_USAGE_VIRTUAL_SOURCE = 15, AUDIO_USAGE_ASSISTANT = 16, } audio_usage_t; typedef enum { AUDIO_CONTENT_TYPE_UNKNOWN = 0u, AUDIO_CONTENT_TYPE_SPEECH = 1u, AUDIO_CONTENT_TYPE_MUSIC = 2u, AUDIO_CONTENT_TYPE_MOVIE = 3u, AUDIO_CONTENT_TYPE_SONIFICATION = 4u, } audio_content_type_t; enum { AUDIO_GAIN_MODE_JOINT = 0x1u, AUDIO_GAIN_MODE_CHANNELS = 0x2u, AUDIO_GAIN_MODE_RAMP = 0x4u, }; typedef enum { AUDIO_PORT_ROLE_NONE = 0, AUDIO_PORT_ROLE_SOURCE = 1, // (::android::hardware::audio::common::V4_0::AudioPortRole.NONE implicitly + 1) AUDIO_PORT_ROLE_SINK = 2, // (::android::hardware::audio::common::V4_0::AudioPortRole.SOURCE implicitly + 1) } audio_port_role_t; typedef enum { AUDIO_PORT_TYPE_NONE = 0, AUDIO_PORT_TYPE_DEVICE = 1, // (::android::hardware::audio::common::V4_0::AudioPortType.NONE implicitly + 1) AUDIO_PORT_TYPE_MIX = 2, // (::android::hardware::audio::common::V4_0::AudioPortType.DEVICE implicitly + 1) AUDIO_PORT_TYPE_SESSION = 3, // (::android::hardware::audio::common::V4_0::AudioPortType.MIX implicitly + 1) } audio_port_type_t; enum { AUDIO_PORT_CONFIG_SAMPLE_RATE = 0x1u, AUDIO_PORT_CONFIG_CHANNEL_MASK = 0x2u, AUDIO_PORT_CONFIG_FORMAT = 0x4u, AUDIO_PORT_CONFIG_GAIN = 0x8u, }; typedef enum { AUDIO_LATENCY_LOW = 0, AUDIO_LATENCY_NORMAL = 1, // (::android::hardware::audio::common::V4_0::AudioMixLatencyClass.LOW implicitly + 1) } audio_mix_latency_class_t; #ifdef __cplusplus } #endif #endif // HIDL_GENERATED_ANDROID_HARDWARE_AUDIO_COMMON_V4_0_EXPORTED_CONSTANTS_H_
james34602/JamesDSPManager
VeryOldOpen_source_edition/Audio_Engine/eclipse_libjamesdsp_free_bp/jni/hardware/system/audio-base.h
C
gpl-2.0
23,325
/* $Id: bitops.h,v 1.1.1.1 2004/06/19 05:02:56 ashieh Exp $ * bitops.h: Bit string operations on the V9. * * Copyright 1996, 1997 David S. Miller ([email protected]) */ #ifndef _SPARC64_BITOPS_H #define _SPARC64_BITOPS_H #include <asm/byteorder.h> extern long ___test_and_set_bit(unsigned long nr, volatile void *addr); extern long ___test_and_clear_bit(unsigned long nr, volatile void *addr); extern long ___test_and_change_bit(unsigned long nr, volatile void *addr); #define test_and_set_bit(nr,addr) ({___test_and_set_bit(nr,addr)!=0;}) #define test_and_clear_bit(nr,addr) ({___test_and_clear_bit(nr,addr)!=0;}) #define test_and_change_bit(nr,addr) ({___test_and_change_bit(nr,addr)!=0;}) #define set_bit(nr,addr) ((void)___test_and_set_bit(nr,addr)) #define clear_bit(nr,addr) ((void)___test_and_clear_bit(nr,addr)) #define change_bit(nr,addr) ((void)___test_and_change_bit(nr,addr)) /* "non-atomic" versions... */ #define __set_bit(X,Y) \ do { unsigned long __nr = (X); \ long *__m = ((long *) (Y)) + (__nr >> 6); \ *__m |= (1UL << (__nr & 63)); \ } while (0) #define __clear_bit(X,Y) \ do { unsigned long __nr = (X); \ long *__m = ((long *) (Y)) + (__nr >> 6); \ *__m &= ~(1UL << (__nr & 63)); \ } while (0) #define __change_bit(X,Y) \ do { unsigned long __nr = (X); \ long *__m = ((long *) (Y)) + (__nr >> 6); \ *__m ^= (1UL << (__nr & 63)); \ } while (0) #define __test_and_set_bit(X,Y) \ ({ unsigned long __nr = (X); \ long *__m = ((long *) (Y)) + (__nr >> 6); \ long __old = *__m; \ long __mask = (1UL << (__nr & 63)); \ *__m = (__old | __mask); \ ((__old & __mask) != 0); \ }) #define __test_and_clear_bit(X,Y) \ ({ unsigned long __nr = (X); \ long *__m = ((long *) (Y)) + (__nr >> 6); \ long __old = *__m; \ long __mask = (1UL << (__nr & 63)); \ *__m = (__old & ~__mask); \ ((__old & __mask) != 0); \ }) #define __test_and_change_bit(X,Y) \ ({ unsigned long __nr = (X); \ long *__m = ((long *) (Y)) + (__nr >> 6); \ long __old = *__m; \ long __mask = (1UL << (__nr & 63)); \ *__m = (__old ^ __mask); \ ((__old & __mask) != 0); \ }) #define smp_mb__before_clear_bit() do { } while(0) #define smp_mb__after_clear_bit() do { } while(0) extern __inline__ int test_bit(int nr, __const__ void *addr) { return (1UL & (((__const__ long *) addr)[nr >> 6] >> (nr & 63))) != 0UL; } /* The easy/cheese version for now. */ extern __inline__ unsigned long ffz(unsigned long word) { unsigned long result; #ifdef ULTRA_HAS_POPULATION_COUNT /* Thanks for nothing Sun... */ __asm__ __volatile__( " brz,pn %0, 1f\n" " neg %0, %%g1\n" " xnor %0, %%g1, %%g2\n" " popc %%g2, %0\n" "1: " : "=&r" (result) : "0" (word) : "g1", "g2"); #else #if 1 /* def EASY_CHEESE_VERSION */ result = 0; while(word & 1) { result++; word >>= 1; } #else unsigned long tmp; result = 0; tmp = ~word & -~word; if (!(unsigned)tmp) { tmp >>= 32; result = 32; } if (!(unsigned short)tmp) { tmp >>= 16; result += 16; } if (!(unsigned char)tmp) { tmp >>= 8; result += 8; } if (tmp & 0xf0) result += 4; if (tmp & 0xcc) result += 2; if (tmp & 0xaa) result ++; #endif #endif return result; } #ifdef __KERNEL__ /* * ffs: find first bit set. This is defined the same way as * the libc and compiler builtin ffs routines, therefore * differs in spirit from the above ffz (man ffs). */ #define ffs(x) generic_ffs(x) /* * hweightN: returns the hamming weight (i.e. the number * of bits set) of a N-bit word */ #ifdef ULTRA_HAS_POPULATION_COUNT extern __inline__ unsigned int hweight32(unsigned int w) { unsigned int res; __asm__ ("popc %1,%0" : "=r" (res) : "r" (w & 0xffffffff)); return res; } extern __inline__ unsigned int hweight16(unsigned int w) { unsigned int res; __asm__ ("popc %1,%0" : "=r" (res) : "r" (w & 0xffff)); return res; } extern __inline__ unsigned int hweight8(unsigned int w) { unsigned int res; __asm__ ("popc %1,%0" : "=r" (res) : "r" (w & 0xff)); return res; } #else #define hweight32(x) generic_hweight32(x) #define hweight16(x) generic_hweight16(x) #define hweight8(x) generic_hweight8(x) #endif #endif /* __KERNEL__ */ /* find_next_zero_bit() finds the first zero bit in a bit string of length * 'size' bits, starting the search at bit 'offset'. This is largely based * on Linus's ALPHA routines, which are pretty portable BTW. */ extern __inline__ unsigned long find_next_zero_bit(void *addr, unsigned long size, unsigned long offset) { unsigned long *p = ((unsigned long *) addr) + (offset >> 6); unsigned long result = offset & ~63UL; unsigned long tmp; if (offset >= size) return size; size -= result; offset &= 63UL; if (offset) { tmp = *(p++); tmp |= ~0UL >> (64-offset); if (size < 64) goto found_first; if (~tmp) goto found_middle; size -= 64; result += 64; } while (size & ~63UL) { if (~(tmp = *(p++))) goto found_middle; result += 64; size -= 64; } if (!size) return result; tmp = *p; found_first: tmp |= ~0UL << size; if (tmp == ~0UL) /* Are any bits zero? */ return result + size; /* Nope. */ found_middle: return result + ffz(tmp); } #define find_first_zero_bit(addr, size) \ find_next_zero_bit((addr), (size), 0) extern long ___test_and_set_le_bit(int nr, volatile void *addr); extern long ___test_and_clear_le_bit(int nr, volatile void *addr); #define test_and_set_le_bit(nr,addr) ({___test_and_set_le_bit(nr,addr)!=0;}) #define test_and_clear_le_bit(nr,addr) ({___test_and_clear_le_bit(nr,addr)!=0;}) #define set_le_bit(nr,addr) ((void)___test_and_set_le_bit(nr,addr)) #define clear_le_bit(nr,addr) ((void)___test_and_clear_le_bit(nr,addr)) extern __inline__ int test_le_bit(int nr, __const__ void * addr) { int mask; __const__ unsigned char *ADDR = (__const__ unsigned char *) addr; ADDR += nr >> 3; mask = 1 << (nr & 0x07); return ((mask & *ADDR) != 0); } #define find_first_zero_le_bit(addr, size) \ find_next_zero_le_bit((addr), (size), 0) extern __inline__ unsigned long find_next_zero_le_bit(void *addr, unsigned long size, unsigned long offset) { unsigned long *p = ((unsigned long *) addr) + (offset >> 6); unsigned long result = offset & ~63UL; unsigned long tmp; if (offset >= size) return size; size -= result; offset &= 63UL; if(offset) { tmp = __swab64p(p++); tmp |= (~0UL >> (64-offset)); if(size < 64) goto found_first; if(~tmp) goto found_middle; size -= 64; result += 64; } while(size & ~63) { if(~(tmp = __swab64p(p++))) goto found_middle; result += 64; size -= 64; } if(!size) return result; tmp = __swab64p(p); found_first: tmp |= (~0UL << size); if (tmp == ~0UL) /* Are any bits zero? */ return result + size; /* Nope. */ found_middle: return result + ffz(tmp); } #ifdef __KERNEL__ #define ext2_set_bit test_and_set_le_bit #define ext2_clear_bit test_and_clear_le_bit #define ext2_test_bit test_le_bit #define ext2_find_first_zero_bit find_first_zero_le_bit #define ext2_find_next_zero_bit find_next_zero_le_bit /* Bitmap functions for the minix filesystem. */ #define minix_test_and_set_bit(nr,addr) test_and_set_bit(nr,addr) #define minix_set_bit(nr,addr) set_bit(nr,addr) #define minix_test_and_clear_bit(nr,addr) test_and_clear_bit(nr,addr) #define minix_test_bit(nr,addr) test_bit(nr,addr) #define minix_find_first_zero_bit(addr,size) find_first_zero_bit(addr,size) #endif /* __KERNEL__ */ #endif /* defined(_SPARC64_BITOPS_H) */
romanalexander/Trickles
include/asm-sparc64/bitops.h
C
gpl-2.0
7,493
#ifndef RENDERENVCONSTS_H_INCLUDED #define RENDERENVCONSTS_H_INCLUDED /* * consts */ /* The following rendering method is expected to engage in the renderer */ /** \brief available renderer type */ enum PreferredRendererType { RendererUndeterminate, /**< a memory block with undefined renderer */ RendererRasterizer, /**< rasterization renderer */ RendererPathTracer, /**< path tracing renderer */ RendererPhotonTracer, /**< photon tracing renderer */ RendererPhotonMap, /**< photon light map generation renderer */ RendererRadiosity, /**< radiosity light map generation renderer */ RendererRadianceCache, /**< radiance cache generation renderer */ RendererPRT, /**< precomputed radiance transfer renderer */ RendererSelection, /**< object selection renderer */ c_NumRendererType }; static const int LightModelDirect = 0X1; static const int LightModelShadow = 0X2; static const int LightModelLightMap = 0X4; static const int LightModelSHProbe = 0X8; static const int LightModelSVO = 0X10; enum GeometryModelType { GeometryModelWireframe, GeometryModelSolid }; /* Renderer should not handle threading from these constants itself, * this are the states telling which situation * the renderer is being created with */ static const int RenderThreadMutual = 0X0; static const int RenderThreadSeparated = 0X1; /* These are what renderer expected to behave internally */ static const int RenderThreadSingle = 0X2; static const int RenderThreadMultiple = 0X4; enum RenderSpecType { RenderSpecSWBuiltin, RenderSpecSWAdvBuiltin, RenderSpecHWOpenGL, RenderSpecHWDirectX }; enum RenderEnvironment { RenderEnvVoid, RenderEnvSpec, RenderEnvProbe, RenderEnvRenderable, RenderEnvRenderOut, RenderEnvThread, RenderEnvAntialias, RenderEnvFiltering, RenderEnvGeometryModel, RenderEnvPreferredRenderer, c_NumRenderEnviornmentType }; #endif // RENDERENVCONSTS_H_INCLUDED
DaviesX/x3ddemoscene
include/x3d/renderenvconsts.h
C
gpl-2.0
2,254
using System; using System.Collections.Generic; using System.Data; using System.Data.SQLite; using System.IO; using System.Linq; using System.Text; using System.Windows.Forms; using System.Xml; namespace VariablesManager { public partial class Form1 : Form { private string _selectedTm; private string _selectedLrt; public string SelectedTm { get => _selectedTm.Trim(); set => _selectedTm = value; } public string SelectedLrt { get => _selectedLrt.Trim(); set => _selectedLrt = value; } public Form1() { InitializeComponent(); } private void btnBrowseTM_Click(object sender, EventArgs e) { openFileDialog.Filter = @"Translation memory (*.sdltm)|*.sdltm"; if (openFileDialog.ShowDialog() == DialogResult.OK) { SelectedTm = openFileDialog.FileName; txtTM.Text = Path.GetFileName(openFileDialog.FileName); } } private void btnBrowseLRT_Click(object sender, EventArgs e) { openFileDialog.Filter = @"Language Resource Template (*.resource)|*.resource"; if (openFileDialog.ShowDialog() == DialogResult.OK) { SelectedLrt = openFileDialog.FileName; txtLRT.Text = Path.GetFileName(openFileDialog.FileName); } } private void btnImportFromFile_Click(object sender, EventArgs e) { openFileDialog.Filter = @"Text files (*.txt)|*.txt|All files (*.*)|*.*"; if (openFileDialog.ShowDialog() == DialogResult.OK) { try { using (var sr = new StreamReader(openFileDialog.FileName)) { txtVariables.Text = sr.ReadToEnd(); } } catch { } } } private void btnExportToFile_Click(object sender, EventArgs e) { saveFileDialog.Filter = @"Text files (*.txt)|*.txt|All files (*.*)|*.*"; saveFileDialog.DefaultExt = "txt"; saveFileDialog.AddExtension = true; if (saveFileDialog.ShowDialog() == DialogResult.OK) { try { using (var sw = new StreamWriter(saveFileDialog.FileName, false)) { sw.Write(txtVariables.Text); } } catch { } } MessageBox.Show(@"The variables list was exported to the selected file."); } private void btnFetchList_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(txtTM.Text)) { FetchFromTm(); } if (!string.IsNullOrEmpty(txtLRT.Text)) { FetchFromLrt(); } } private void FetchFromLrt() { if (string.IsNullOrEmpty(SelectedLrt)) return; var vars = GetVariablesAsTextFromLrt(); if (string.IsNullOrEmpty(vars)) return; if (!string.IsNullOrEmpty(txtVariables.Text) && txtVariables.Text[txtVariables.Text.Length - 1] != '\n') txtVariables.Text += "\r\n"; txtVariables.Text += vars; } private string GetVariablesAsTextFromLrt() { try { var xFinalDoc = new XmlDocument(); xFinalDoc.Load(SelectedLrt); XmlNodeList languageResources = xFinalDoc.DocumentElement.GetElementsByTagName("LanguageResource"); if (languageResources.Count > 0) { foreach (XmlElement languageResource in languageResources) { if (languageResource.HasAttribute("Type") && languageResource.Attributes["Type"].Value == "Variables") { IEnumerable<XmlText> textElements = languageResource.ChildNodes.OfType<XmlText>(); if (textElements.Any()) { var textElement = textElements.FirstOrDefault(); var base64Vars = textElement.Value; return Encoding.UTF8.GetString(Convert.FromBase64String(base64Vars)); } } } } } catch { } return string.Empty; } private void FetchFromTm() { if (string.IsNullOrEmpty(txtTM.Text) || string.IsNullOrEmpty(SelectedTm)) return; int count = 0; var vars = GetVariablesAsTextFromTm(out count); if (string.IsNullOrEmpty(vars)) return; if (!string.IsNullOrEmpty(txtVariables.Text) && txtVariables.Text[txtVariables.Text.Length - 1] != '\n') txtVariables.Text += "\r\n"; txtVariables.Text += vars; } private string GetVariablesAsTextFromTm(out int count) { count = 0; try { SQLiteConnectionStringBuilder sb = new SQLiteConnectionStringBuilder(); sb.DataSource = SelectedTm; sb.Version = 3; sb.JournalMode = SQLiteJournalModeEnum.Off; using (var connection = new SQLiteConnection(sb.ConnectionString, true)) using (var command = new SQLiteCommand(connection)) { connection.Open(); command.CommandText = "SELECT data FROM resources where type = 1"; using (var reader = command.ExecuteReader()) { while (reader.Read()) { count++; var buffer = GetBytes(reader); return Encoding.UTF8.GetString(buffer); } } } } catch { } return string.Empty; } static byte[] GetBytes(SQLiteDataReader reader) { const int CHUNK_SIZE = 2 * 1024; var buffer = new byte[CHUNK_SIZE]; long bytesRead; long fieldOffset = 0; using (MemoryStream stream = new MemoryStream()) { while ((bytesRead = reader.GetBytes(0, fieldOffset, buffer, 0, buffer.Length)) > 0) { stream.Write(buffer, 0, (int)bytesRead); fieldOffset += bytesRead; } return stream.ToArray(); } } private void btnAddToTMorLRT_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(txtTM.Text)) AddToTm(); if (!string.IsNullOrEmpty(txtLRT.Text)) AddToLrt(); } private void AddToLrt() { if (string.IsNullOrEmpty(SelectedLrt) || string.IsNullOrEmpty(txtVariables.Text)) return; var vars = GetVariablesAsTextFromLrt() + txtVariables.Text; if (!string.IsNullOrEmpty(vars) && vars[vars.Length - 1] != '\n') vars += "\r\n"; var base64Vars = Convert.ToBase64String(Encoding.UTF8.GetBytes(vars)); SetVariablesInLrt(base64Vars); MessageBox.Show(@"The variables list was add to the selected Language Resource Template."); } private void SetVariablesInLrt(string base64Vars) { try { var xFinalDoc = new XmlDocument(); xFinalDoc.Load(SelectedLrt); XmlNodeList languageResources = xFinalDoc.DocumentElement.GetElementsByTagName("LanguageResource"); if (languageResources.Count > 0) { foreach (XmlElement languageResource in languageResources) { if (languageResource.HasAttribute("Type") && languageResource.Attributes["Type"].Value == "Variables") { languageResource.InnerText = base64Vars; } } } using (var writer = new XmlTextWriter(SelectedLrt, null)) { writer.Formatting = Formatting.None; xFinalDoc.Save(writer); } } catch { } } private void AddToTm() { if (string.IsNullOrEmpty(SelectedTm) || string.IsNullOrEmpty(txtVariables.Text)) return; int count = 0; var vars = GetVariablesAsTextFromTm(out count) + txtVariables.Text; if (!string.IsNullOrEmpty(vars) && vars[vars.Length - 1] != '\n') vars += "\r\n"; SetVariablesInTm(Encoding.UTF8.GetBytes(vars), count); MessageBox.Show(@"The variables list was add to the selected Translation Memory."); } private void SetVariablesInTm(byte[] variablesAsBytes, int count) { try { var sb = new SQLiteConnectionStringBuilder { DataSource = SelectedTm, Version = 3, JournalMode = SQLiteJournalModeEnum.Off }; int maxID = 0; if (count == 0) { using (var connection = new SQLiteConnection(sb.ConnectionString, true)) { using (var command = new SQLiteCommand(connection)) { connection.Open(); command.CommandText = "Select max(id) from resources"; object oId = command.ExecuteScalar(); maxID = oId == DBNull.Value ? 1 : Convert.ToInt32(oId) + 1; } } } using (var connection = new SQLiteConnection(sb.ConnectionString, true)) { using (var command = new SQLiteCommand(connection)) { connection.Open(); if (count == 0) { command.CommandText = string.Format( "insert into resources (rowid, id, guid, type, language, data) values ({2}, {2}, '{0}', 1, '{1}', @data)", Guid.NewGuid(), GetTmLanguage(), maxID); } else { command.CommandText = "update resources set data = @data where type = 1"; } command.Parameters.Add("@data", DbType.Binary).Value = variablesAsBytes; command.ExecuteNonQuery(); } } } catch (Exception e) { } } private object GetTmLanguage() { try { var sb = new SQLiteConnectionStringBuilder { DataSource = SelectedTm, Version = 3, JournalMode = SQLiteJournalModeEnum.Off }; using (var connection = new SQLiteConnection(sb.ConnectionString, true)) using (var command = new SQLiteCommand(connection)) { connection.Open(); command.CommandText = "SELECT source_language FROM translation_memories"; using (var reader = command.ExecuteReader()) { while (reader.Read()) { return reader.GetString(0); } } } } catch { } return string.Empty; } private void btnReplateToTMorLRT_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(txtTM.Text)) { ReplaceToTm(); } if (!string.IsNullOrEmpty(txtLRT.Text)) { ReplaceToLrt(); } } private void ReplaceToLrt() { if (string.IsNullOrEmpty(SelectedLrt)) { return; } var vars = txtVariables.Text; if (!string.IsNullOrEmpty(vars) && vars[vars.Length - 1] != '\n') { vars += "\r\n"; } var base64Vars = Convert.ToBase64String(Encoding.UTF8.GetBytes(vars)); SetVariablesInLrt(base64Vars); MessageBox.Show(@"The variables list from the selected Language Resource Template was replaced with the new one."); } private void ReplaceToTm() { if (string.IsNullOrEmpty(SelectedTm)) return; var vars = txtVariables.Text; if (!string.IsNullOrEmpty(vars) && vars[vars.Length - 1] != '\n') vars += "\r\n"; var count = 0; GetVariablesAsTextFromTm(out count); SetVariablesInTm(Encoding.UTF8.GetBytes(vars), count); MessageBox.Show(@"The variables list from the selected Translation Memory was replaced with the new one."); } private void btnClear_Click(object sender, EventArgs e) { txtVariables.Clear(); } } }
sdl/Sdl-Community
VariablesManager/VariablesManager/Form1.cs
C#
gpl-2.0
13,948
/* IEEE754 floating point arithmetic * single precision */ /* * MIPS floating point support * Copyright (C) 1994-2000 Algorithmics Ltd. * * ######################################################################## * * This program is free software; you can distribute it and/or modify it * under the terms 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., * 59 Temple Place - Suite 330, Boston MA 02111-1307, USA. * * ######################################################################## */ #include "ieee754sp.h" /* close to ieeep754sp_logb */ ieee754sp ieee754sp_frexp(ieee754sp x, int *eptr) { COMPXSP; CLEARCX; EXPLODEXSP; switch (xc) { case IEEE754_CLASS_SNAN: case IEEE754_CLASS_QNAN: case IEEE754_CLASS_INF: case IEEE754_CLASS_ZERO: *eptr = 0; return x; case IEEE754_CLASS_DNORM: SPDNORMX; break; case IEEE754_CLASS_NORM: break; } *eptr = xe + 1; return buildsp(xs, -1 + SP_EBIAS, xm & ~SP_HIDDEN_BIT); }
evolver56k/xpenology
arch/mips/math-emu/sp_frexp.c
C
gpl-2.0
1,405
<?php include_once "./_common.php"; //pc버전에서 모바일가기 링크 타고 들어올 경우 세션을 삭제한다. 세션이 삭제되면 모바일 기기에서 PC버전 접속시 자동으로 모바일로 이동된다. /extend/g4m.config.php 파일 참고. if($_GET['from'] == 'pc'){ set_session("frommoblie", ""); } include_once './_head.php'; // 최신글 $sql = " select bo_table, bo_subject,bo_m_latest_skin from {$g4['board_table']} where bo_m_use='1' order by gr_id, bo_m_sort, bo_table "; $result = sql_query($sql); for ($i = 0; $row = sql_fetch_array($result); $i++) { echo g4m_latest($row['bo_m_latest_skin'], $row['bo_table']); } include_once './_tail.php'; ?>
typeofb/SmartTongsin
m/index.php
PHP
gpl-2.0
690
#ifndef MATRIX_SPMATRIX_H #define MATRIX_SPMATRIX_H #include "dgeMatrix.h" #include "R_ext/Lapack.h" SEXP dspMatrix_validate(SEXP obj); double get_norm_sp(SEXP obj, const char *typstr); SEXP dspMatrix_norm(SEXP obj, SEXP type); SEXP dspMatrix_rcond(SEXP obj, SEXP type); SEXP dspMatrix_solve(SEXP a); SEXP dspMatrix_matrix_solve(SEXP a, SEXP b); SEXP dspMatrix_getDiag(SEXP x); SEXP lspMatrix_getDiag(SEXP x); SEXP dspMatrix_setDiag(SEXP x, SEXP d); SEXP lspMatrix_setDiag(SEXP x, SEXP d); SEXP dspMatrix_as_dsyMatrix(SEXP from); SEXP dspMatrix_matrix_mm(SEXP a, SEXP b); SEXP dspMatrix_trf(SEXP x); #endif
cxxr-devel/cxxr-svn-mirror
src/library/Recommended/Matrix/src/dspMatrix.h
C
gpl-2.0
610