code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
require 'cj4r/drivers/daily_publisher_commission.rb'
require 'cj4r/drivers/daily_publisher_commission_mapping_registry.rb'
class PublisherCommissionServicePortType < ::SOAP::RPC::Driver
DefaultEndpointUrl = "https://pubcommission.api.cj.com/services/publisherCommissionService"
Methods = [
[ "",
"findPublisherCommissions",
[ ["in", "parameters", ["::SOAP::SOAPElement", "http://api.cj.com", "findPublisherCommissions"]],
["out", "parameters", ["::SOAP::SOAPElement", "http://api.cj.com", "findPublisherCommissionsResponse"]] ],
{ :request_style => :document, :request_use => :literal,
:response_style => :document, :response_use => :literal,
:faults => {} }
],
[ "",
"findPublisherCommissionDetails",
[ ["in", "parameters", ["::SOAP::SOAPElement", "http://api.cj.com", "findPublisherCommissionDetails"]],
["out", "parameters", ["::SOAP::SOAPElement", "http://api.cj.com", "findPublisherCommissionDetailsResponse"]] ],
{ :request_style => :document, :request_use => :literal,
:response_style => :document, :response_use => :literal,
:faults => {} }
]
]
def initialize(endpoint_url = nil)
endpoint_url ||= DefaultEndpointUrl
super(endpoint_url, nil)
self.mapping_registry = DefaultMappingRegistry::EncodedRegistry
self.literal_mapping_registry = DefaultMappingRegistry::LiteralRegistry
init_methods
end
private
def init_methods
Methods.each do |definitions|
opt = definitions.last
if opt[:request_style] == :document
add_document_operation(*definitions)
else
add_rpc_operation(*definitions)
qname = definitions[0]
name = definitions[2]
if qname.name != name and qname.name.capitalize == name.capitalize
::SOAP::Mapping.define_singleton_method(self, qname.name) do |*arg|
__send__(name, *arg)
end
end
end
end
end
end
|
norbauer/cj4r
|
lib/cj4r/drivers/daily_publisher_commission_driver.rb
|
Ruby
|
mit
| 1,969
|
/******************************************************************************
File: ExtCall.cpp
Description:
Implementation of the Interpreter class' generic external call primitive
methods (but see also ExternalCall.asm).
******************************************************************************/
#include "Ist.h"
#pragma code_seg(FFI_SEG)
// Prevent warning of redefinition of WIN32_LEAN_AND_MEAN in atldef.h
#define ATL_NO_LEAN_AND_MEAN
#include <atlconv.h>
#include "ObjMem.h"
#include "Interprt.h"
#include "DolphinX.h"
using namespace DolphinX;
#include "InterprtPrim.inl"
#include "InterprtProc.inl"
// Smalltalk Classes
#include "STBehavior.h"
#include "STExternal.h"
#include "STByteArray.h"
#include "STString.h"
#include "STMethod.h"
#include "STCharacter.h"
#include "STInteger.h"
#include "STFloat.h"
#include "STContext.h"
#include "STBlockClosure.h"
static AnsiStringOTE* (__fastcall *ForceNonInlineNewByteStringFromUtf16)(LPCWSTR) = &AnsiString::New;
static AnsiStringOTE* (__fastcall *ForceNonInlineNewByteStringWithLen)(const char * __restrict, size_t) = &AnsiString::New;
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Helpers for creating new structures and structure pointers.
// N.B. Requires intimate knowledge of the layout of the ExternalStructure
// subclasses!!
StructureOTE* __fastcall ExternalStructure::NewRefStruct(BehaviorOTE* classPointer, void* ptr)
{
StructureOTE* resultPointer = reinterpret_cast<StructureOTE*>(ObjectMemory::newPointerObject(classPointer));
ExternalStructure& extStruct = *resultPointer->m_location;
AddressOTE* oteAddress = ExternalAddress::New(ptr);
extStruct.m_contents = reinterpret_cast<BytesOTE*>(oteAddress);
extStruct.m_contents->m_count = 1;
return resultPointer;
}
///////////////////////////////////////////////////////////////////////////////
// Answer a new ExternalStructure pointer of the specified class with the specified pointer value
OTE* __fastcall ExternalStructure::NewPointer(BehaviorOTE* classPointer, void* ptr)
{
OTE* resultPointer;
Behavior& behavior = *classPointer->m_location;
if (behavior.isPointers())
{
resultPointer = reinterpret_cast<OTE*>(NewRefStruct(classPointer, ptr));
}
else
{
if (behavior.isIndirect())
{
AddressOTE* oteBytes = reinterpret_cast<AddressOTE*>(ObjectMemory::newByteObject<false, false>(classPointer, sizeof(uint8_t*)));
ExternalAddress* extAddress = static_cast<ExternalAddress*>(oteBytes->m_location);
extAddress->m_pointer = ptr;
resultPointer = reinterpret_cast<OTE*>(oteBytes);
}
else
{
size_t nSize = behavior.extraSpec();
BytesOTE* oteBytes = ObjectMemory::newByteObject(classPointer, nSize, ptr);
resultPointer = reinterpret_cast<OTE*>(oteBytes);
}
classPointer->countUp();
}
return resultPointer;
}
///////////////////////////////////////////////////////////////////////////////
// Answer a new ExternalStructure pointer of the specified class with the specified pointer value
OTE* __fastcall ExternalStructure::New(BehaviorOTE* classPointer, void* ptr)
{
OTE* resultPointer;
Behavior& behavior = *classPointer->m_location;
BytesOTE* bytesPointer;
auto size = behavior.extraSpec();
if (behavior.isPointers())
{
StructureOTE* otePointers = reinterpret_cast<StructureOTE*>(ObjectMemory::newPointerObject(classPointer));
ExternalStructure* extStruct = otePointers->m_location;
bytesPointer = ObjectMemory::newByteObject<false, false>(Pointers.ClassByteArray, size);
extStruct->m_contents = bytesPointer;
bytesPointer->m_count = 1;
resultPointer = reinterpret_cast<OTE*>(otePointers);
}
else
{
bytesPointer = ObjectMemory::newByteObject<false, false>(classPointer, size);
// N.B. newByteObject does not inc. ref count of class when not initializing
classPointer->countUp();
resultPointer = reinterpret_cast<OTE*>(bytesPointer);
}
VariantByteObject* bytes = bytesPointer->m_location;
memcpy(bytes->m_fields, ptr, size);
return resultPointer;
}
///////////////////////////////////////////////////////////////////////////////
// Answer a new BSTR from the specified UTF16 string
AddressOTE* __fastcall NewBSTR(const char16_t* pChars, size_t len)
{
AddressOTE* resultPointer = reinterpret_cast<AddressOTE*>(ObjectMemory::newByteObject<false, false>(Pointers.ClassBSTR, sizeof(uint8_t*)));
ExternalAddress* extAddress = resultPointer->m_location;
if (len > 0)
{
extAddress->m_pointer = reinterpret_cast<uint8_t*>(::SysAllocStringLen((const OLECHAR*)pChars, len));
resultPointer->beFinalizable();
}
else
extAddress->m_pointer = 0;
return resultPointer;
}
// Answer a new BSTR converted from the a byte string with the specified encoding
template <codepage_t CP, class TChar> static AddressOTE* __fastcall NewBSTR(const TChar* psz, size_t cch)
{
const UINT cp = CP == CP_ACP ? Interpreter::m_ansiCodePage : CP;
int cwch = cch * 2;
char16_t* buf = reinterpret_cast<char16_t*>(_malloca(cwch * 2));
cwch = ::MultiByteToWideChar(cp, 0, reinterpret_cast<LPCCH>(psz), cch, reinterpret_cast<LPWSTR>(buf), cwch);
AddressOTE* bstr = NewBSTR(buf, cwch);
_freea(buf);
return bstr;
}
AddressOTE* __fastcall NewBSTR(OTE* ote)
{
if (ote->isNullTerminated())
{
StringClass* strClass = reinterpret_cast<StringClass*>(ote->m_oteClass->m_location);
switch (strClass->Encoding)
{
case StringEncoding::Ansi:
return NewBSTR<CP_ACP, AnsiString::CU>(reinterpret_cast<AnsiStringOTE*>(ote)->m_location->m_characters, ote->getSize());
case StringEncoding::Utf8:
return NewBSTR<CP_UTF8, Utf8String::CU>(reinterpret_cast<Utf8StringOTE*>(ote)->m_location->m_characters, ote->getSize());
case StringEncoding::Utf16:
return NewBSTR(reinterpret_cast<Utf16StringOTE*>(ote)->m_location->m_characters, ote->getSize() / sizeof(Utf16String::CU));
case StringEncoding::Utf32:
return nullptr;
default:
// Unrecognised encoding
__assume(false);
break;
}
}
return nullptr;
}
///////////////////////////////////////////////////////////////////////////////
// Answer a new wide string converted from any othre type of string
// Used for lpwstr arguments
Utf16StringOTE* __fastcall ST::Utf16String::New(OTE* oteString)
{
ASSERT(oteString->isNullTerminated());
switch (oteString->m_oteClass->m_location->m_instanceSpec.m_encoding)
{
case StringEncoding::Ansi:
return Utf16String::New<CP_ACP>(reinterpret_cast<const AnsiStringOTE*>(oteString)->m_location->m_characters, oteString->getSize());
case StringEncoding::Utf8:
return Utf16String::New<CP_UTF8>(reinterpret_cast<const Utf8StringOTE*>(oteString)->m_location->m_characters, oteString->getSize());
case StringEncoding::Utf16:
ASSERT(FALSE);
return reinterpret_cast<Utf16StringOTE*>(oteString);
case StringEncoding::Utf32:
// TODO: Implement conversion for UTF-32
return nullptr;
default:
__assume(false);
break;
}
return nullptr;
}
///////////////////////////////////////////////////////////////////////////////
//
inline void Interpreter::push(LPCWSTR pStr)
{
if (pStr)
{
pushNewObject((OTE*)ST::Utf16String::New(pStr));
}
else
pushNil();
}
BytesOTE* __fastcall NewGUID(GUID* rguid)
{
return ObjectMemory::newByteObject(Pointers.ClassGUID, sizeof(GUID), rguid);
}
FARPROC Interpreter::GetDllCallProcAddress(DolphinX::ExternalMethodDescriptor* descriptor, LibraryOTE* oteReceiver)
{
HMODULE hModule = static_cast<HMODULE>(oteReceiver->m_location->m_handle->m_location->m_handle);
LPCSTR procName = reinterpret_cast<LPCSTR>(descriptor->m_descriptor.m_args + descriptor->m_descriptor.m_argsLen);
int ordinal = atoi(procName);
if (ordinal != 0)
{
procName = reinterpret_cast<LPCSTR>(ordinal);
}
FARPROC proc = ::GetProcAddress(hModule, procName);
descriptor->m_proc = proc;
return proc;
}
///////////////////////////////////////////////////////////////////////////////
//
argcount_t Interpreter::pushArgsAt(const ExternalDescriptor* descriptor, uint8_t* lpParms)
{
DescriptorOTE* oteTypes = descriptor->m_descriptor;
const DescriptorBytes* types = oteTypes->m_location;
const auto argsLen = types->argsLen(oteTypes);
auto i=0u;
while (i<argsLen)
{
uint8_t arg = types->m_args[i++];
// Similar to primitiveDLL32Call return values, but VOID is not supported as a parameter type
switch(ExtCallArgType(arg))
{
case ExtCallArgType::Void: // Not a valid argument
HARDASSERT(FALSE);
pushNil();
lpParms += sizeof(uintptr_t);
break;
case ExtCallArgType::LPVoid:
pushNewObject((OTE*)ExternalAddress::New(*(uint8_t**)lpParms));
lpParms += sizeof(uint8_t*);
break;
case ExtCallArgType::Char:
pushObject((OTE*)Character::NewUnicode(*reinterpret_cast<char32_t*>(lpParms)));
lpParms += sizeof(uintptr_t);
break;
case ExtCallArgType::UInt8:
pushSmallInteger(*lpParms);
lpParms += sizeof(uintptr_t);
break;
case ExtCallArgType::Int8:
pushSmallInteger(*reinterpret_cast<char*>(lpParms));
lpParms += sizeof(uintptr_t);
break;
case ExtCallArgType::UInt16:
pushSmallInteger(*reinterpret_cast<uint16_t*>(lpParms));
lpParms += sizeof(uintptr_t);
break;
case ExtCallArgType::Int16:
pushSmallInteger(*reinterpret_cast<int16_t*>(lpParms));
lpParms += sizeof(uintptr_t);
break;
case ExtCallArgType::UInt32:
pushUint32(*reinterpret_cast<uint32_t*>(lpParms));
lpParms += sizeof(uintptr_t);
break;
case ExtCallArgType::Int32:
case ExtCallArgType::HResult:
case ExtCallArgType::NTStatus:
pushInt32(*reinterpret_cast<int32_t*>(lpParms));
lpParms += sizeof(uintptr_t);
break;
case ExtCallArgType::Bool:
pushBool(*reinterpret_cast<BOOL*>(lpParms));
lpParms += sizeof(uintptr_t);
break;
case ExtCallArgType::Handle:
pushHandle(*reinterpret_cast<HANDLE*>(lpParms));
lpParms += sizeof(uintptr_t);
break;
case ExtCallArgType::Double:
push(*reinterpret_cast<double*>(lpParms));
// Yup, even doubles passed on main stack
lpParms += sizeof(DOUBLE);
break;
case ExtCallArgType::LPStr:
push(*reinterpret_cast<LPCSTR*>(lpParms));
lpParms += sizeof(uintptr_t);
break;
case ExtCallArgType::Oop:
case ExtCallArgType::Ote:
push(*reinterpret_cast<Oop*>(lpParms));
lpParms += sizeof(uintptr_t);
break;
case ExtCallArgType::Float:
push(static_cast<double>(*reinterpret_cast<float*>(lpParms)));
// Yup, even floats passed on main stack
lpParms += sizeof(uintptr_t);
break;
case ExtCallArgType::LPPVoid:
// Push an LPVOID* instance onto the stack
pushNewObject(ExternalStructure::NewPointer(Pointers.ClassLPVOID, *(uint8_t**)lpParms));
lpParms += sizeof(uint8_t*);
break;
case ExtCallArgType::LPWStr:
push(*reinterpret_cast<LPWSTR*>(lpParms));
lpParms += sizeof(LPWSTR);
break;
case ExtCallArgType::UInt64:
push(Integer::NewUnsigned64(*reinterpret_cast<uint64_t*>(lpParms)));
lpParms += sizeof(uint64_t);
break;
case ExtCallArgType::Int64:
push(Integer::NewSigned64(*reinterpret_cast<int64_t*>(lpParms)));
lpParms += sizeof(int64_t);
break;
case ExtCallArgType::Bstr:
push(*reinterpret_cast<LPWSTR*>(lpParms));
lpParms += sizeof(BSTR);
break;
case ExtCallArgType::Variant:
pushNewObject(ExternalStructure::New(Pointers.ClassVARIANT, lpParms));
lpParms += sizeof(VARIANT);
break;
case ExtCallArgType::Date:
pushNewObject(ExternalStructure::New(Pointers.ClassDATE, lpParms));
lpParms += sizeof(DATE);
break;
case ExtCallArgType::VarBool:
pushBool(*reinterpret_cast<VARIANT_BOOL*>(lpParms));
lpParms += sizeof(uintptr_t);
break;
case ExtCallArgType::Guid:
pushNewObject((OTE*)NewGUID(reinterpret_cast<GUID*>(lpParms)));
lpParms += sizeof(GUID);
break;
case ExtCallArgType::UIntPtr:
pushUintPtr(*reinterpret_cast<UINT_PTR*>(lpParms));
lpParms += sizeof(UINT_PTR);
break;
case ExtCallArgType::IntPtr:
pushIntPtr(*reinterpret_cast<INT_PTR*>(lpParms));
lpParms += sizeof(INT_PTR);
break;
case ExtCallArgType::Struct:
{
arg = types->m_args[i++];
BehaviorOTE* behaviorPointer = reinterpret_cast<BehaviorOTE*>(descriptor->m_literals[arg]);
pushNewObject(ExternalStructure::New(behaviorPointer, lpParms));
lpParms += behaviorPointer->m_location->extraSpec();
}
break;
case ExtCallArgType::Struct32:
{
arg = types->m_args[i++];
BehaviorOTE* behaviorPointer = reinterpret_cast<BehaviorOTE*>(descriptor->m_literals[arg]);
pushNewObject(ExternalStructure::New(behaviorPointer, lpParms));
lpParms += sizeof(uintptr_t);
}
break;
case ExtCallArgType::Struct64:
{
arg = types->m_args[i++];
BehaviorOTE* behaviorPointer = reinterpret_cast<BehaviorOTE*>(descriptor->m_literals[arg]);
pushNewObject(ExternalStructure::New(behaviorPointer, lpParms));
lpParms += 8;
}
break;
case ExtCallArgType::LPStruct:
{
arg = types->m_args[i++];
BehaviorOTE* behaviorPointer = reinterpret_cast<BehaviorOTE*>(descriptor->m_literals[arg]);
pushNewObject(ExternalStructure::NewPointer(behaviorPointer, *(uint8_t**)lpParms));
lpParms += sizeof(uint8_t*);
}
break;
case ExtCallArgType::LPPStruct: // Not a valid argument
arg = types->m_args[i++];
pushNewObject(ExternalStructure::NewPointer(Pointers.ClassLPVOID, *(uint8_t**)lpParms));
lpParms += sizeof(uint8_t*);
break;
case ExtCallArgType::ComPtr:
{
arg = types->m_args[i++];
IUnknown* punk = *(IUnknown**)lpParms;
BehaviorOTE* behaviorPointer = reinterpret_cast<BehaviorOTE*>(descriptor->m_literals[arg]);
StructureOTE* oteUnknown = ExternalStructure::NewRefStruct(behaviorPointer, punk);
if (punk != NULL)
{
punk->AddRef();
oteUnknown->beFinalizable();
}
pushNewObject((OTE*)oteUnknown);
lpParms += sizeof(IUnknown*);
}
break;
default:
__assume(false);
}
}
return types->m_argumentCount;
}
///////////////////////////////////////////////////////////////////////////////
//
Oop* __fastcall Interpreter::primitivePerformWithArgsAt(Oop* const sp, primargcount_t)
{
Oop oopDescriptor = *sp;
if (ObjectMemoryIsIntegerObject(oopDescriptor))
return primitiveFailure(_PrimitiveFailureCode::InvalidParameter3);
OTE* descriptorPointer = reinterpret_cast<OTE*>(oopDescriptor);
if (descriptorPointer->isBytes())
return primitiveFailure(_PrimitiveFailureCode::InvalidParameter3);
Oop oopSelector = *(sp-2);
if (ObjectMemoryIsIntegerObject(oopSelector))
return primitiveFailure(_PrimitiveFailureCode::InvalidParameter1);
TODO("Should really check that it is actually a symbol?");
SymbolOTE* selectorPointer = reinterpret_cast<SymbolOTE*>(oopSelector);
// Decode the address argument
Oop oopAddress = *(sp-1);
uint8_t* lpParms;
if (ObjectMemoryIsIntegerObject(oopAddress))
lpParms = reinterpret_cast<uint8_t*>(ObjectMemoryIntegerValueOf(oopAddress));
else
{
OTE* args = reinterpret_cast<OTE*>(oopAddress);
if (args->isPointers())
return primitiveFailure(_PrimitiveFailureCode::InvalidParameter2);
else
{
lpParms = static_cast<uint8_t*>(static_cast<ExternalAddress*>(args->m_location)->m_pointer);
}
}
// Pop the descriptor and address and the selector
m_registers.m_stackPointer = sp - 3;
argcount_t argCount;
// NEW FORMAT
ExternalDescriptor* descriptor = static_cast<ExternalDescriptor*>(descriptorPointer->m_location);
argCount = pushArgsAt(descriptor, lpParms);
// Now we can throw away the descriptor
sendSelectorArgumentCount(selectorPointer, argCount);
return primitiveSuccess(0);
}
///////////////////////////////////////////////////////////////////////////////
// N.B. THIS IS VERY SIMILAR TO primitiveValueWithArgs()!
Oop* __fastcall Interpreter::primitiveValueWithArgsAt(Oop* const sp, primargcount_t)
{
Oop oopDescriptor = *sp;
if (ObjectMemoryIsIntegerObject(oopDescriptor))
return primitiveFailure(_PrimitiveFailureCode::InvalidParameter2);
OTE* descriptorPointer = reinterpret_cast<OTE*>(oopDescriptor);
if (descriptorPointer->isBytes())
return primitiveFailure(_PrimitiveFailureCode::InvalidParameter2);
Oop argPointer = *(sp-1);
uint8_t* lpParms;
if (ObjectMemoryIsIntegerObject(argPointer))
lpParms = reinterpret_cast<uint8_t*>(ObjectMemoryIntegerValueOf(argPointer));
else
{
OTE* args = reinterpret_cast<OTE*>(argPointer);
if (args->isPointers())
return primitiveFailure(_PrimitiveFailureCode::InvalidParameter1);
else
lpParms = static_cast<uint8_t*>(static_cast<ExternalAddress*>(args->m_location)->m_pointer);
}
BlockOTE* oteBlock = reinterpret_cast<BlockOTE*>(*(sp-2));
HARDASSERT(ObjectMemory::fetchClassOf(Oop(oteBlock)) == Pointers.ClassBlockClosure);
BlockClosure* block = oteBlock->m_location;
const auto blockArgumentCount = block->m_info.argumentCount;
const ExternalDescriptor* descriptor = static_cast<ExternalDescriptor*>(descriptorPointer->m_location);
const DescriptorBytes* types = static_cast<DescriptorBytes*>(descriptor->m_descriptor->m_location);
const auto argCount = types->m_argumentCount;
if (argCount != blockArgumentCount)
return primitiveFailure(_PrimitiveFailureCode::WrongNumberOfArgs);
// Pop off args and receiver block.
m_registers.m_stackPointer = sp - 3;
// Store old context details from interpreter registers
m_registers.StoreContextRegisters();
push(block->m_receiver); // Note that this overwrites the block itself
// BP of new frame points at first arg
Oop* bp = m_registers.m_stackPointer+1;
// With new block closures, args must be on the stack immediate after receiver (i.e. at BP)
pushArgsAt(descriptor, lpParms);
Oop* localSp = m_registers.m_stackPointer + 1;
const auto copiedValues = block->copiedValuesCount(oteBlock);
{
for (auto i=0u;i<copiedValues;i++)
{
Oop oopCopied = block->m_copiedValues[i];
*localSp++ = oopCopied;
}
}
const auto extraTemps = block->stackTempsCount();
{
const Oop nilPointer = Oop(Pointers.Nil);
for (auto i=0u;i<extraTemps;i++)
*localSp++ = nilPointer;
}
// Stack frame follows args...
StackFrame* pFrame = reinterpret_cast<StackFrame*>(localSp);
m_registers.m_stackPointer = reinterpret_cast<Oop*>(reinterpret_cast<uint8_t*>(pFrame)+sizeof(StackFrame)) - 1;
pFrame->m_caller = m_registers.activeFrameOop(); // This overwrites receiver in stack, ref. count used for m_base
// We don't need to store down correct IP and SP into the frame until it is suspended,
// but we do need to initialize the slots so they don't contain old garbage
pFrame->m_ip = ZeroPointer;
pFrame->m_sp = ZeroPointer;
HARDASSERT(ObjectMemory::isKindOf(block->m_method, Pointers.ClassCompiledMethod));
pFrame->m_method = block->m_method;
// Note that ref. count remains the same due to overwritten receiver slot
const auto envTemps = block->envTempsCount();
if (envTemps > 0)
{
ContextOTE* oteContext = Context::New(envTemps, reinterpret_cast<Oop>(block->m_outer));
pFrame->m_environment = reinterpret_cast<Oop>(oteContext);
Context* context = oteContext->m_location;
context->m_block = oteBlock;
oteBlock->countUp();
}
else
pFrame->m_environment = reinterpret_cast<Oop>(oteBlock);
pFrame->m_bp = reinterpret_cast<Oop>(bp)+1;
m_registers.m_basePointer = bp;
CompiledMethod* pMethod = pFrame->m_method->m_location;
m_registers.m_pMethod = pMethod;
m_registers.m_instructionPointer = ObjectMemory::ByteAddressOfObjectContents(pMethod->m_byteCodes) +
block->initialIP() - 1;
m_registers.m_pActiveFrame = pFrame;
return m_registers.m_stackPointer;
}
///////////////////////////////////////////////////////////////////////////////
//
#ifdef _DEBUG
// Some test functions
extern "C" {
__declspec(dllexport) uint32_t __stdcall answerArg(uint32_t intParm)
{
return intParm;
}
__declspec(dllexport) float __stdcall answerFloatFromDouble(double fParm)
{
return static_cast<float>(fParm);
}
__declspec(dllexport) float __stdcall answerFloatFromFloat(float fParm)
{
return fParm;
}
__declspec(dllexport) double __stdcall answerDoubleFromInt(int32_t intParm)
{
return intParm;
}
__declspec(dllexport) double __stdcall addDoubles(double parm1, double parm2)
{
return parm1 + parm2;
}
__declspec(dllexport) double __stdcall incDouble(double parm1)
{
double blah = addDoubles(parm1, 1.0);
return blah;
}
};
#endif
/*
// Debug example for returning struct by value
struct Blah
{
int32_t a;
int32_t b;
int32_t c;
};
extern "C" __declspec(dllexport) Blah __stdcall makeBlah(int32_t a, int32_t b, int32_t c)
{
Blah answer;
answer.a = a;
answer.b = b;
answer.c = c;
return answer;
}
void doBlah()
{
Blah x = makeBlah(1, 2, 3);
printf("%d %d %d", x.a, x.b, x.c);
}
*/
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// CPP Implementation (with inline assembler)
// N.B. THESE ARE NOT UP TO DATE WITH THE VERSIONS IN ExternalCall.asm
//
///////////////////////////////////////////////////////////////////////////////
#ifndef _M_IX86
extern "C" BOOL __stdcall callExternalFunction(FARPROC pProc, argcount_t argCount, uint8_t* argTypes, BOOL isVirtual);
BOOL __fastcall Interpreter::primitiveVirtualCall(Oop* const sp, primargcount_t argCount)
{
// Calling out may initiate a callback to Smalltalk
// We need to ensure that this primitive is reentrant so we
// save any cached registers of the interpreter.
//
CompiledMethod& method = *m_registers.m_oopNewMethod->m_location;
OTE* objectPointer = *(sp - argCount);
#ifdef _DEBUG
// SmallIntegers are not valid receivers
if (ObjectMemoryIsIntegerObject(objectPointer))
return primitiveFailure(0); // invalid receiver
#endif
if (ote->isPointers())
{
// If a pointer object, may be OK if the first byte is a byte object >= 4 bytes
objectPointer = static_cast<VariantObject*>(ote->m_location)->m_fields[0];
if (ObjectMemory::isPointers(objectPointer))
return primitiveFailure(0); // invalid receiver
}
ByteArray* receiverBytes = reinterpretcast<ByteArray*>(ote->m_location);
if (ObjectMemory::fetchByteLengthOf(receiverBytes) < 4)
return primitiveFailure(0); // invalid receiver
uint8_t* thisPointer;
if (ObjectMemory::isIndirect(receiverBytes.m_class))
{
thisPointer = static_cast<ExternalAddress*>(receiverBytes)->m_pointer;
}
else
thisPointer = receiverBytes.m_elements;
// We must leave arguments on the stack until after the call to
// ensure that any callbacks to Smalltalk don't overwrite them
// prematurely.
//
OTE* arrayPointer = method.m_aLiterals[LibCallArgArray];
ByteArray* argTypes = static_cast<ByteArray*>(arrayPointer->m_location);
// Compiler should have generated a literal array of argument types
ASSERT(arrayPointer->isNil() || argTypes->m_class == Pointers.ClassByteArray);
FARPROC pVirtualProc = reinterpret_cast<FARPROC*>(reinterpret_cast<uintptr_t*>(thisPointer)->[argTypes->m_elements[VirtualCallOffset]]);
return ::callExternalFunction(pVirtualProc, argCount, argTypes->m_elements, TRUE);
}
// Compiler generates a special literal frame for this special primitive. The first literal
// is a byte array containing:
//
// 0..3 Proc address cache (may not be used)
// 4 calling convention (#stdcall, #api, #pascal, #c)
// 5..N Array of argument types (last is return type)
// N+1..M Symbolic name of function to be called, or ordinal number
//
// This primitive does not check that enough types are specified, because it
// assumes that the compiler does this.
//
BOOL __fastcall Interpreter::primitiveDLL32Call(Oop* const sp, primargcount_t argCount)
{
CompiledMethod& method = *m_registers.m_oopNewMethod->m_location;
// Calling out may initiate a callback to Smalltalk
// We need to ensure that this primitive is reentrant so we
// save any cached registers of the interpreter.
//
// We must leave arguments on the stack until after the call to
// ensure that any callbacks to Smalltalk don't overwrite them
// prematurely.
//
Oop arrayPointer = method.m_aLiterals[LibCallArgArray];
ByteArray* argTypes = static_cast<ByteArray*>(ObjectMemory::GetObj(arrayPointer));
// Compiler should have generated a literal array of argument types
ASSERT(arrayPointer->isNil() || argTypes.m_class == Pointers.ClassByteArray);
// Try the cached address
FARPROC pLibProc = *reinterpret_cast<FARPROC*>(argTypes.m_elements);
if (!pLibProc)
{
size_t procNameOffset = argCount+ExtCallArgStart;
#ifdef _DEBUG
// Compiler should have ensured number of arg types = argumentCount
size_t argsLength = ObjectMemory::fetchByteLengthOf(arrayPointer);
ASSERT(argsLength > procNameOffset);
// Compiler allocates space for a null terminator
ASSERT(argTypes.m_elements[argsLength-1] == 0);
#endif
char* procName = reinterpret_cast<char*>(argTypes.m_elements)+procNameOffset;
OTE* handlePointer = *(sp - argCount);
ASSERT(!ObjectMemory::isBytes(handlePointer));
handlePointer = reinterpret_cast<OTE*>(ObjectMemory::fetchPointerOfObject(0, handlePointer));
HMODULE hModule = static_cast<HMODULE>((static_cast<ExternalHandle*>(handlePointer->m_location)->m_handle);
// Compiler generates string for ordinals too
unsigned ordinal = atoi(procName);
pLibProc = ::GetProcAddress(hModule, ordinal?(LPCSTR)ordinal:procName);
// Cache the value back in the method for later use
*reinterpret_cast<FARPROC*>(argTypes.m_elements) = pLibProc;
}
if (pLibProc)
{
TODO("Implement thiscall and fastcall");
ASSERT(argTypes.m_elements[ExtCallConvention] < ExtCallThisCall);
//TRACE((char*)(argTypes).m_elements+argCount+6); TRACESTREAM<< L"\n";
return ::callExternalFunction(pLibProc, argCount, argTypes.m_elements, FALSE);
}
else
return primitiveFailure(1); // procedure not found
}
// Returns true/false for success/failure. Also sets the failure code.
BOOL __stdcall Interpreter::callExternalFunction(FARPROC pProc, argcount_t argCount, uint8_t* argTypes, BOOL isVirtual)
{
Oop arg;
uintptr_t retValue;
TODO("Rewrite the whole lot in assembler for speed")
TODO("Fix all the sign extension stuff")
// Compiler optimises out unless we pretend its volatile
StackFrame volatile* pCallingFrame = (StackFrame volatile*)m_pActiveFrame;
uintptr_t savedSP;
_asm {
mov eax, esp
mov DWORD PTR[savedSP], eax
}
size_t pushCount = argCount + isVirtual - 1;
Oop* stackPointer = m_stackPointer - pushCount;
// Push args from Smalltalk stack onto machine stack
for (auto i = pushCount;i >= 0;i--)
{
arg = stackPointer[i];
switch (argTypes[ExtCallArgStart+i])
{
case ExtCallArgVOID:
// Compiler should not generate this
goto preCallFail;
case ExtCallArgLPSTR:
_asm
{
mov eax, DWORD PTR [arg] // Load Oop
test al, 1 // Is it a SmallInteger?
jnz preCallFail // Yes? an error
//jz skipZero
//cmp eax, 1
//je integerPointer
//jmp preCallFail
//skipZero:
test BYTE PTR([eax].m_flags), 2 // Is it a pointer object?
jnz tryNil // Yes, OK only if Nil object
mov ecx, [eax].m_oteClass // Load the class Oop
mov eax, [eax].m_location // Load object pointer
add eax, sizeof(Object) // Skip the object header
cmp ecx, [Pointers.ClassByteString]
jne preCallFail // Not a String? an error
push eax // Push pointer to object data
}
break;
case ExtCallArgLPVOID:
_asm
{
mov eax, DWORD PTR [arg] // Load Oop
test al, 1 // Is it a SmallInteger?
jnz integerPointer // Yes, try as pointer
test BYTE PTR([eax].m_flags), 2 // Is it a pointer object?
jz pushByteObjectAddress // No, skip handling for ExternalStructures
cmp eax, [Pointers.Nil] // Is it nil?
je pushNil // Yes, then push 0 and continue
mov eax, [eax].m_location // Load pointer to object
cmp [eax].m_size, sizeof(Object)+sizeof(Oop) // Byte Length of at least 12?
jl preCallFail // No, not valid
mov eax, DWORD PTR [eax+sizeof(Object)] // Load Oop of first inst var
test al, 1 // Is the first inst var a SmallInteger
jnz integerPointer // Yes
test BYTE PTR([eax].m_flags), 2 // Is it a pointer object?
jnz preCallFail // If still pointer object, then fail it
pushByteObjectAddress:
mov ecx, [eax].m_oteClass // Load the class Oop
mov eax, [eax].m_location // Load object pointer
add eax, sizeof(Object) // Skip the object header
mov ecx, [ecx].m_location // Load address of class object
TODO("YUCK, makes difficult to change - do some other way")
test BYTE PTR[ecx].m_instanceSpec+3, 0x10 // Test indirection bit
jz skipIndirection
mov eax, [eax] // Object contains an address so deref it
skipIndirection:
push eax // Push pointer to object data
}
continue;
integerPointer:
_asm
{
sar eax, 1
push eax
}
break;
case ExtCallArgCHAR:
_asm
{
mov eax, DWORD PTR [arg] // Load Oop
test al, 1 // Is it a SmallInteger?
jnz preCallFail // Yes, no good
mov ecx, [eax].m_oteClass // Load the class Oop
mov eax, [eax].m_location // Load object pointer
cmp ecx, [Pointers.ClassCharacter]
jne preCallFail // Not a character
mov eax, [eax].m_codePoint // Load ascii value of char (SmallInteger)
sar eax, 1 // Convert to SmallInteger
push eax
}
break;
case ExtCallArgBYTE:
_asm
{
mov eax, DWORD PTR [arg] // Load Oop
test al, 1 // Is it a SmallInteger?
jz preCallFail
sar eax, 1
cmp eax, 0xFF
ja preCallFail // Fail if above 16rFF (unsigned comparison)
push eax
}
break;
case ExtCallArgSBYTE:
_asm
{
mov eax, DWORD PTR [arg] // Load Oop
test al, 1 // Is it a SmallInteger?
jz preCallFail
sar eax, 1
cmp eax, 127
jg preCallFail // Fail if > 127 (signed comparison)
cmp eax, -128
jl preCallFail
and eax, 0xFF
push eax
}
break;
case ExtCallArgWORD:
_asm
{
mov eax, DWORD PTR [arg] // Load Oop
test al, 1 // Is it a SmallInteger?
jz wordFromBytes // No
sar eax, 1
and eax, 0xFFFF
push eax
}
continue;
wordFromBytes:
_asm {
test BYTE PTR([eax].m_flags), 2 // Is it a pointer object?
jnz tryNil // Yes, no good unless nil
mov eax, [eax].m_location // Load address of object
cmp [eax].m_size, sizeof(Object)+2 // Byte Length of 2?
jne preCallFail // No, no good
movzx eax, WORD PTR[eax+sizeof(Object)] // Load first word after header (zero extend)
push eax
}
break;
case ExtCallArgSWORD:
_asm
{
mov eax, DWORD PTR [arg] // Load Oop
test al, 1 // Is it a SmallInteger?
jz swordFromBytes // No
sar eax, 1
and eax, 0xFFFF
push eax
}
continue;
swordFromBytes:
_asm {
test BYTE PTR[eax+4], 2 // Is it a pointer object?
jnz tryNil // Yes, no good
mov eax, [eax].m_location // Load address of object
cmp [eax].m_size, sizeof(Object)+2 // Byte Length of 2?
jne preCallFail // No, no good
movsx eax, WORD PTR[eax+sizeof(Object)] // Load first word after header (sign extend)
push eax
}
break;
case ExtCallArgHANDLE:
case ExtCallArgSDWORD:
case ExtCallArgDWORD:
case ExtCallArgHRESULT:
case ExtCallArgNTSTATUS:
_asm
{
mov eax, DWORD PTR [arg] // Load Oop
test al, 1 // Is it a SmallInteger?
jz dwordFromBytes // No
sar eax, 1
push eax
}
continue;
dwordFromBytes:
_asm {
test BYTE PTR([eax].m_flags), 2 // Is it a pointer object?
jnz tryNil // Yes, but might be nil
mov eax, [eax].m_location // Load address of object
cmp [eax].m_size, sizeof(Object)+4 // Byte Length of 4?
jne preCallFail // No, no good
mov eax, DWORD PTR[eax+sizeof(Object)] // Load first word after header (zero extend)
push eax
}
continue;
tryNil:
_asm cmp eax, [Pointers.Nil]
_asm jne preCallFail
pushNil:
_asm push 0x00000000
break;
case ExtCallArgBOOL:
_asm
{
mov eax, DWORD PTR [arg] // Load Oop
test al, 1 // Is it a SmallInteger?
jz tryTrue // No
sar eax, 1 // Convert to machine representation
push eax // and push it
}
continue;
tryTrue:
_asm
{
cmp eax, DWORD PTR [Pointers.True]
jne tryFalse
push 0x00000001 // True value is 1
}
continue;
tryFalse:
_asm {
cmp eax, DWORD PTR [Pointers.False]
jne preCallFail // Neither true nor false, so fail
push 0x00000000 // False value is 0
}
break;
case ExtCallArgOOP:
_asm
{
mov eax, DWORD PTR[arg]
push eax
}
break;
case ExtCallArgDATE:
case ExtCallArgDOUBLE:
_asm
{
//inc [dwordsToPop]
mov eax, DWORD PTR[arg]
test al, 1 // SmallInteger?
jz pushDouble // No
sar eax, 1 // Convert to machine representation
mov DWORD PTR[arg], eax
fild DWORD PTR[arg]
sub esp, 8
fstp QWORD PTR [esp]
}
continue;
pushDouble:
_asm {
mov edx, [eax].m_oteClass // Load class of object
mov eax, [eax].m_location // Load address of object
cmp edx, [Pointers.ClassFloat] // Is it a Float
jne preCallFail // No
mov edx, DWORD PTR[eax+sizeof(Object)+4] // Load second dword after header
push edx
mov edx, DWORD PTR[eax+sizeof(Object)] // Load first dword after header
push edx
}
break;
case ExtCallArgFLOAT:
_asm
{
mov eax, DWORD PTR[arg]
test al, 1 // SmallInteger?
jz pushFloat // No
sar eax, 1 // Convert to machine representation
mov DWORD PTR[arg], eax
fild DWORD PTR[arg]
sub esp, 4
fstp DWORD PTR [esp]
}
continue;
pushFloat:
_asm {
mov edx, [eax].m_oteClass // Load class of object
mov eax, [eax].m_location // Load address of object
cmp edx, [Pointers.ClassFloat] // Is it a Float
jne preCallFail // No
fld QWORD PTR[eax+sizeof(Object)]
sub esp, 4
fstp DWORD PTR[esp]
}
break;
case ExtCallArgLPPVOID:
_asm {
mov eax, DWORD PTR [arg] // Load Oop
test al, 1 // Is it a SmallInteger?
jnz preCallFail // Yes, fail it
test BYTE PTR([eax].m_flags), 2 // Is it a pointer object?
jz pushAddress // No, skip handling for ExternalStructures
mov eax, [eax].m_location // Load pointer to object
cmp [eax], sizeof(Object)+4 // Byte Length of at least 12?
jl preCallFail // No, not valid
mov eax, DWORD PTR [eax+sizeof(Object)] // Load Oop of first inst var
test al, 1 // Is the first inst var a SmallInteger
jnz preCallFail // Yes, fail it
test BYTE PTR([eax].m_flags), 2 // Is the first inst var a pointer object
jnz preCallFail // If still pointer object, then fail it
pushAddress:
mov ecx, [eax].m_oteClass // Load the class Oop
mov eax, [eax].m_location // Load object pointer
add eax, sizeof(Object) // Skip the object header
mov ecx, [ecx].m_location // Load address of class object
TODO("YUCK, makes difficult to change - do some other way")
test BYTE PTR[ecx].m_instanceSpec+3, 0x10 // Test indirection bit
jz preCallFail // only ExternalAddress acceptable
push eax // Push pointer to object data
}
break;
default:
// Unsupported type
goto preCallFail;
}
}
// Do the call and store the result.
// Note that the arguments are left on the stack for the duration of the call
// to prevent a recursive invocation overwriting them and causing them to be
// deallocated and also in case of a GP fault in the library procedure
retValue = (*pProc)();
// Reset the stack
_asm
{
mov eax, DWORD PTR[savedSP]
mov esp, eax
}
// If an error occurs during a DLL call which causes a callback to Smalltalk, then the
// Smalltalk stack may be being unwound past the return from this primitive, so we simply
// do nothing (which will allow any unwind blocks to run), otherwise we must adjust the stack
// for arguments, and push the result.
if (pCallingFrame == m_pActiveFrame)
{
#ifdef _DEBUG
stackPointer += pushCount;
if (stackPointer != m_stackPointer)
{
TRACE("primitiveDLL32Call WARNING: before call SP %p, after call SP %p\n\r", stackPointer, m_stackPointer);
const ptrdiff_t extra = m_stackPointer - stackPointer;
if (extra > 0)
{
for (auto i=0;i<extra;i++)
{
printStackTop(m_stackPointer, TRACESTREAM);
m_stackPointer--;
}
ASSERT(m_stackPointer == stackPointer);
}
m_stackPointer = stackPointer;
}
#endif
// Place return value on Smalltalk stack.
// It may appear that the pop() to clear down the stack is common, but it isn't because
// HRESULT returns can fail the primitive at this late stage. Note also that VOID return
// value causes the method to answer self.
switch(argTypes[ExtCallReturnType])
{
case ExtCallArgLPPVOID:
// Compiler should not generate as a return type, but if it does, treat as lpvoid
case ExtCallArgLPVOID:
pop(argCount);
replaceStackTopObjectWithNewObject(NewExternalAddress(reinterpret_cast<uint8_t*>(retValue));
break;
case ExtCallArgCHAR:
pop(argCount);
replaceStackTopObjectNoRefCnt(NewChar(static_cast<char>(retValue)));
break;
case ExtCallArgBYTE:
pop(argCount);
replaceStackTopObjectNoRefCnt(ObjectMemoryIntegerObjectOf(static_cast<uint8_t>(retValue));
break;
case ExtCallArgSBYTE:
{
pop(argCount);
char signedChar = static_cast<char>(retValue);
replaceStackTopObjectNoRefCnt(ObjectMemoryIntegerObjectOf(static_cast<SmallInteger>(signedChar)));
break;
}
case ExtCallArgWORD:
pop(argCount);
replaceStackTopObjectNoRefCnt(ObjectMemoryIntegerObjectOf(static_cast<uint16_t>(retValue));
break;
case ExtCallArgSWORD:
{
pop(argCount);
int16_t signedWord = static_cast<int16_t>(retValue);
replaceStackTopObjectNoRefCnt(ObjectMemoryIntegerObjectOf(static_cast<SmallInteger>(signedWord)));
break;
}
case ExtCallArgHRESULT:
case ExtCallArgNTSTATUS:
{
HRESULT hresult = static_cast<HRESULT>(retValue);
if (FAILED(hresult))
return primitiveFailure(NewSigned(hresult)); // Fail it, leaving stack as it was
}
// Deliberately drop through, so handled same as #dword
case ExtCallArgDWORD:
pop(argCount);
replaceObjectAtStackTopWith(NewUnsigned(retValue));
break;
case ExtCallArgSDWORD:
pop(argCount);
replaceObjectAtStackTopWith(NewSigned(retValue));
break;
case ExtCallArgBOOL:
pop(argCount);
replaceStackTopObjectNoRefCnt(retValue ? Pointers.True : Pointers.False);
break;
case ExtCallArgHANDLE:
pop(argCount);
if (!dwValue)
replaceStackTopObjectNoRefCnt(Pointers.Nil);
else
replaceStackTopObjectWithNewObject(NewExternalHandle(static_cast<HANDLE>(retValue)));
break;
case ExtCallArgDATE:
case ExtCallArgDOUBLE:
case ExtCallArgFLOAT:
{
double fResult;
_asm fstp QWORD PTR [fResult]
pop(argCount);
replaceStackTopObjectWithNewObject(NewFloat(fResult));
break;
}
case ExtCallArgLPSTR:
pop(argCount);
if (!dwValue)
replaceStackTopObjectNoRefCnt(Pointers.Nil);
else
replaceStackTopObjectWithNewObject(NewString((const char*)retValue));
break;
// For future use with User Primitive Kit
case ExtCallArgOOP:
pop(argCount);
ASSERT(!ObjectMemoryIsIntegerObject(retValue));
*m_registers.m_stackPointer = dwValue;
break;
case ExtCallArgVOID:
// Do nothing - leaving receiver on stack
default:
pop(argCount);
break; // Not a valid return type
}
}
else
TRACE("Unwinding %s\n", argTypes+ExtCallArgStart+argCount);
return primitiveSuccess();
preCallFail:
// Reset the stack following failure to set up correctly
_asm
{
mov eax, DWORD PTR[savedSP]
mov esp, eax
}
return primitiveFailure(16+i);
}
#endif
|
shoshanatech/Dolphin
|
Core/DolphinVM/extcall.cpp
|
C++
|
mit
| 41,254
|
<p>You can bind our <code>NgbPagination</code> component with slicing the data list</p>
<table class="table table-striped">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Country</th>
<th scope="col">Area</th>
<th scope="col">Population</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let country of countries">
<th scope="row">{{ country.id }}</th>
<td>
<img [src]="'https://upload.wikimedia.org/wikipedia/commons/' + country.flag" class="me-2" style="width: 20px">
{{ country.name }}
</td>
<td>{{ country.area | number}}</td>
<td>{{ country.population | number }}</td>
</tr>
</tbody>
</table>
<div class="d-flex justify-content-between p-2">
<ngb-pagination [collectionSize]="collectionSize" [(page)]="page" [pageSize]="pageSize" (pageChange)="refreshCountries()">
</ngb-pagination>
<select class="form-select" style="width: auto" [(ngModel)]="pageSize" (ngModelChange)="refreshCountries()">
<option [ngValue]="2">2 items per page</option>
<option [ngValue]="4">4 items per page</option>
<option [ngValue]="6">6 items per page</option>
</select>
</div>
|
fbasso/ng-bootstrap
|
demo/src/app/components/table/demos/pagination/table-pagination.html
|
HTML
|
mit
| 1,139
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* @author Lloric Mayuga Garcia <emorickfighter@gmail.com>
*/
class Migration_Report_info extends CI_Migration
{
const CI_DB_TABLE = 'report_info';
public function __construct($config = array())
{
parent::__construct($config);
}
public function up()
{
//$this->down();
$fields = array(
'school_name' => array(
'type' => 'VARCHAR',
'constraint' => '100',
'null' => FALSE
),
'school_address' => array(
'type' => 'VARCHAR',
'constraint' => '100',
'null' => FALSE
),
'school_contact' => array(
'type' => 'VARCHAR',
'constraint' => '100',
'null' => FALSE
),
//------------------------------------
'created_at' => array(
'type' => 'INT',
'constraint' => '11',
'null' => FALSE
),
'created_user_id' => array(
'type' => 'INT',
'constraint' => '11',
'unsigned' => TRUE,
'null' => FALSE
)
);
$this->dbforge->add_field($fields);
$this->dbforge->create_table(self::CI_DB_TABLE, TRUE);
}
public function down()
{
$this->dbforge->drop_table(self::CI_DB_TABLE, TRUE);
}
}
|
lloricode/ci-capstone
|
application/migrations/20170411093534_report_info.php
|
PHP
|
mit
| 1,909
|
{{extend 'layout.html'}}
<h2>{{=response.title}}</h2>
<form method=POST>
<textarea name=sql cols=90 rows=10>{{=sql or ""}}</textarea><br>
<input type=submit value="Execute SQL">
</form>
{{
if error:
}}
<div class=error style="margin-left:0px">
{{=repr(error).replace("\n", "<br>")}}
</div>
{{
pass
if results:
txt = "<table class=\"zebra datatable tablesorter\">"
txt += "<thead>"
txt += "<tr>"
for c in columns:
txt += "<th>%s</th>" % c
pass
txt += "</tr>"
txt += "</thead>"
txt += "<tbody>"
for r in results:
txt += "<tr>"
for c in columns:
txt += "<td class=normaltext>%s</td>" % getattr(r, c)
pass
txt += "</tr>"
pass
txt += "</tbody>"
txt += "</table>"
response.write(XML(txt))
pass}}
<script>
$(document).ready(function() {
$(".tablesorter").tablesorter();
});
</script>
|
ccpgames/eve-metrics
|
web2py/applications/evemetrics/views/default/SafeSQL.html
|
HTML
|
mit
| 887
|
import Vector from '../../../../src/lib/Vector';
import Utils from '../../../../src/lib/Utils';
import Perlin from '../../../../src/lib/Perlin';
export default class FlowField {
constructor(w, h, z, resolution, source, cbInit) {
this.ctx;
this.width = w;
this.height = h;
this.field = [];
this.resolution = resolution || 10;
this.rows = Math.round(w / this.resolution);
this.cols = Math.round(h / this.resolution);
this.depth = z >= 1 ? z:1;
this.zIndex = 0;
this.mustRedraw = false;
this.isReady = false;
this.cbInit = cbInit || null;
this.initField(source);
}
pushZ() {
this.zIndex++;
if (this.zIndex >= this.depth) {
this.zIndex = 0;
}
this.mustRedraw = true;
}
lookup(vector) {
let x = vector.getX() / this.resolution;
let y = vector.getY() / this.resolution;
let col = parseInt(Utils.constrain(y, 0, this.cols-1));
let row = parseInt(Utils.constrain(x, 0, this.rows-1));
return this.field[this.zIndex][col][row].copy();
}
initField(source) {
let type = typeof source;
switch (type) {
case 'string':
if (source === 'special') {
this.gridFromSpecial();
} else {
this.gridFromImage(source);
}
break;
case 'object':
this.gridFromPerlin(source);
break;
default:
console.error("FlowField :: createField: invalid source.");
return false;
}
}
createGrid(vectors) {
if (!this.ctx) {
this.ctx = this.createCanvas();
}
this.field = vectors;
this.mustRedraw = true;
this.isReady = true;
if (typeof this.cbInit === 'function') {
this.cbInit();
}
}
gridFromImage(imageSrc) {
this.getVectorsFromImage(imageSrc, (vectors) => {
this.createGrid(vectors)
});
}
gridFromPerlin(source) {
source = source || {};
let vectors = this.getVectorsFromPerlinNoise(source.seed, source.res);
this.createGrid(vectors);
}
gridFromSpecial() {
let vectors = this.getSpecialVectors();
this.createGrid(vectors);
}
getSpecialVectors() {
let vectors = [];
for (let z=0; z<this.depth; z++) {
vectors[z] = [];
for (let i = 0; i<this.cols; i++) {
vectors[z][i] = new Array(this.rows);
for (let j = 0; j<this.rows; j++) {
let angle;
let prob = Math.random();
if (prob < 0.85) {
angle = Utils.randomRange(0.2, 0.6);
} else {
angle = Utils.randomRange(-0.9, 0.1);
}
let vector = new Vector({
x: Math.cos(angle),
y: Math.sin(angle)
});
vectors[z][i][j] = vector;
}
}
}
return vectors;
}
getVectorsFromPerlinNoise(seed, res) {
res = res || {};
res = {
x: res.x || 0.02,
y: res.y || 0.02,
z: res.z || 0.02
};
seed = seed || Math.random();
let noise = new Perlin();
noise.seed(seed);
let xOff = 0;
let yOff = 0;
let zOff = 0;
let vectors = [];
for (let z=0; z<this.depth; z++) {
vectors[z] = [];
for (let i = 0; i<this.cols; i++) {
yOff = 0;
vectors[z][i] = new Array(this.rows);
for (let j = 0; j<this.rows; j++) {
let noiseVal = noise.noise(xOff, yOff, zOff);
let angle = Utils.mapRange(noiseVal, 0, 1, -1, 1);
let vector = new Vector({
x: Math.cos(angle),
y: Math.sin(angle)
});
vectors[z][i][j] = vector;
yOff += res.y;
}
xOff += res.x;
}
zOff += res.z;
}
return vectors;
}
getVectorsFromImage(imageSrc, cb) {
let image = new Image();
image.src = imageSrc;
image.onload = function() {
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
canvas.width = this.width;
canvas.height = this.height;
document.getElementsByTagName("BODY")[0].appendChild(canvas);
ctx.drawImage(image, 0, 0);
let imageData = ctx.getImageData(0, 0, this.width, this.height);
let vectors = [[]];
for (let i=0; i<this.cols; i++) {
vectors[0][i] = new Array(this.rows);
for (let j=0; j<this.rows; j++) {
let brightness = this.imageGetBlockValue(imageData, i, j);
let angle = Utils.mapRange(brightness, 0, 255, -1, 1);
let vector = new Vector({
x: Math.cos(angle),
y: Math.sin(angle)
});
vectors[0][i][j] = vector;
}
}
cb(vectors);
}.bind(this);
}
imageGetBlockValue(imageData, col, row) {
let pixelData = 4;
let blockSize = this.resolution * pixelData;
let blockSizeSquare = this.resolution * blockSize;
let start = (col * blockSize) + row * this.width * blockSize;
let end = start + blockSize;
let nextOffset = this.cols * blockSize;
let cut = start + nextOffset * this.resolution
let acum = 0;
let y=0;
while (start < cut) {
for (let i=start; i<end; i++) {
acum += imageData.data[i];
y++;
}
start += nextOffset;
end = start + blockSize;
}
return acum / blockSizeSquare;
}
debugPaintImageBlock(imageData, col, row) {
let pixelData = 4;
let blockSize = this.resolution * pixelData;
let blockSizeSquare = this.resolution * blockSize;
let start = (col * blockSize) + row * this.width * blockSize;
let end = start + blockSize;
let nextOffset = this.cols * blockSize;
let cut = start + nextOffset*this.resolution
let acum = 0;
let y=0;
while (start < cut) {
for (let i=start; i<end; i++) {
acum += imageData.data[i];
imageData.data[i] = 255;
y++;
}
start += nextOffset;
end = start + blockSize;
}
}
drawCell(x, y, a) {
let arrowSize = this.resolution / 1.5;
let halfRes = this.resolution / 2;
let xOffset = (this.resolution - arrowSize) / 2;
let arrowColor = "#a3a3a3";
let arrowHeadSize = arrowSize * 10 / 100;
// this.ctx.lineWidth = 1;
//
// this.ctx.setLineDash([5, 15]);
// this.ctx.beginPath();
// this.ctx.rect(x, y, this.resolution , this.resolution);
// this.ctx.stroke();
// this.ctx.closePath();
this.ctx.save();
this.ctx.translate(x + halfRes, y + halfRes);
this.ctx.rotate(a);
this.ctx.setLineDash([]);
this.ctx.strokeStyle = arrowColor;
this.ctx.fillStyle = arrowColor;
this.ctx.beginPath();
this.ctx.moveTo(-(arrowSize/2), 0);
this.ctx.lineTo((arrowSize/2)-arrowHeadSize, 0);
this.ctx.closePath();
this.ctx.stroke();
this.ctx.beginPath();
this.ctx.moveTo((arrowSize/2)-arrowHeadSize, -arrowHeadSize);
this.ctx.lineTo((arrowSize/2)-arrowHeadSize, arrowHeadSize);
this.ctx.lineTo(arrowSize/2, 0);
this.ctx.closePath();
this.ctx.fill();
this.ctx.restore();
}
draw() {
if (!this.mustRedraw) {
return;
}
let x = 0;
let y = 0;
this.ctx.clearRect(0, 0, this.width, this.height);
for (let i = 0; i<this.cols; i++) {
y = i * this.resolution;
for (let j = 0; j<this.rows; j++) {
x = j * this.resolution;
let v = this.field[this.zIndex][i][j];
let angle = v.getAngle();
this.drawCell(x, y, angle);
}
}
this.mustRedraw = false;
}
createCanvas() {
let canvas = document.createElement("canvas");
let width = window.innerWidth;
let height = window.innerHeight-4;
canvas.height = height;
canvas.width = width;
canvas.setAttribute("id", "flowField");
canvas.style = "position: absolute; background:transparent; top:0; left:0; z-index:-1";
document.getElementsByTagName("BODY")[0].appendChild(canvas);
return canvas.getContext("2d");
}
}
|
GorillaBus/PhySim
|
projects/local/noc-tests/lib/FlowField.js
|
JavaScript
|
mit
| 7,895
|
/*
* Generated by class-dump 3.3.4 (64 bit).
*
* class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by Steve Nygard.
*/
#import "NSObject-Protocol.h"
@protocol XDComponentIdentifying <NSObject>
+ (id)defaultIdentifier;
- (id)identifier;
@end
|
liyong03/YLCleaner
|
YLCleaner/Xcode-RuntimeHeaders/XDInterface/XDComponentIdentifying-Protocol.h
|
C
|
mit
| 266
|
/* encodeErgeHssCellLines.h was originally generated by the autoSql program, which also
* generated encodeErgeHssCellLines.c and encodeErgeHssCellLines.sql. This header links the database and
* the RAM representation of objects. */
/* Copyright (C) 2008 The Regents of the University of California
* See README in this or parent directory for licensing information. */
#ifndef ENCODEERGEHSSCELLLINES_H
#define ENCODEERGEHSSCELLLINES_H
#define ENCODEERGEHSSCELLLINES_NUM_COLS 15
struct encodeErgeHssCellLines
/* ENCODE experimental data from dbERGEII */
{
struct encodeErgeHssCellLines *next; /* Next in singly linked list. */
char *chrom; /* Human chromosome */
unsigned chromStart; /* Start position in chromosome */
unsigned chromEnd; /* End position in chromosome */
char *name; /* Name of read - up to 255 characters */
unsigned score; /* Score from 0-1000. 1000 is best */
char strand[2]; /* Value should be + or - */
unsigned thickStart; /* Start of where display should be thick (start codon) */
unsigned thickEnd; /* End of where display should be thick (stop codon) */
unsigned reserved; /* Always zero for now */
unsigned blockCount; /* Number of separate blocks (regions without gaps) */
unsigned *blockSizes; /* Comma separated list of block sizes */
unsigned *chromStarts; /* Start position of each block in relative to chromStart */
char *Id; /* dbERGEII Id */
char *color; /* RGB color values */
char *allLines; /* List of all cell lines */
};
struct encodeErgeHssCellLines *encodeErgeHssCellLinesLoad(char **row);
/* Load a encodeErgeHssCellLines from row fetched with select * from encodeErgeHssCellLines
* from database. Dispose of this with encodeErgeHssCellLinesFree(). */
struct encodeErgeHssCellLines *encodeErgeHssCellLinesLoadAll(char *fileName);
/* Load all encodeErgeHssCellLines from whitespace-separated file.
* Dispose of this with encodeErgeHssCellLinesFreeList(). */
struct encodeErgeHssCellLines *encodeErgeHssCellLinesLoadAllByChar(char *fileName, char chopper);
/* Load all encodeErgeHssCellLines from chopper separated file.
* Dispose of this with encodeErgeHssCellLinesFreeList(). */
#define encodeErgeHssCellLinesLoadAllByTab(a) encodeErgeHssCellLinesLoadAllByChar(a, '\t');
/* Load all encodeErgeHssCellLines from tab separated file.
* Dispose of this with encodeErgeHssCellLinesFreeList(). */
struct encodeErgeHssCellLines *encodeErgeHssCellLinesCommaIn(char **pS, struct encodeErgeHssCellLines *ret);
/* Create a encodeErgeHssCellLines out of a comma separated string.
* This will fill in ret if non-null, otherwise will
* return a new encodeErgeHssCellLines */
void encodeErgeHssCellLinesFree(struct encodeErgeHssCellLines **pEl);
/* Free a single dynamically allocated encodeErgeHssCellLines such as created
* with encodeErgeHssCellLinesLoad(). */
void encodeErgeHssCellLinesFreeList(struct encodeErgeHssCellLines **pList);
/* Free a list of dynamically allocated encodeErgeHssCellLines's */
void encodeErgeHssCellLinesOutput(struct encodeErgeHssCellLines *el, FILE *f, char sep, char lastSep);
/* Print out encodeErgeHssCellLines. Separate fields with sep. Follow last field with lastSep. */
#define encodeErgeHssCellLinesTabOut(el,f) encodeErgeHssCellLinesOutput(el,f,'\t','\n');
/* Print out encodeErgeHssCellLines as a line in a tab-separated file. */
#define encodeErgeHssCellLinesCommaOut(el,f) encodeErgeHssCellLinesOutput(el,f,',',',');
/* Print out encodeErgeHssCellLines as a comma separated list including final comma. */
/* -------------------------------- End autoSql Generated Code -------------------------------- */
struct encodeErgeHssCellLines *encodeErgeHssCellLinesLoadByQuery(struct sqlConnection *conn, char *query);
/* Load all encodeErge from table that satisfy the query given.
* Where query is of the form 'select * from example where something=something'
* or 'select example.* from example, anotherTable where example.something =
* anotherTable.something'.
* Dispose of this with encodeErgeFreeList(). */
#endif /* ENCODEERGEHSSCELLLINES_H */
|
hillerlab/GenomeAlignmentTools
|
kent/src/hg/inc/encode/encodeErgeHssCellLines.h
|
C
|
mit
| 4,129
|
// The size of Rectangle, Bound etc.
class Size {
constructor(width, height) {
this.type = 'Size'
this.width = width
this.height = height
}
set(width, height) {
this.width = width
this.height = height
}
}
export default Size
|
jarvisniu/Bu.js
|
src/math/Size.js
|
JavaScript
|
mit
| 256
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from .sub_resource import SubResource
class VirtualNetworkPeering(SubResource):
"""Peerings in a virtual network resource.
:param id: Resource ID.
:type id: str
:param allow_virtual_network_access: Whether the VMs in the linked virtual
network space would be able to access all the VMs in local Virtual network
space.
:type allow_virtual_network_access: bool
:param allow_forwarded_traffic: Whether the forwarded traffic from the VMs
in the remote virtual network will be allowed/disallowed.
:type allow_forwarded_traffic: bool
:param allow_gateway_transit: If gateway links can be used in remote
virtual networking to link to this virtual network.
:type allow_gateway_transit: bool
:param use_remote_gateways: If remote gateways can be used on this virtual
network. If the flag is set to true, and allowGatewayTransit on remote
peering is also true, virtual network will use gateways of remote virtual
network for transit. Only one peering can have this flag set to true. This
flag cannot be set if virtual network already has a gateway.
:type use_remote_gateways: bool
:param remote_virtual_network: The reference of the remote virtual
network.
:type remote_virtual_network: :class:`SubResource
<azure.mgmt.network.v2017_03_01.models.SubResource>`
:param peering_state: The status of the virtual network peering. Possible
values are 'Initiated', 'Connected', and 'Disconnected'. Possible values
include: 'Initiated', 'Connected', 'Disconnected'
:type peering_state: str or :class:`VirtualNetworkPeeringState
<azure.mgmt.network.v2017_03_01.models.VirtualNetworkPeeringState>`
:param provisioning_state: The provisioning state of the resource.
:type provisioning_state: str
:param name: The name of the resource that is unique within a resource
group. This name can be used to access the resource.
:type name: str
:param etag: A unique read-only string that changes whenever the resource
is updated.
:type etag: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'allow_virtual_network_access': {'key': 'properties.allowVirtualNetworkAccess', 'type': 'bool'},
'allow_forwarded_traffic': {'key': 'properties.allowForwardedTraffic', 'type': 'bool'},
'allow_gateway_transit': {'key': 'properties.allowGatewayTransit', 'type': 'bool'},
'use_remote_gateways': {'key': 'properties.useRemoteGateways', 'type': 'bool'},
'remote_virtual_network': {'key': 'properties.remoteVirtualNetwork', 'type': 'SubResource'},
'peering_state': {'key': 'properties.peeringState', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
}
def __init__(self, id=None, allow_virtual_network_access=None, allow_forwarded_traffic=None, allow_gateway_transit=None, use_remote_gateways=None, remote_virtual_network=None, peering_state=None, provisioning_state=None, name=None, etag=None):
super(VirtualNetworkPeering, self).__init__(id=id)
self.allow_virtual_network_access = allow_virtual_network_access
self.allow_forwarded_traffic = allow_forwarded_traffic
self.allow_gateway_transit = allow_gateway_transit
self.use_remote_gateways = use_remote_gateways
self.remote_virtual_network = remote_virtual_network
self.peering_state = peering_state
self.provisioning_state = provisioning_state
self.name = name
self.etag = etag
|
SUSE/azure-sdk-for-python
|
azure-mgmt-network/azure/mgmt/network/v2017_03_01/models/virtual_network_peering.py
|
Python
|
mit
| 4,140
|
/*
Template Name: Color Admin - Responsive Admin Dashboard Template build with Twitter Bootstrap 3.3.2
Version: 1.6.0
Author: Sean Ngu
Website: http://www.seantheme.com/color-admin-v1.6/admin/
*/
var handleEmailToInput = function() {
$('#email-to').tagit({
availableTags: ["c++", "java", "php", "javascript", "ruby", "python", "c"]
});
};
var handleEmailContent = function() {
$('#wysihtml5').wysihtml5();
};
var EmailCompose = function () {
"use strict";
return {
//main function
init: function () {
handleEmailToInput();
handleEmailContent();
}
};
}();
|
kamalmahmudi/sia
|
src/main/webapp/resources/js/email-compose.demo.js
|
JavaScript
|
mit
| 663
|
--[[
#############################
## (c) Soner ##
## EasyIni ##
#############################
]]--
EasyIni = {}
EasyIni.__index = EasyIni
function EasyIni:LoadFile(filename, ignoreExists)
-- traceback()
local self = setmetatable({},EasyIni)
if not(ignoreExists) then
if not fileExists(filename) then
file = fileCreate(filename)
fileClose(file)
end
end
local file = fileOpen(filename)
if not(file) then
return false;
end
local size = fileGetSize(file)
if(size < 1) then
size = 10;
end
local read = fileRead(file, size);
fileClose(file)
local data = {}
local filedata = split(read,"\n")
local lastzone = ""
for _,row in ipairs(filedata) do
if string.find(row, "[", 1, true) and string.find(row, "]", 1, true) then
local b,e = string.find(row,"]",1,true)
lastzone = string.sub(row,2,e-1)
if not data[lastzone] then
data[lastzone]={}
end
elseif string.find(string.sub(row,1,1),";",1,true) then --Ignorieren von INI Kommentierungen
else
local tempsplit = split(row,"=")
data[lastzone][tempsplit[1]] = tempsplit[2]
end
end
self.data = data
self.filename = filename
return self
end
function EasyIni:NewFile(filename)
local self = setmetatable({},EasyIni)
self.data = {}
self.filename = filename
return self
end
function EasyIni:Get(selection,name)
if self.data[selection] then
if self.data[selection][name] then
return self.data[selection][name]
else
return false
end
else
return false
end
end
function EasyIni:GetNamesFromSelection(selection)
if self.data[selection] then
return self.data[selection];
else
return false
end
end
function EasyIni:Set(selection,name,value)
if not self.data[selection] then
self.data[selection] = {}
end
self.data[selection][name] = value
return true
end
function EasyIni:Save()
local string = ""
for selection,selectiontable in pairs(self.data) do
string = string.."["..selection.."]\n"
for k,v in pairs(selectiontable) do
if(k and v) then
string = string..k.."="..tostring(v).."\n"
end
end
end
local file = fileCreate(self.filename)
fileWrite(file,string)
fileFlush(file) -- KLOSPUELUNG!!
fileClose(file)
return true
end
function traceback ()
local level = 1
while true do
local info = debug.getinfo(level, "Sl")
if not info then break end
if info.what == "C" then -- is a C function?
outputDebugString(level, "C function")
else -- a Lua function
outputDebugString(string.format("[%s]:%d",
info.short_src, info.currentline))
end
level = level + 1
end
end
|
ReWrite94/iLife
|
client/Classes/Hud/cIni.lua
|
Lua
|
mit
| 2,565
|
---
title: Faster Recruiting
---
With the rise of React, it's become easier to find talented developers who are skilled in React, than developers who are skilled in various flavors of CMS UI development frameworks.
Jesus Olivas, the Head of Engineering at WeKnow, a 40-person agency based in San Diego, CA, [explains](https://www.youtube.com/watch?v=tWu1xfF18FI&feature=youtu.be&t=2392):
> On the agency side of things, it's easier to get a developer that knows React, than finding another developer that knows Drupal theming [and] Twig...
|
gatsbyjs/gatsby
|
docs/docs/using-gatsby-professionally/faster-recruiting.md
|
Markdown
|
mit
| 543
|
var assert = require('assert')
var parse = require('../')
// test parser
assert.equal(parse('***foo***'),
'<p><strong><em>foo</em></strong></p>\n')
assert.equal(parse('# **blah**'),
'<h1><a name="--blah--"></a><strong>blah</strong></h1>\n')
assert.equal(parse('Blah blah\n-----'),
'<h2><a name="blah-blah"></a>Blah blah</h2>\n')
// test sanitizer
assert.equal(parse('<a href="blah" id="wat">foo</a>'),
'<p><a href="blah">foo</a></p>\n')
assert.equal(parse('<a href=blah>foo</a>'),
'<p><a href="blah">foo</a></p>\n')
assert.equal(parse('<div><i>foo <b>blah</i></b>'),
'<div><i>foo <b>blah</b></i></div>')
assert.equal(parse('<a class="evil" href="blah">foo</a>'),
'<p></p>\n')
// highlighter
assert.equal(parse('```js\nvar foo = "bar";\n```'),
'<pre><code class="lang-js"><span class="hljs-keyword">var</span> foo = <span class="hljs-string">"bar"</span>;\n</code></pre>\n')
assert.equal(parse('```sh\n$ test\n```'),
'<pre><code class="lang-sh">$ <span class="hljs-built_in">test</span>\n</code></pre>\n')
assert.equal(parse('```\n-----\n```'),
'<pre><code>-----\n</code></pre>\n')
// metadata
assert.equal(parse('---\naaa: 123\nbbb: "*456*"\n---\n\n*foo*\n'),
'<table>\n<thead>\n<th>\naaa</th>\n<th>\nbbb</th>\n</thead>\n<tbody>\n<td>\n123</td>\n<td>\n*456*</td>\n</tbody>\n</table>\n<p><em>foo</em></p>\n')
|
rlidwka/render-readme
|
test/test.js
|
JavaScript
|
mit
| 1,538
|
using UnityEngine;
using System.Collections;
public class Telecommande : MonoBehaviour
{
#pragma warning disable 0414
private vrCommand m_MyCommand;
#pragma warning restore 0414
private vrWebView m_webView;
private vrValue CommandHandler(vrValue iValue)
{
print("HTML Button was clicked");
m_webView.ExecuteJavascript("setText('Button was clicked !')");
return null;
}
void Start () {
m_MyCommand = new vrCommand("MyCommand", CommandHandler);
m_webView = GetComponent<VRWebView>().webView;
}
}
|
nhurman/avalon
|
Kerpape_HR/Assets/Scripts/Telecommande.cs
|
C#
|
mit
| 531
|
const name = 'wizard';
describe("Metro 4 :: Wizard", () => {
it('Component Initialization', ()=>{
cy.visit("cypress/"+name+".html");
})
})
|
ridjohansen/Metro-UI-CSS
|
cypress/integration/components/wizard.js
|
JavaScript
|
mit
| 155
|
<div class="row">
<div class="medium-12 columns">
<label>{{ label }}{{# required }} <span style="font-weight:normal" title="{{ lang.required }}">*</span>{{/ required}}
<input name="{{ name }}" value="{{ value }}" type="text" placeholder="{{ placeholder }}" style="width:{{ width }}">
</label>
</div>
</div>
|
helmut/forms
|
src/Fields/Text/templates/foundation/text.mustache.php
|
PHP
|
mit
| 316
|
CREATE TABLE list (id VARCHAR(10) NOT NULL, value VARCHAR(64) NOT NULL, PRIMARY KEY(id));
INSERT INTO "list" ("id", "value") VALUES ('AFN', 'Afgani Afganistan');
INSERT INTO "list" ("id", "value") VALUES ('AFA', 'Afgani Afganistan (1927–2002)');
INSERT INTO "list" ("id", "value") VALUES ('ALK', 'Albanian Lek (1946–1965)');
INSERT INTO "list" ("id", "value") VALUES ('MGA', 'Ariary Madagaskar');
INSERT INTO "list" ("id", "value") VALUES ('ARA', 'Austral Argentina');
INSERT INTO "list" ("id", "value") VALUES ('THB', 'Baht Thailand');
INSERT INTO "list" ("id", "value") VALUES ('PAB', 'Balboa Panama');
INSERT INTO "list" ("id", "value") VALUES ('ETB', 'Birr Etiopia');
INSERT INTO "list" ("id", "value") VALUES ('VEF', 'Bolivar Venezuela');
INSERT INTO "list" ("id", "value") VALUES ('VEB', 'Bolivar Venezuela (1871–2008)');
INSERT INTO "list" ("id", "value") VALUES ('BOB', 'Boliviano');
INSERT INTO "list" ("id", "value") VALUES ('BOL', 'Boliviano Bolivia (1863–1963)');
INSERT INTO "list" ("id", "value") VALUES ('GHS', 'Cedi Ghana');
INSERT INTO "list" ("id", "value") VALUES ('GHC', 'Cedi Ghana (1979–2007)');
INSERT INTO "list" ("id", "value") VALUES ('CNX', 'Chinese People’s Bank Dollar');
INSERT INTO "list" ("id", "value") VALUES ('SVC', 'Colon El Savador');
INSERT INTO "list" ("id", "value") VALUES ('CRC', 'Colon Kosta Rika');
INSERT INTO "list" ("id", "value") VALUES ('NIO', 'Cordoba Nikaragua');
INSERT INTO "list" ("id", "value") VALUES ('NIC', 'Cordoba Nikaragua (1988–1991)');
INSERT INTO "list" ("id", "value") VALUES ('BRN', 'Cruzado Baru Brasil (1989–1990)');
INSERT INTO "list" ("id", "value") VALUES ('BRC', 'Cruzado Brasil (1986–1989)');
INSERT INTO "list" ("id", "value") VALUES ('BRB', 'Cruzeiro Baru Brasil (1967–1986)');
INSERT INTO "list" ("id", "value") VALUES ('BRZ', 'Cruzeiro Brasil (1942–1967)');
INSERT INTO "list" ("id", "value") VALUES ('BRE', 'Cruzeiro Brasil (1990–1993)');
INSERT INTO "list" ("id", "value") VALUES ('BRR', 'Cruzeiro Brasil (1993–1994)');
INSERT INTO "list" ("id", "value") VALUES ('MDC', 'Cupon Moldova');
INSERT INTO "list" ("id", "value") VALUES ('GMD', 'Dalasi Gambia');
INSERT INTO "list" ("id", "value") VALUES ('XRE', 'Dana RINET');
INSERT INTO "list" ("id", "value") VALUES ('MKD', 'Denar Makedonia');
INSERT INTO "list" ("id", "value") VALUES ('MKN', 'Denar Makedonia (1992–1993)');
INSERT INTO "list" ("id", "value") VALUES ('DZD', 'Dinar Algeria');
INSERT INTO "list" ("id", "value") VALUES ('BHD', 'Dinar Bahrain');
INSERT INTO "list" ("id", "value") VALUES ('BAN', 'Dinar Baru Bosnia-Herzegovina (1994–1997)');
INSERT INTO "list" ("id", "value") VALUES ('YUM', 'Dinar Baru Yugoslavia (1994–2002)');
INSERT INTO "list" ("id", "value") VALUES ('BAD', 'Dinar Bosnia-Herzegovina (1992–1994)');
INSERT INTO "list" ("id", "value") VALUES ('IQD', 'Dinar Irak');
INSERT INTO "list" ("id", "value") VALUES ('YUN', 'Dinar Konvertibel Yugoslavia (1990–1992)');
INSERT INTO "list" ("id", "value") VALUES ('HRD', 'Dinar Kroasia');
INSERT INTO "list" ("id", "value") VALUES ('KWD', 'Dinar Kuwait');
INSERT INTO "list" ("id", "value") VALUES ('LYD', 'Dinar Libya');
INSERT INTO "list" ("id", "value") VALUES ('YUR', 'Dinar Reformasi Yugoslavia (1992–1993)');
INSERT INTO "list" ("id", "value") VALUES ('RSD', 'Dinar Serbia');
INSERT INTO "list" ("id", "value") VALUES ('CSD', 'Dinar Serbia (2002–2006)');
INSERT INTO "list" ("id", "value") VALUES ('SDD', 'Dinar Sudan (1992–2007)');
INSERT INTO "list" ("id", "value") VALUES ('TND', 'Dinar Tunisia');
INSERT INTO "list" ("id", "value") VALUES ('YDD', 'Dinar Yaman');
INSERT INTO "list" ("id", "value") VALUES ('JOD', 'Dinar Yordania');
INSERT INTO "list" ("id", "value") VALUES ('MAD', 'Dirham Maroko');
INSERT INTO "list" ("id", "value") VALUES ('AED', 'Dirham Uni Emirat Arab');
INSERT INTO "list" ("id", "value") VALUES ('STD', 'Dobra Sao Tome dan Principe');
INSERT INTO "list" ("id", "value") VALUES ('USN', 'Dolar AS (Hari berikutnya)');
INSERT INTO "list" ("id", "value") VALUES ('USS', 'Dolar AS (Hari yang sama)');
INSERT INTO "list" ("id", "value") VALUES ('USD', 'Dolar Amerika Serikat');
INSERT INTO "list" ("id", "value") VALUES ('AUD', 'Dolar Australia');
INSERT INTO "list" ("id", "value") VALUES ('BSD', 'Dolar Bahama');
INSERT INTO "list" ("id", "value") VALUES ('BBD', 'Dolar Barbados');
INSERT INTO "list" ("id", "value") VALUES ('TWD', 'Dolar Baru Taiwan');
INSERT INTO "list" ("id", "value") VALUES ('BZD', 'Dolar Belize');
INSERT INTO "list" ("id", "value") VALUES ('BMD', 'Dolar Bermuda');
INSERT INTO "list" ("id", "value") VALUES ('BND', 'Dolar Brunei');
INSERT INTO "list" ("id", "value") VALUES ('FJD', 'Dolar Fiji');
INSERT INTO "list" ("id", "value") VALUES ('GYD', 'Dolar Guyana');
INSERT INTO "list" ("id", "value") VALUES ('HKD', 'Dolar Hong Kong');
INSERT INTO "list" ("id", "value") VALUES ('JMD', 'Dolar Jamaika');
INSERT INTO "list" ("id", "value") VALUES ('CAD', 'Dolar Kanada');
INSERT INTO "list" ("id", "value") VALUES ('XCD', 'Dolar Karibia Timur');
INSERT INTO "list" ("id", "value") VALUES ('KYD', 'Dolar Kepulauan Cayman');
INSERT INTO "list" ("id", "value") VALUES ('SBD', 'Dolar Kepulauan Solomon');
INSERT INTO "list" ("id", "value") VALUES ('LRD', 'Dolar Liberia');
INSERT INTO "list" ("id", "value") VALUES ('NAD', 'Dolar Namibia');
INSERT INTO "list" ("id", "value") VALUES ('RHD', 'Dolar Rhodesia');
INSERT INTO "list" ("id", "value") VALUES ('NZD', 'Dolar Selandia Baru');
INSERT INTO "list" ("id", "value") VALUES ('SGD', 'Dolar Singapura');
INSERT INTO "list" ("id", "value") VALUES ('SRD', 'Dolar Suriname');
INSERT INTO "list" ("id", "value") VALUES ('TTD', 'Dolar Trinidad dan Tobago');
INSERT INTO "list" ("id", "value") VALUES ('ZWD', 'Dolar Zimbabwe (1980–2008)');
INSERT INTO "list" ("id", "value") VALUES ('ZWR', 'Dolar Zimbabwe (2008)');
INSERT INTO "list" ("id", "value") VALUES ('ZWL', 'Dolar Zimbabwe (2009)');
INSERT INTO "list" ("id", "value") VALUES ('VND', 'Dong Vietnam');
INSERT INTO "list" ("id", "value") VALUES ('VNN', 'Dong Vietnam (1978–1985)');
INSERT INTO "list" ("id", "value") VALUES ('GRD', 'Drachma Yunani');
INSERT INTO "list" ("id", "value") VALUES ('AMD', 'Dram Armenia');
INSERT INTO "list" ("id", "value") VALUES ('GQE', 'Ekuele Guinea Ekuatorial');
INSERT INTO "list" ("id", "value") VALUES ('CLE', 'Escudo Cile');
INSERT INTO "list" ("id", "value") VALUES ('GWE', 'Escudo Guinea Portugal');
INSERT INTO "list" ("id", "value") VALUES ('MZE', 'Escudo Mozambik');
INSERT INTO "list" ("id", "value") VALUES ('PTE', 'Escudo Portugal');
INSERT INTO "list" ("id", "value") VALUES ('CVE', 'Escudo Tanjung Verde');
INSERT INTO "list" ("id", "value") VALUES ('TPE', 'Escudo Timor');
INSERT INTO "list" ("id", "value") VALUES ('EUR', 'Euro');
INSERT INTO "list" ("id", "value") VALUES ('CHE', 'Euro WIR');
INSERT INTO "list" ("id", "value") VALUES ('LUL', 'Financial Franc Luksemburg');
INSERT INTO "list" ("id", "value") VALUES ('AWG', 'Florin Aruba');
INSERT INTO "list" ("id", "value") VALUES ('HUF', 'Forint Hungaria');
INSERT INTO "list" ("id", "value") VALUES ('BEF', 'Franc Belgia');
INSERT INTO "list" ("id", "value") VALUES ('BEL', 'Franc Belgia (keuangan)');
INSERT INTO "list" ("id", "value") VALUES ('BEC', 'Franc Belgia (konvertibel)');
INSERT INTO "list" ("id", "value") VALUES ('BIF', 'Franc Burundi');
INSERT INTO "list" ("id", "value") VALUES ('XOF', 'Franc CFA BCEAO');
INSERT INTO "list" ("id", "value") VALUES ('XAF', 'Franc CFA BEAC');
INSERT INTO "list" ("id", "value") VALUES ('XPF', 'Franc CFP');
INSERT INTO "list" ("id", "value") VALUES ('XFO', 'Franc Gold Perancis');
INSERT INTO "list" ("id", "value") VALUES ('GNF', 'Franc Guinea');
INSERT INTO "list" ("id", "value") VALUES ('DJF', 'Franc Jibuti');
INSERT INTO "list" ("id", "value") VALUES ('KMF', 'Franc Komoro');
INSERT INTO "list" ("id", "value") VALUES ('CDF', 'Franc Kongo');
INSERT INTO "list" ("id", "value") VALUES ('LUC', 'Franc Konvertibel Luksemburg');
INSERT INTO "list" ("id", "value") VALUES ('LUF', 'Franc Luksemburg');
INSERT INTO "list" ("id", "value") VALUES ('MGF', 'Franc Malagasi');
INSERT INTO "list" ("id", "value") VALUES ('MLF', 'Franc Mali');
INSERT INTO "list" ("id", "value") VALUES ('MAF', 'Franc Maroko');
INSERT INTO "list" ("id", "value") VALUES ('MCF', 'Franc Monegasque');
INSERT INTO "list" ("id", "value") VALUES ('FRF', 'Franc Prancis');
INSERT INTO "list" ("id", "value") VALUES ('RWF', 'Franc Rwanda');
INSERT INTO "list" ("id", "value") VALUES ('CHF', 'Franc Swiss');
INSERT INTO "list" ("id", "value") VALUES ('XFU', 'Franc UIC Perancis');
INSERT INTO "list" ("id", "value") VALUES ('CHW', 'Franc WIR');
INSERT INTO "list" ("id", "value") VALUES ('HTG', 'Gourde Haiti');
INSERT INTO "list" ("id", "value") VALUES ('PYG', 'Guarani Paraguay');
INSERT INTO "list" ("id", "value") VALUES ('ANG', 'Guilder Antilla Belanda');
INSERT INTO "list" ("id", "value") VALUES ('NLG', 'Guilder Belanda');
INSERT INTO "list" ("id", "value") VALUES ('SRG', 'Guilder Suriname');
INSERT INTO "list" ("id", "value") VALUES ('YUD', 'Hard Dinar Yugoslavia (1966–1990)');
INSERT INTO "list" ("id", "value") VALUES ('CSK', 'Hard Koruna Cheska');
INSERT INTO "list" ("id", "value") VALUES ('BGL', 'Hard Lev Bulgaria');
INSERT INTO "list" ("id", "value") VALUES ('UAH', 'Hryvnia Ukraina');
INSERT INTO "list" ("id", "value") VALUES ('KRH', 'Hwan Korea Selatan (1953–1962)');
INSERT INTO "list" ("id", "value") VALUES ('PEI', 'Inti Peru');
INSERT INTO "list" ("id", "value") VALUES ('UAK', 'Karbovanet Ukraina');
INSERT INTO "list" ("id", "value") VALUES ('PGK', 'Kina Papua Nugini');
INSERT INTO "list" ("id", "value") VALUES ('LAK', 'Kip Laos');
INSERT INTO "list" ("id", "value") VALUES ('CZK', 'Koruna Cheska');
INSERT INTO "list" ("id", "value") VALUES ('SKK', 'Koruna Slovakia');
INSERT INTO "list" ("id", "value") VALUES ('ISK', 'Krona Islandia');
INSERT INTO "list" ("id", "value") VALUES ('ISJ', 'Krona Islandia (1918–1981)');
INSERT INTO "list" ("id", "value") VALUES ('SEK', 'Krona Swedia');
INSERT INTO "list" ("id", "value") VALUES ('DKK', 'Krone Denmark');
INSERT INTO "list" ("id", "value") VALUES ('NOK', 'Krone Norwegia');
INSERT INTO "list" ("id", "value") VALUES ('EEK', 'Kroon Estonia');
INSERT INTO "list" ("id", "value") VALUES ('HRK', 'Kuna Kroasia');
INSERT INTO "list" ("id", "value") VALUES ('GEK', 'Kupon Larit Georgia');
INSERT INTO "list" ("id", "value") VALUES ('MWK', 'Kwacha Malawi');
INSERT INTO "list" ("id", "value") VALUES ('ZMW', 'Kwacha Zambia');
INSERT INTO "list" ("id", "value") VALUES ('ZMK', 'Kwacha Zambia (1968–2012)');
INSERT INTO "list" ("id", "value") VALUES ('AOA', 'Kwanza Angola');
INSERT INTO "list" ("id", "value") VALUES ('AOK', 'Kwanza Angola (1977–1991)');
INSERT INTO "list" ("id", "value") VALUES ('AOR', 'Kwanza Angola yang Disesuaikan Lagi (1995–1999)');
INSERT INTO "list" ("id", "value") VALUES ('AON', 'Kwanza Baru Angola (1990–2000)');
INSERT INTO "list" ("id", "value") VALUES ('BUK', 'Kyat Burma');
INSERT INTO "list" ("id", "value") VALUES ('MMK', 'Kyat Myanmar');
INSERT INTO "list" ("id", "value") VALUES ('GEL', 'Lari Georgia');
INSERT INTO "list" ("id", "value") VALUES ('LVL', 'Lats Latvia');
INSERT INTO "list" ("id", "value") VALUES ('ALL', 'Lek Albania');
INSERT INTO "list" ("id", "value") VALUES ('HNL', 'Lempira Honduras');
INSERT INTO "list" ("id", "value") VALUES ('SLL', 'Leone Sierra Leone');
INSERT INTO "list" ("id", "value") VALUES ('MDL', 'Leu Moldova');
INSERT INTO "list" ("id", "value") VALUES ('RON', 'Leu Rumania');
INSERT INTO "list" ("id", "value") VALUES ('ROL', 'Leu Rumania (1952–2006)');
INSERT INTO "list" ("id", "value") VALUES ('BGN', 'Lev Bulgaria');
INSERT INTO "list" ("id", "value") VALUES ('BGO', 'Lev Bulgaria (1879–1952)');
INSERT INTO "list" ("id", "value") VALUES ('SZL', 'Lilangeni Swaziland');
INSERT INTO "list" ("id", "value") VALUES ('ITL', 'Lira Italia');
INSERT INTO "list" ("id", "value") VALUES ('MTL', 'Lira Malta');
INSERT INTO "list" ("id", "value") VALUES ('TRY', 'Lira Turki');
INSERT INTO "list" ("id", "value") VALUES ('TRL', 'Lira Turki (1922–2005)');
INSERT INTO "list" ("id", "value") VALUES ('LTL', 'Litas Lituania');
INSERT INTO "list" ("id", "value") VALUES ('LSL', 'Loti Lesotho');
INSERT INTO "list" ("id", "value") VALUES ('AZN', 'Manat Azerbaijan');
INSERT INTO "list" ("id", "value") VALUES ('AZM', 'Manat Azerbaijan (1993–2006)');
INSERT INTO "list" ("id", "value") VALUES ('TMT', 'Manat Turkimenistan');
INSERT INTO "list" ("id", "value") VALUES ('TMM', 'Manat Turkmenistan (1993–2009)');
INSERT INTO "list" ("id", "value") VALUES ('DEM', 'Mark Jerman');
INSERT INTO "list" ("id", "value") VALUES ('DDM', 'Mark Jerman Timur');
INSERT INTO "list" ("id", "value") VALUES ('BAM', 'Mark Konvertibel Bosnia-Herzegovina');
INSERT INTO "list" ("id", "value") VALUES ('FIM', 'Markka Finlandia');
INSERT INTO "list" ("id", "value") VALUES ('MZN', 'Metical Mozambik');
INSERT INTO "list" ("id", "value") VALUES ('MZM', 'Metical Mozambik (1980–2006)');
INSERT INTO "list" ("id", "value") VALUES ('BOV', 'Mvdol Bolivia');
INSERT INTO "list" ("id", "value") VALUES ('NGN', 'Naira Nigeria');
INSERT INTO "list" ("id", "value") VALUES ('ERN', 'Nakfa Eritrea');
INSERT INTO "list" ("id", "value") VALUES ('BTN', 'Ngultrum Bhutan');
INSERT INTO "list" ("id", "value") VALUES ('MRO', 'Ouguiya Mauritania');
INSERT INTO "list" ("id", "value") VALUES ('MOP', 'Pataca Makau');
INSERT INTO "list" ("id", "value") VALUES ('TOP', 'Paʻanga Tonga');
INSERT INTO "list" ("id", "value") VALUES ('ADP', 'Peseta Andorra');
INSERT INTO "list" ("id", "value") VALUES ('ESP', 'Peseta Spanyol');
INSERT INTO "list" ("id", "value") VALUES ('ESA', 'Peseta Spanyol (akun)');
INSERT INTO "list" ("id", "value") VALUES ('ESB', 'Peseta Spanyol (konvertibel)');
INSERT INTO "list" ("id", "value") VALUES ('ARS', 'Peso Argentina');
INSERT INTO "list" ("id", "value") VALUES ('ARM', 'Peso Argentina (1881–1970)');
INSERT INTO "list" ("id", "value") VALUES ('ARP', 'Peso Argentina (1983–1985)');
INSERT INTO "list" ("id", "value") VALUES ('BOP', 'Peso Bolivia');
INSERT INTO "list" ("id", "value") VALUES ('CLP', 'Peso Cile');
INSERT INTO "list" ("id", "value") VALUES ('DOP', 'Peso Dominika');
INSERT INTO "list" ("id", "value") VALUES ('PHP', 'Peso Filipina');
INSERT INTO "list" ("id", "value") VALUES ('GWP', 'Peso Guinea-Bissau');
INSERT INTO "list" ("id", "value") VALUES ('COP', 'Peso Kolombia');
INSERT INTO "list" ("id", "value") VALUES ('CUC', 'Peso Konvertibel Kuba');
INSERT INTO "list" ("id", "value") VALUES ('CUP', 'Peso Kuba');
INSERT INTO "list" ("id", "value") VALUES ('ARL', 'Peso Ley Argentina (1970–1983)');
INSERT INTO "list" ("id", "value") VALUES ('MXN', 'Peso Meksiko');
INSERT INTO "list" ("id", "value") VALUES ('MXP', 'Peso Silver Meksiko (1861–1992)');
INSERT INTO "list" ("id", "value") VALUES ('UYU', 'Peso Uruguay');
INSERT INTO "list" ("id", "value") VALUES ('UYP', 'Peso Uruguay (1975–1993)');
INSERT INTO "list" ("id", "value") VALUES ('UYI', 'Peso Uruguay (Unit Diindeks)');
INSERT INTO "list" ("id", "value") VALUES ('PLN', 'Polandia Zloty');
INSERT INTO "list" ("id", "value") VALUES ('GIP', 'Pound Gibraltar');
INSERT INTO "list" ("id", "value") VALUES ('GBP', 'Pound Inggris');
INSERT INTO "list" ("id", "value") VALUES ('IEP', 'Pound Irlandia');
INSERT INTO "list" ("id", "value") VALUES ('ILP', 'Pound Israel');
INSERT INTO "list" ("id", "value") VALUES ('FKP', 'Pound Kepulauan Falkland');
INSERT INTO "list" ("id", "value") VALUES ('LBP', 'Pound Lebanon');
INSERT INTO "list" ("id", "value") VALUES ('MTP', 'Pound Malta');
INSERT INTO "list" ("id", "value") VALUES ('EGP', 'Pound Mesir');
INSERT INTO "list" ("id", "value") VALUES ('SHP', 'Pound Saint Helena');
INSERT INTO "list" ("id", "value") VALUES ('CYP', 'Pound Siprus');
INSERT INTO "list" ("id", "value") VALUES ('SDG', 'Pound Sudan');
INSERT INTO "list" ("id", "value") VALUES ('SDP', 'Pound Sudan (1957–1998)');
INSERT INTO "list" ("id", "value") VALUES ('SSP', 'Pound Sudan Selatan');
INSERT INTO "list" ("id", "value") VALUES ('SYP', 'Pound Suriah');
INSERT INTO "list" ("id", "value") VALUES ('BWP', 'Pula Botswana');
INSERT INTO "list" ("id", "value") VALUES ('GTQ', 'Quetzal Guatemala');
INSERT INTO "list" ("id", "value") VALUES ('ZAR', 'Rand Afrika Selatan');
INSERT INTO "list" ("id", "value") VALUES ('ZAL', 'Rand Afrika Selatan (Keuangan)');
INSERT INTO "list" ("id", "value") VALUES ('BRL', 'Real Brasil');
INSERT INTO "list" ("id", "value") VALUES ('IRR', 'Rial Iran');
INSERT INTO "list" ("id", "value") VALUES ('OMR', 'Rial Oman');
INSERT INTO "list" ("id", "value") VALUES ('QAR', 'Rial Qatar');
INSERT INTO "list" ("id", "value") VALUES ('YER', 'Rial Yaman');
INSERT INTO "list" ("id", "value") VALUES ('KHR', 'Riel Kamboja');
INSERT INTO "list" ("id", "value") VALUES ('MYR', 'Ringgit Malaysia');
INSERT INTO "list" ("id", "value") VALUES ('SAR', 'Riyal Arab Saudi');
INSERT INTO "list" ("id", "value") VALUES ('BYB', 'Rubel Baru Belarus (1994–1999)');
INSERT INTO "list" ("id", "value") VALUES ('BYN', 'Rubel Belarusia');
INSERT INTO "list" ("id", "value") VALUES ('BYR', 'Rubel Belarusia (2000–2016)');
INSERT INTO "list" ("id", "value") VALUES ('LVR', 'Rubel Latvia');
INSERT INTO "list" ("id", "value") VALUES ('RUB', 'Rubel Rusia');
INSERT INTO "list" ("id", "value") VALUES ('RUR', 'Rubel Rusia (1991–1998)');
INSERT INTO "list" ("id", "value") VALUES ('SUR', 'Rubel Soviet');
INSERT INTO "list" ("id", "value") VALUES ('TJR', 'Rubel Tajikistan');
INSERT INTO "list" ("id", "value") VALUES ('MVR', 'Rufiyaa Maladewa');
INSERT INTO "list" ("id", "value") VALUES ('MVP', 'Rufiyaa Maladewa (1947–1981)');
INSERT INTO "list" ("id", "value") VALUES ('INR', 'Rupee India');
INSERT INTO "list" ("id", "value") VALUES ('MUR', 'Rupee Mauritius');
INSERT INTO "list" ("id", "value") VALUES ('NPR', 'Rupee Nepal');
INSERT INTO "list" ("id", "value") VALUES ('PKR', 'Rupee Pakistan');
INSERT INTO "list" ("id", "value") VALUES ('SCR', 'Rupee Seychelles');
INSERT INTO "list" ("id", "value") VALUES ('LKR', 'Rupee Sri Lanka');
INSERT INTO "list" ("id", "value") VALUES ('IDR', 'Rupiah Indonesia');
INSERT INTO "list" ("id", "value") VALUES ('CLF', 'Satuan Hitung (UF) Cile');
INSERT INTO "list" ("id", "value") VALUES ('XEU', 'Satuan Mata Uang Eropa');
INSERT INTO "list" ("id", "value") VALUES ('ECV', 'Satuan Nilai Tetap Ekuador');
INSERT INTO "list" ("id", "value") VALUES ('ATS', 'Schilling Austria');
INSERT INTO "list" ("id", "value") VALUES ('ILS', 'Shekel Baru Israel');
INSERT INTO "list" ("id", "value") VALUES ('ILR', 'Shekel Israel');
INSERT INTO "list" ("id", "value") VALUES ('KES', 'Shilling Kenya');
INSERT INTO "list" ("id", "value") VALUES ('SOS', 'Shilling Somalia');
INSERT INTO "list" ("id", "value") VALUES ('TZS', 'Shilling Tanzania');
INSERT INTO "list" ("id", "value") VALUES ('UGX', 'Shilling Uganda');
INSERT INTO "list" ("id", "value") VALUES ('UGS', 'Shilling Uganda (1966–1987)');
INSERT INTO "list" ("id", "value") VALUES ('BGM', 'Socialist Lev Bulgaria');
INSERT INTO "list" ("id", "value") VALUES ('PEN', 'Sol Peru');
INSERT INTO "list" ("id", "value") VALUES ('PES', 'Sol Peru (1863–1965)');
INSERT INTO "list" ("id", "value") VALUES ('KGS', 'Som Kirgistan');
INSERT INTO "list" ("id", "value") VALUES ('UZS', 'Som Uzbekistan');
INSERT INTO "list" ("id", "value") VALUES ('TJS', 'Somoni Tajikistan');
INSERT INTO "list" ("id", "value") VALUES ('ECS', 'Sucre Ekuador');
INSERT INTO "list" ("id", "value") VALUES ('GNS', 'Syli Guinea');
INSERT INTO "list" ("id", "value") VALUES ('BDT', 'Taka Bangladesh');
INSERT INTO "list" ("id", "value") VALUES ('WST', 'Tala Samoa');
INSERT INTO "list" ("id", "value") VALUES ('LTT', 'Talonas Lituania');
INSERT INTO "list" ("id", "value") VALUES ('KZT', 'Tenge Kazakstan');
INSERT INTO "list" ("id", "value") VALUES ('SIT', 'Tolar Slovenia');
INSERT INTO "list" ("id", "value") VALUES ('MNT', 'Tugrik Mongolia');
INSERT INTO "list" ("id", "value") VALUES ('MXV', 'Unit Investasi Meksiko');
INSERT INTO "list" ("id", "value") VALUES ('COU', 'Unit Nilai Nyata Kolombia');
INSERT INTO "list" ("id", "value") VALUES ('VUV', 'Vatu Vanuatu');
INSERT INTO "list" ("id", "value") VALUES ('KRW', 'Won Korea Selatan');
INSERT INTO "list" ("id", "value") VALUES ('KRO', 'Won Korea Selatan (1945–1953)');
INSERT INTO "list" ("id", "value") VALUES ('KPW', 'Won Korea Utara');
INSERT INTO "list" ("id", "value") VALUES ('JPY', 'Yen Jepang');
INSERT INTO "list" ("id", "value") VALUES ('CNY', 'Yuan Tiongkok');
INSERT INTO "list" ("id", "value") VALUES ('ZRN', 'Zaire Baru Zaire (1993–1998)');
INSERT INTO "list" ("id", "value") VALUES ('ZRZ', 'Zaire Zaire (1971–1993)');
INSERT INTO "list" ("id", "value") VALUES ('PLZ', 'Zloty Polandia (1950–1995)');
|
umpirsky/currency-list
|
data/id_ID/currency.sqlite.sql
|
SQL
|
mit
| 20,806
|
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-example62-production</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular-sanitize.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="mySceApp">
<div ng-controller="myAppController as myCtrl">
<i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
<b>User comments</b><br>
By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
$sanitize is available. If $sanitize isn't available, this results in an error instead of an
exploit.
<div class="well">
<div ng-repeat="userComment in myCtrl.userComments">
<b>{{userComment.name}}</b>:
<span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
<br>
</div>
</div>
</div>
</body>
</html>
|
ProjectGinsberg/dashboard-open
|
lib/angular/docs/examples/example-example62/index-production.html
|
HTML
|
mit
| 994
|
module.exports={"title":"R","hex":"276DC3","source":"https://www.r-project.org/logo/","svg":"<svg aria-labelledby=\"simpleicons-r-icon\" role=\"img\" viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\"><title id=\"simpleicons-r-icon\">R icon</title><path d=\"M12 18.82c-6.627 0-12-3.598-12-8.037s5.373-8.037 12-8.037 12 3.599 12 8.037-5.373 8.037-12 8.037zm1.837-12.932c-5.038 0-9.121 2.46-9.121 5.495s4.083 5.494 9.12 5.494 8.756-1.682 8.756-5.494-3.718-5.495-8.755-5.495z\"/><path d=\"M18.275 15.194a9.038 9.038 0 0 1 1.149.433 2.221 2.221 0 0 1 .582.416 1.573 1.573 0 0 1 .266.383l2.863 4.826-4.627.002-2.163-4.063a5.229 5.229 0 0 0-.716-.982.753.753 0 0 0-.549-.25h-1.099v5.292l-4.093.001V7.737h8.221s3.744.067 3.744 3.63a3.822 3.822 0 0 1-3.578 3.827zm-1.78-4.526l-2.479-.001v2.298h2.479a1.134 1.134 0 0 0 1.148-1.17 1.07 1.07 0 0 0-1.148-1.127z\"/></svg>"};
|
cdnjs/cdnjs
|
ajax/libs/simple-icons/1.9.12/r.js
|
JavaScript
|
mit
| 870
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = requirePropFactory;
function requirePropFactory(componentNameInError) {
if (process.env.NODE_ENV === 'production') {
return () => null;
}
const requireProp = requiredProp => (props, propName, componentName, location, propFullName) => {
const propFullNameSafe = propFullName || propName;
if (typeof props[propName] !== 'undefined' && !props[requiredProp]) {
return new Error(`The prop \`${propFullNameSafe}\` of ` + `\`${componentNameInError}\` must be used on \`${requiredProp}\`.`);
}
return null;
};
return requireProp;
}
|
cdnjs/cdnjs
|
ajax/libs/material-ui/5.0.0-alpha.14/node/utils/requirePropFactory.js
|
JavaScript
|
mit
| 662
|
import type { DragDropMonitor, DragSource, Identifier } from 'dnd-core';
import type { Connector } from '../../internals';
import type { DragSourceMonitor } from '../../types';
import type { DragSourceHookSpec } from '../types';
export declare class DragSourceImpl<O, R, P> implements DragSource {
spec: DragSourceHookSpec<O, R, P>;
private monitor;
private connector;
constructor(spec: DragSourceHookSpec<O, R, P>, monitor: DragSourceMonitor<O, R>, connector: Connector);
beginDrag(): NonNullable<O> | null;
canDrag(): boolean;
isDragging(globalMonitor: DragDropMonitor, target: Identifier): boolean;
endDrag(): void;
}
|
cdnjs/cdnjs
|
ajax/libs/react-dnd/15.0.2/types/hooks/useDrag/DragSourceImpl.d.ts
|
TypeScript
|
mit
| 667
|
require 'require_relative' if RUBY_VERSION[0,3] == '1.8'
require_relative 'acceptance_helper'
describe "Delete your account" do
include AcceptanceHelper
before do
@u = Fabricate(:user)
@update = Fabricate(:update)
@u.feed.updates << @update
log_in_username(@u)
end
it "lets you delete your account and deletes all your updates" do
visit "/users/#{@u.username}/edit"
click_link "Delete Account"
fill_in "username_confirmation", :with => @u.username
click_button "Delete Account"
within flash do
assert has_content?("Your account has been deleted. We're sorry to see you go.")
end
assert logged_out?
visit "/updates"
within "#updates" do
assert has_no_content?(@update.text)
end
end
it "returns you to your edit page if you click cancel" do
visit "/users/#{@u.username}/edit"
click_link "Delete Account"
click_link "Cancel"
page.current_url.must_match("/users/#{@u.username}/edit")
end
it "returns you to your edit page if you dont type a username" do
visit "/users/#{@u.username}/edit"
click_link "Delete Account"
click_button "Delete Account"
page.current_url.must_match("/users/#{@u.username}/edit")
within flash do
assert has_content?("Nothing was deleted since you did not type your username.")
end
end
it "returns you to your edit page if you type your username wrong" do
visit "/users/#{@u.username}/edit"
click_link "Delete Account"
fill_in "username_confirmation", :with => "nopenopenope"
click_button "Delete Account"
page.current_url.must_match("/users/#{@u.username}/edit")
within flash do
assert has_content?("Nothing was deleted since you did not type your username.")
end
end
it "does not let you delete someone else's account" do
@someone_else = Fabricate(:user, :username => "someone_else")
delete "/users/someone_else"
visit "/users/someone_else"
within "span.user-text" do
assert has_content?("someone_else")
end
end
end
|
carols10cents/rstat.us
|
test/acceptance/account_deletion_test.rb
|
Ruby
|
cc0-1.0
| 2,052
|
//>>built
define({"widgets/Stream/setting/nls/strings":{_widgetLabel:"Ruscello",streamControls:"Controlli streaming",streamFilter:"Filtro",startStreaming:"Avvia streaming",stopStreaming:"Interrompi streaming",streamLayers:"Layer di flusso",startStopStream:"Attiva opzione Interrompi streaming o Avvia streaming",clearStream:"Attiva opzione Cancella le osservazioni precedenti",attributeFilter:"Attiva filtro attributo",spatialFilter:"Attiva filtro spaziale",name:"Nome",configFilter:"Configura filtro attributi in streaming",
drawPrevious:"Attiva opzione Traccia osservazioni precedenti",addNew:"Aggiungi filtro",setFilterName:"Imposta nome filtro",filterNameExists:"Nome filtro gi\u00e0 esistente nella tabella.",invalidFilterName:"Il nome deve essere una parola contenente a-z, A-Z, 0-9 o _.",noFilterTip:"Nessun filtro configurato",addFilterFailed:"Impossibile aggiungere un filtro",filterName:"Nome filtro",limitMapExtent:"Limita osservazioni nell'area mappa corrente",limitDrawExtent:"Limita osservazioni nell'area definita dall'utente",
newFilter:"Nuovo filtro",_localized:{}}});
|
SARscene/MapSAROnlinev4
|
Web Mapping Application/widgets/Stream/setting/nls/Setting_it.js
|
JavaScript
|
cc0-1.0
| 1,085
|
(function() {
var cx = scriptParams.google_search_engine_id;
//var cx = '007604623310582658229:j5pu9nxyssu';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
'//www.google.com/cse/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
|
visitmost/visitmost.github.io
|
wp-content/plugins/wp-google-search/assets/js/google_cse_v2.js
|
JavaScript
|
cc0-1.0
| 468
|
package com.enderio.core.common.compat;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Value;
import org.apache.commons.lang3.ArrayUtils;
import com.enderio.core.EnderCore;
import com.enderio.core.common.util.RegisterTime;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.event.FMLStateEvent;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class CompatRegistry
{
@Value
private static class Registration
{
String[] modids;
RegisterTime[] times;
private Registration(RegisterTime time, String... modids)
{
this.modids = modids;
this.times = new RegisterTime[] { time };
}
private Registration(RegisterTime[] times, String... modids)
{
this.modids = modids;
this.times = times;
}
}
public static final CompatRegistry INSTANCE = new CompatRegistry();
private Map<Registration, String> compatMap = new HashMap<Registration, String>();
@Getter
private RegisterTime state = null;
public void registerCompat(RegisterTime time, String clazz, String... modids)
{
compatMap.put(new Registration(time, modids), clazz);
}
public void registerCompat(RegisterTime[] times, String clazz, String... modids)
{
compatMap.put(new Registration(times, modids), clazz);
}
public void handle(FMLStateEvent event)
{
RegisterTime time = RegisterTime.timeFor(event);
state = time;
for (Registration r : compatMap.keySet())
{
if (ArrayUtils.contains(r.times, time) && allModsLoaded(r.modids))
{
doLoad(compatMap.get(r));
}
}
}
private boolean allModsLoaded(String[] modids)
{
for (String s : modids)
{
if (!Loader.isModLoaded(s))
{
return false;
}
}
return true;
}
public void forceLoad(String clazz)
{
Iterator<Registration> iter = compatMap.keySet().iterator();
while (iter.hasNext())
{
Registration r = iter.next();
String s = compatMap.get(r);
if (s.equals(clazz))
{
doLoad(s);
}
}
}
private void doLoad(String clazz)
{
try
{
EnderCore.logger.info("[Compat] Loading compatability class " + clazz);
Class<?> compat = Class.forName(clazz);
compat.getDeclaredMethod(ICompat.METHOD_NAME).invoke(null);
}
catch (NoSuchMethodException e)
{
EnderCore.logger.error("[Compat] ICompatability class {} did not contain static method {}!", clazz, ICompat.METHOD_NAME);
e.printStackTrace();
}
catch (InvocationTargetException e)
{
throw new RuntimeException("Error in compatability class " + clazz, e.getTargetException());
}
catch (Throwable e)
{
EnderCore.logger.error("[Compat] An unknown error was thrown loading class {}.", clazz);
e.printStackTrace();
}
}
}
|
minecreatr/EnderCore
|
src/main/java/com/enderio/core/common/compat/CompatRegistry.java
|
Java
|
cc0-1.0
| 3,350
|
# Listă de cursuri, seminarii și modele de examen pentru Facultatea de Matematică și Informatică
Toate linkurile sunt funcționale și vor fi hostate pe Dropbox-ul meu. Cele mai bune resurse în afară de wiki-ul meu mai sunt:
* https://github.com/aliasbind/Sesiune
* http://fmi.is-a-geek.net/ - am făcut și un [mirror](https://www.dropbox.com/s/8ncr98owj69b8aj/fmi-is-a-geek.zip?dl=0) în caz că pică site-ul
* https://drive.google.com/drive/u/0/#folders/0BxI0dBW6RL4mcEdWeVR3LUNwRDQ
* https://drive.google.com/folderview?id=0B0-Ney8GB2GyS2hRcFRQRFpxdlU&u
# Unde găsesc teme?
* https://github.com/palcu/homework
* https://github.com/kitz99
* https://github.com/tvararu/
* https://github.com/aliasbind
* https://github.com/adrian-budau
* https://github.com/andrei14vl/
* https://github.com/rdragos
# Grupuri Facebook
Majoritatea subiectelor și materialelor au fost adunate de pe diferite grupuri publice:
* [FMI Unibuc](https://www.facebook.com/groups/126743390712654/)
* [FMI 2013](https://www.facebook.com/groups/fmi2013.ub/)
* [FMI 2012](https://www.facebook.com/groups/fmi2012/)
* [FMI 2014](https://www.facebook.com/groups/FMI2014/)
* [FMI-UB/INFO/2013-2016](https://www.facebook.com/groups/fmi.ub.info/)
* [FMI-UB/INFO/2014-2017](https://www.facebook.com/groups/310345475799027)
* [FMI 2015](https://www.facebook.com/groups/fmi.ub.2015/)
* [FMI-UB/INFO 2015-2018](https://www.facebook.com/groups/1662350980651951/)
|
Vlaaaaaaad/fmi-1
|
README.md
|
Markdown
|
cc0-1.0
| 1,439
|
/**
* Copyright (c) 2010-2021 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.hydrawise.internal.api.model;
import java.util.LinkedList;
import java.util.List;
/**
* The {@link StatusScheduleResponse} class models the Status and Schedule response message
*
* @author Dan Cunningham - Initial contribution
*/
public class StatusScheduleResponse extends LocalScheduleResponse {
public Integer controllerId;
public Integer customerId;
public Integer userId;
public Integer nextpoll;
public List<Sensor> sensors = new LinkedList<>();
public String message;
public String obsRain;
public String obsRainWeek;
public String obsMaxtemp;
public Integer obsRainUpgrade;
public String obsRainText;
public String obsCurrenttemp;
public String wateringTime;
public Integer waterSaving;
public String lastContact;
public List<Forecast> forecast = new LinkedList<>();
public String status;
public String statusIcon;
}
|
paulianttila/openhab2
|
bundles/org.openhab.binding.hydrawise/src/main/java/org/openhab/binding/hydrawise/internal/api/model/StatusScheduleResponse.java
|
Java
|
epl-1.0
| 1,330
|
/*******************************************************************************
* Copyright (c) 1997, 2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.webcontainer.extension;
import java.util.List;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import com.ibm.wsspi.webcontainer.extension.ExtensionProcessor;
import com.ibm.wsspi.webcontainer.metadata.WebComponentMetaData;
import com.ibm.wsspi.webcontainer.servlet.IServletWrapper;
public class ExtHandshakeVHostExtensionProcessor implements ExtensionProcessor {
public ExtHandshakeVHostExtensionProcessor() {
}
/* (non-Javadoc)
* @see com.ibm.wsspi.webcontainer.extension.ExtensionProcessor#getPatternList()
*/
@SuppressWarnings("unchecked")
public List getPatternList() {
return null;
}
/* (non-Javadoc)
* @see com.ibm.wsspi.webcontainer.RequestProcessor#handleRequest(javax.servlet.ServletRequest, javax.servlet.ServletResponse)
*/
public void handleRequest(ServletRequest req, ServletResponse res) throws Exception {
}
public String getName() {
return "ExtHandshakeVHostExtensionProcessor";
}
public boolean isInternal() {
return false;
}
public IServletWrapper getServletWrapper(ServletRequest req,
ServletResponse resp) {
// TODO Auto-generated method stub
return null;
}
public WebComponentMetaData getMetaData() {
// TODO Auto-generated method stub
return null;
}
}
|
OpenLiberty/open-liberty
|
dev/com.ibm.ws.webcontainer/src/com/ibm/ws/webcontainer/extension/ExtHandshakeVHostExtensionProcessor.java
|
Java
|
epl-1.0
| 1,879
|
/*
* Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.yangtools.yang.data.impl.schema.transform;
import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
/**
* Factory for different normalized node serializers.
*
* @param <E>
* type of resulting/serialized element from NormalizedNode
*/
public interface FromNormalizedNodeSerializerFactory<E> {
FromNormalizedNodeSerializer<E, AugmentationNode, AugmentationSchema> getAugmentationNodeSerializer();
FromNormalizedNodeSerializer<E, ChoiceNode, ChoiceSchemaNode> getChoiceNodeSerializer();
FromNormalizedNodeSerializer<E, ContainerNode, ContainerSchemaNode> getContainerNodeSerializer();
FromNormalizedNodeSerializer<E, LeafNode<?>, LeafSchemaNode> getLeafNodeSerializer();
FromNormalizedNodeSerializer<E, LeafSetEntryNode<?>, LeafListSchemaNode> getLeafSetEntryNodeSerializer();
FromNormalizedNodeSerializer<E, LeafSetNode<?>, LeafListSchemaNode> getLeafSetNodeSerializer();
FromNormalizedNodeSerializer<E, MapEntryNode, ListSchemaNode> getMapEntryNodeSerializer();
FromNormalizedNodeSerializer<E, MapNode, ListSchemaNode> getMapNodeSerializer();
FromNormalizedNodeSerializer<E, UnkeyedListNode, ListSchemaNode> getUnkeyedListNodeSerializer();
FromNormalizedNodeSerializer<E, AnyXmlNode, AnyXmlSchemaNode> getAnyXmlNodeSerializer();
}
|
522986491/yangtools
|
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/FromNormalizedNodeSerializerFactory.java
|
Java
|
epl-1.0
| 2,724
|
/**
* Copyright (c) 2005-2013 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Eclipse Public License (EPL).
* Please see the license.txt included with this distribution for details.
* Any modifications to this file must keep this entire header intact.
*/
/*
* Created on 13/07/2005
*/
package org.python.pydev.core.docutils;
import java.util.Iterator;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentExtension3;
import org.eclipse.jface.text.IDocumentPartitionerExtension2;
import org.python.pydev.core.IPythonPartitions;
import org.python.pydev.shared_core.string.BaseParsingUtils;
import org.python.pydev.shared_core.string.FastStringBuffer;
import org.python.pydev.shared_core.string.StringUtils;
/**
* Helper class for parsing python code.
*
* @author Fabio
*/
public abstract class ParsingUtils extends BaseParsingUtils implements IPythonPartitions {
public ParsingUtils(boolean throwSyntaxError) {
super(throwSyntaxError);
}
/**
* Class that handles char[]
*
* @author Fabio
*/
private static final class FixedLenCharArrayParsingUtils extends ParsingUtils {
private final char[] cs;
private final int len;
public FixedLenCharArrayParsingUtils(char[] cs, boolean throwSyntaxError, int len) {
super(throwSyntaxError);
this.cs = cs;
this.len = len;
}
@Override
public int len() {
return len;
}
@Override
public char charAt(int i) {
return cs[i];
}
}
/**
* Class that handles FastStringBuffer
*
* @author Fabio
*/
private static final class FixedLenFastStringBufferParsingUtils extends ParsingUtils {
private final FastStringBuffer cs;
private final int len;
public FixedLenFastStringBufferParsingUtils(FastStringBuffer cs, boolean throwSyntaxError, int len) {
super(throwSyntaxError);
this.cs = cs;
this.len = len;
}
@Override
public int len() {
return len;
}
@Override
public char charAt(int i) {
return cs.charAt(i);
}
}
/**
* Class that handles StringBuffer
*
* @author Fabio
*/
private static final class FixedLenStringBufferParsingUtils extends ParsingUtils {
private final StringBuffer cs;
private final int len;
public FixedLenStringBufferParsingUtils(StringBuffer cs, boolean throwSyntaxError, int len) {
super(throwSyntaxError);
this.cs = cs;
this.len = len;
}
@Override
public int len() {
return len;
}
@Override
public char charAt(int i) {
return cs.charAt(i);
}
}
/**
* Class that handles String
*
* @author Fabio
*/
private static final class FixedLenStringParsingUtils extends ParsingUtils {
private final String cs;
private final int len;
public FixedLenStringParsingUtils(String cs, boolean throwSyntaxError, int len) {
super(throwSyntaxError);
this.cs = cs;
this.len = len;
}
@Override
public int len() {
return len;
}
@Override
public char charAt(int i) {
return cs.charAt(i);
}
}
/**
* Class that handles String
*
* @author Fabio
*/
private static final class FixedLenIDocumentParsingUtils extends ParsingUtils {
private final IDocument cs;
private final int len;
public FixedLenIDocumentParsingUtils(IDocument cs, boolean throwSyntaxError, int len) {
super(throwSyntaxError);
this.cs = cs;
this.len = len;
}
@Override
public int len() {
return len;
}
@Override
public char charAt(int i) {
try {
return cs.getChar(i);
} catch (BadLocationException e) {
throw new RuntimeException(e);
}
}
}
/**
* Class that handles FastStringBuffer
*
* @author Fabio
*/
private static final class FastStringBufferParsingUtils extends ParsingUtils {
private final FastStringBuffer cs;
public FastStringBufferParsingUtils(FastStringBuffer cs, boolean throwSyntaxError) {
super(throwSyntaxError);
this.cs = cs;
}
@Override
public int len() {
return cs.length();
}
@Override
public char charAt(int i) {
return cs.charAt(i);
}
}
/**
* Class that handles StringBuffer
*
* @author Fabio
*/
private static final class StringBufferParsingUtils extends ParsingUtils {
private final StringBuffer cs;
public StringBufferParsingUtils(StringBuffer cs, boolean throwSyntaxError) {
super(throwSyntaxError);
this.cs = cs;
}
@Override
public int len() {
return cs.length();
}
@Override
public char charAt(int i) {
return cs.charAt(i);
}
}
/**
* Class that handles String
*
* @author Fabio
*/
private static final class IDocumentParsingUtils extends ParsingUtils {
private final IDocument cs;
public IDocumentParsingUtils(IDocument cs, boolean throwSyntaxError) {
super(throwSyntaxError);
this.cs = cs;
}
@Override
public int len() {
return cs.getLength();
}
@Override
public char charAt(int i) {
try {
return cs.getChar(i);
} catch (BadLocationException e) {
return '\0'; // For documents this may really happen as their len may change under the hood...
}
}
}
/**
* Factory method to create it (and by default doesn't throw any errors).
*/
public static ParsingUtils create(Object cs) {
return create(cs, false);
}
/**
* Factory method to create it. Object len may not be changed afterwards.
*/
public static ParsingUtils create(Object cs, boolean throwSyntaxError, int len) {
if (cs instanceof char[]) {
char[] cs2 = (char[]) cs;
return new FixedLenCharArrayParsingUtils(cs2, throwSyntaxError, len);
}
if (cs instanceof FastStringBuffer) {
FastStringBuffer cs2 = (FastStringBuffer) cs;
return new FixedLenFastStringBufferParsingUtils(cs2, throwSyntaxError, len);
}
if (cs instanceof StringBuffer) {
StringBuffer cs2 = (StringBuffer) cs;
return new FixedLenStringBufferParsingUtils(cs2, throwSyntaxError, len);
}
if (cs instanceof String) {
String cs2 = (String) cs;
return new FixedLenStringParsingUtils(cs2, throwSyntaxError, len);
}
if (cs instanceof IDocument) {
IDocument cs2 = (IDocument) cs;
return new FixedLenIDocumentParsingUtils(cs2, throwSyntaxError, len);
}
throw new RuntimeException("Don't know how to create instance for: " + cs.getClass());
}
/**
* Factory method to create it.
*/
public static ParsingUtils create(Object cs, boolean throwSyntaxError) {
if (cs instanceof char[]) {
char[] cs2 = (char[]) cs;
return new FixedLenCharArrayParsingUtils(cs2, throwSyntaxError, cs2.length);
}
if (cs instanceof FastStringBuffer) {
FastStringBuffer cs2 = (FastStringBuffer) cs;
return new FastStringBufferParsingUtils(cs2, throwSyntaxError);
}
if (cs instanceof StringBuffer) {
StringBuffer cs2 = (StringBuffer) cs;
return new StringBufferParsingUtils(cs2, throwSyntaxError);
}
if (cs instanceof String) {
String cs2 = (String) cs;
return new FixedLenStringParsingUtils(cs2, throwSyntaxError, cs2.length());
}
if (cs instanceof IDocument) {
IDocument cs2 = (IDocument) cs;
return new IDocumentParsingUtils(cs2, throwSyntaxError);
}
throw new RuntimeException("Don't know how to create instance for: " + cs.getClass());
}
//API methods --------------------------------------------------------------------
/**
* @param buf used to add the comments contents (out) -- if it's null, it'll simply advance to the position and
* return it.
* @param i the # position
* @return the end of the comments position (end of document or new line char)
* @note the new line char (\r or \n) will be added as a part of the comment.
*/
public int eatComments(FastStringBuffer buf, int i) {
return eatComments(buf, i, true);
}
/**
* @param addNewLine whether the '\r' or '\n' should be added or not (if false
* will return the char right before \r or \n).
*/
public int eatComments(FastStringBuffer buf, int i, boolean addNewLine) {
int len = len();
char c = '\0';
while (i < len && (c = charAt(i)) != '\n' && c != '\r') {
if (buf != null) {
buf.append(c);
}
i++;
}
if (!addNewLine) {
if (c == '\r' || c == '\n') {
i--;
return i;
}
}
if (i < len) {
// c must be '\r' or '\n' at this point
if (buf != null) {
buf.append(c);
}
if (c == '\r') {
if (i + 1 < len && charAt(i + 1) == '\n') {
i++;
if (buf != null) {
buf.append('\n');
}
}
}
}
return i;
}
/**
* This is a special construct to try to get an import.
*/
public int eatFromImportStatement(FastStringBuffer buf, int i) throws SyntaxErrorException {
int len = len();
char c = '\0';
if (i + 5 <= len) {
// 'from '
if (charAt(i) == 'f' && charAt(i + 1) == 'r' && charAt(i + 2) == 'o' && charAt(i + 3) == 'm'
&& ((c = charAt(i + 4)) == ' ' || c == '\t')) {
i += 5;
if (buf != null) {
buf.append("from");
buf.append(c);
}
} else {
return i; //Walk nothing
}
} else {
return i;
}
while (i < len && (c = charAt(i)) != '\n' && c != '\r') {
if (c == '#') {
// Just ignore any comment
i = eatComments(null, i);
} else if (c == '\\') {
char c2;
if (i + 1 < len && ((c2 = charAt(i + 1)) == '\n' || c2 == '\r')) {
if (buf != null) {
buf.append(c);
buf.append(c2);
}
i++;
if (c2 == '\r') {
//get \r too
if (i + 1 < len) {
c2 = charAt(i + 1);
if (c2 == '\n') {
if (buf != null) {
buf.append(c2);
}
i++;
}
}
}
}
i++;
} else if (c == '(') {
if (buf != null) {
buf.append(c);
}
i = eatPar(i, buf);
if (buf != null) {
if (i < len) {
buf.append(charAt(i));
}
}
i++;
} else {
if (buf != null) {
buf.append(c);
}
i++;
}
}
return i;
}
/**
* @param buf used to add the spaces (out) -- if it's null, it'll simply advance to the position and
* return it.
* @param i the first ' ' position
* @return the position of the last space found
*/
public int eatWhitespaces(FastStringBuffer buf, int i) {
int len = len();
char c;
while (i < len && (c = charAt(i)) == ' ') {
if (buf != null) {
buf.append(c);
}
i++;
}
//go back to the last space found
i--;
return i;
}
public int eatLiteralsBackwards(FastStringBuffer buf, int i) throws SyntaxErrorException {
//ok, current pos is ' or "
//check if we're starting a single or multiline comment...
char curr = charAt(i);
if (curr != '"' && curr != '\'') {
throw new RuntimeException("Wrong location to eat literals. Expecting ' or \" Found:" + curr);
}
int j = getLiteralStart(i, curr);
if (buf != null) {
for (int k = j; k <= i; k++) {
buf.append(charAt(k));
}
}
return j;
}
/**
* Equivalent to eatLiterals(buf, startPos, false) .
*
* @param buf
* @param startPos
* @return
* @throws SyntaxErrorException
*/
public int eatLiterals(FastStringBuffer buf, int startPos) throws SyntaxErrorException {
return eatLiterals(buf, startPos, false);
}
/**
* Returns the index of the last character of the current string literal
* beginning at startPos, optionally copying the contents of the literal to
* an output buffer.
*
* @param buf
* If non-null, the contents of the literal are appended to this
* object.
* @param startPos
* The position of the initial ' or "
* @param rightTrimMultiline
* Whether to right trim the whitespace of each line in multi-
* line literals when appending to buf .
* @return The position of the last ' or " character of the literal (or the
* end of the document).
*/
public int eatLiterals(FastStringBuffer buf, int startPos, boolean rightTrimMultiline) throws SyntaxErrorException {
char startChar = charAt(startPos);
if (startChar != '"' && startChar != '\'') {
throw new RuntimeException(
"Wrong location to eat literals. Expecting ' or \". Found: >>" + startChar + "<<");
}
// Retrieves the correct end position for single- and multi-line
// string literals.
int endPos = getLiteralEnd(startPos, startChar);
if (buf != null) {
boolean rightTrim = rightTrimMultiline && isMultiLiteral(startPos, startChar);
int lastPos = Math.min(endPos, len() - 1);
for (int i = startPos; i <= lastPos; i++) {
char ch = charAt(i);
if (rightTrim && (ch == '\r' || ch == '\n')) {
buf.rightTrimWhitespacesAndTabs();
}
buf.append(ch);
}
}
return endPos;
}
/**
* @param i index we are analyzing it
* @param curr current char
* @return the end of the multiline literal
* @throws SyntaxErrorException
*/
public int getLiteralStart(int i, char curr) throws SyntaxErrorException {
boolean multi = isMultiLiteralBackwards(i, curr);
int j;
if (multi) {
j = findPreviousMulti(i - 3, curr);
} else {
j = findPreviousSingle(i - 1, curr);
}
return j;
}
/**
* @param i index we are analyzing it
* @param curr current char
* @return the end of the multiline literal
* @throws SyntaxErrorException
*/
public int getLiteralEnd(int i, char curr) throws SyntaxErrorException {
boolean multi = isMultiLiteral(i, curr);
int j;
if (multi) {
j = findNextMulti(i + 3, curr);
} else {
j = findNextSingle(i + 1, curr);
}
return j;
}
/**
* @param i the ' or " position
* @param buf used to add the comments contents (out)
* @return the end of the literal position (or end of document)
* @throws SyntaxErrorException
*/
public int eatPar(int i, FastStringBuffer buf) throws SyntaxErrorException {
return eatPar(i, buf, '(');
}
/**
* @param i the index where we should start getting chars
* @param buf the buffer that should be filled with the contents gotten (if null, they're ignored)
* @return the index where the parsing stopped. It should always be the character just before the new line
* (or before the end of the document).
* @throws SyntaxErrorException
*/
public int getFullFlattenedLine(int i, FastStringBuffer buf) throws SyntaxErrorException {
char c = this.charAt(i);
int len = len();
boolean ignoreNextNewLine = false;
while (i < len) {
c = charAt(i);
i++;
if (c == '\'' || c == '"') { //ignore comments or multiline comments...
i = eatLiterals(null, i - 1) + 1;
} else if (c == '#') {
i = eatComments(null, i - 1, false) + 1;
break;
} else if (c == '(' || c == '[' || c == '{') { //open par.
i = eatPar(i - 1, null, c) + 1;
} else if (c == '\r' || c == '\n') {
if (!ignoreNextNewLine) {
i--;
break;
}
// ignoreNextNewLine == true
if (i < len && c == '\r') {
//deal with \r\n if found...
if (charAt(i) == '\n') {
i++;
}
}
} else if (c == '\\') {
ignoreNextNewLine = true;
continue;
} else {
if (buf != null) {
buf.append(c);
}
}
ignoreNextNewLine = false;
}
i--; //we have to do that because we passed 1 char in the beginning of the while.
return i;
}
/**
* @param buf if null, it'll simply advance without adding anything to the buffer.
*
* IMPORTANT: Won't add all to the buffer, only the chars found at this level (i.e.: not contents inside another [] or ()).
* @throws SyntaxErrorException
*/
public int eatPar(int i, FastStringBuffer buf, char par) throws SyntaxErrorException {
char c = ' ';
char closingPar = StringUtils.getPeer(par);
int j = i + 1;
int len = len();
while (j < len && (c = charAt(j)) != closingPar) {
j++;
if (c == '\'' || c == '"') { //ignore comments or multiline comments...
j = eatLiterals(null, j - 1) + 1;
} else if (c == '#') {
j = eatComments(null, j - 1) + 1;
} else if (c == par) { //open another par.
j = eatPar(j - 1, null, par) + 1;
} else {
if (buf != null) {
buf.append(c);
}
}
}
if (this.throwSyntaxError && c != closingPar) {
throw new SyntaxErrorException();
}
if (j >= len) {
// We could overflow in eatPar(j - 1, null, par) + 1;
j = len;
}
return j;
}
/**
* discover the position of the closing quote
* @throws SyntaxErrorException
*/
public int findNextSingle(int i, char curr) throws SyntaxErrorException {
boolean ignoreNext = false;
int len = len();
while (i < len) {
char c = charAt(i);
if (!ignoreNext && c == curr) {
return i;
}
if (!ignoreNext) {
if (c == '\\') { //escaped quote, ignore the next char even if it is a ' or "
ignoreNext = true;
}
} else {
ignoreNext = false;
}
i++;
}
if (throwSyntaxError) {
throw new SyntaxErrorException();
}
return i;
}
/**
* discover the position of the closing quote
* @throws SyntaxErrorException
*/
public int findPreviousSingle(int i, char curr) throws SyntaxErrorException {
while (i >= 0) {
char c = charAt(i);
if (c == curr) {
if (i > 0) {
if (charAt(i - 1) == '\\') {
//escaped
i--;
continue;
}
}
return i;
}
i--;
}
if (throwSyntaxError) {
throw new SyntaxErrorException();
}
return i;
}
/**
* check the end of the multiline quote
* @throws SyntaxErrorException
*/
public int findNextMulti(int i, char curr) throws SyntaxErrorException {
int len = len();
while (i + 2 < len) {
char c = charAt(i);
if (c == curr && charAt(i + 1) == curr && charAt(i + 2) == curr) {
return i + 2;
}
i++;
if (c == '\\') { //this is for escaped quotes
i++;
}
}
if (throwSyntaxError) {
throw new SyntaxErrorException();
}
if (len < i + 2) {
return len;
}
return i + 2;
}
/**
* check the end of the multiline quote
* @throws SyntaxErrorException
*/
public int findPreviousMulti(int i, char curr) throws SyntaxErrorException {
while (i - 2 >= 0) {
char c = charAt(i);
if (c == curr && charAt(i - 1) == curr && charAt(i - 2) == curr) {
return i - 2;
}
i--;
}
if (throwSyntaxError) {
throw new SyntaxErrorException();
}
//Got to the start.
return 0;
}
//STATIC INTERFACES FROM NOW ON ----------------------------------------------------------------
//STATIC INTERFACES FROM NOW ON ----------------------------------------------------------------
//STATIC INTERFACES FROM NOW ON ----------------------------------------------------------------
//STATIC INTERFACES FROM NOW ON ----------------------------------------------------------------
//STATIC INTERFACES FROM NOW ON ----------------------------------------------------------------
/**
* @param i current position (should have a ' or ")
* @param curr the current char (' or ")
* @return whether we are at the end of a multi line literal or not.
*/
public boolean isMultiLiteralBackwards(int i, char curr) {
if (0 > i - 2) {
return false;
}
if (charAt(i - 1) == curr && charAt(i - 2) == curr) {
return true;
}
return false;
}
/**
* @param i current position (should have a ' or ")
* @param curr the current char (' or ")
* @return whether we are at the start of a multi line literal or not.
*/
public boolean isMultiLiteral(int i, char curr) {
int len = len();
if (len <= i + 2) {
return false;
}
if (charAt(i + 1) == curr && charAt(i + 2) == curr) {
return true;
}
return false;
}
public static void removeCommentsWhitespacesAndLiterals(FastStringBuffer buf, boolean throwSyntaxError)
throws SyntaxErrorException {
removeCommentsWhitespacesAndLiterals(buf, true, throwSyntaxError);
}
/**
* Removes all the comments, whitespaces and literals from a FastStringBuffer (might be useful when
* just finding matches for something).
*
* NOTE: the literals and the comments are changed for spaces (if we don't remove them too)
*
* @param buf the buffer from where things should be removed.
* @param whitespacesToo: are you sure about the whitespaces?
* @throws SyntaxErrorException
*/
public static void removeCommentsWhitespacesAndLiterals(FastStringBuffer buf, boolean whitespacesToo,
boolean throwSyntaxError) throws SyntaxErrorException {
ParsingUtils parsingUtils = create(buf, throwSyntaxError);
for (int i = 0; i < buf.length(); i++) { //The length can'n be extracted at this point as the buffer may change its size.
char ch = buf.charAt(i);
if (ch == '#') {
int j = i;
int len = buf.length();
while (j < len && ch != '\n' && ch != '\r') {
ch = buf.charAt(j);
j++;
}
buf.delete(i, j);
i--;
} else if (ch == '\'' || ch == '"') {
int j = parsingUtils.getLiteralEnd(i, ch);
if (whitespacesToo) {
buf.delete(i, j + 1);
} else {
for (int k = 0; i + k < j + 1; k++) {
buf.replace(i + k, i + k + 1, " ");
}
}
}
}
if (whitespacesToo) {
buf.removeWhitespaces();
}
}
public static void removeLiterals(FastStringBuffer buf, boolean throwSyntaxError) throws SyntaxErrorException {
ParsingUtils parsingUtils = create(buf, throwSyntaxError);
for (int i = 0; i < buf.length(); i++) {
char ch = buf.charAt(i);
if (ch == '#') {
//just past through comments
while (i < buf.length() && ch != '\n' && ch != '\r') {
ch = buf.charAt(i);
i++;
}
}
if (ch == '\'' || ch == '"') {
int j = parsingUtils.getLiteralEnd(i, ch);
for (int k = 0; i + k < j + 1; k++) {
buf.replace(i + k, i + k + 1, " ");
}
}
}
}
public static Iterator<String> getNoLiteralsOrCommentsIterator(IDocument doc) {
return new PyDocIterator(doc);
}
public static void removeCommentsAndWhitespaces(FastStringBuffer buf) {
for (int i = 0; i < buf.length(); i++) {
char ch = buf.charAt(i);
if (ch == '#') {
int j = i;
while (j < buf.length() - 1 && ch != '\n' && ch != '\r') {
j++;
ch = buf.charAt(j);
}
buf.delete(i, j);
}
}
int length = buf.length();
for (int i = length - 1; i >= 0; i--) {
char ch = buf.charAt(i);
if (Character.isWhitespace(ch)) {
buf.deleteCharAt(i);
}
}
}
/**
* @param initial the document
* @param currPos the offset we're interested in
* @return the content type of the current position
*
* The version with the IDocument as a parameter should be preffered, as
* this one can be much slower (still, it is an alternative in tests or
* other places that do not have document access), but keep in mind
* that it may be slow.
*/
public static String getContentType(String initial, int currPos) {
FastStringBuffer buf = new FastStringBuffer(initial, 0);
ParsingUtils parsingUtils = create(initial);
String curr = PY_DEFAULT;
for (int i = 0; i < buf.length() && i < currPos; i++) {
char ch = buf.charAt(i);
curr = PY_DEFAULT;
if (ch == '#') {
curr = PY_COMMENT;
int j = i;
while (j < buf.length() - 1 && ch != '\n' && ch != '\r') {
j++;
ch = buf.charAt(j);
}
i = j;
}
if (i >= currPos) {
return curr;
}
if (ch == '\'' || ch == '"') {
boolean multi = parsingUtils.isMultiLiteral(i, ch);
if (multi) {
curr = PY_MULTILINE_BYTES1;
if (ch == '"') {
curr = PY_MULTILINE_BYTES2;
}
} else {
curr = PY_SINGLELINE_BYTES1;
if (ch == '"') {
curr = PY_SINGLELINE_BYTES2;
}
}
try {
if (multi) {
i = parsingUtils.findNextMulti(i + 3, ch);
} else {
i = parsingUtils.findNextSingle(i + 1, ch);
}
} catch (SyntaxErrorException e) {
throw new RuntimeException(e);
}
if (currPos < i) {
return curr; //found inside
}
if (currPos == i) {
if (PY_SINGLELINE_BYTES1.equals(curr) || PY_SINGLELINE_BYTES2.equals(curr)) {
return curr;
}
}
//if currPos == i, this means it'll go to the next partition (we always prefer open
//partitions here, so, the last >>'<< from a string is actually treated as the start
//of the next partition).
curr = PY_DEFAULT;
}
}
return curr;
}
/**
* @param document the document we want to get info on
* @param i the document offset we're interested in
* @return the content type at that position (according to IPythonPartitions)
*
* Uses the default if the partitioner is not set in the document (for testing purposes)
*/
public static String getContentType(IDocument document, int i) {
IDocumentExtension3 docExtension = (IDocumentExtension3) document;
IDocumentPartitionerExtension2 partitioner = (IDocumentPartitionerExtension2) docExtension
.getDocumentPartitioner(IPythonPartitions.PYTHON_PARTITION_TYPE);
if (partitioner != null) {
return partitioner.getContentType(i, true);
}
return getContentType(document.get(), i);
}
public static String makePythonParseable(String code, String delimiter) {
return makePythonParseable(code, delimiter, new FastStringBuffer());
}
/**
* Ok, this method will get some code and make it suitable for putting at a shell
* @param code the initial code we'll make parseable
* @param delimiter the delimiter we should use
* @return a String that can be passed to the shell
*/
public static String makePythonParseable(String code, String delimiter, FastStringBuffer lastLine) {
FastStringBuffer buffer = new FastStringBuffer();
FastStringBuffer currLine = new FastStringBuffer();
//we may have line breaks with \r\n, or only \n or \r
boolean foundNewLine = false;
boolean foundNewLineAtChar;
boolean lastWasNewLine = false;
if (lastLine.length() > 0) {
lastWasNewLine = true;
}
for (int i = 0; i < code.length(); i++) {
foundNewLineAtChar = false;
char c = code.charAt(i);
if (c == '\r') {
if (i + 1 < code.length() && code.charAt(i + 1) == '\n') {
i++; //skip the \n
}
foundNewLineAtChar = true;
} else if (c == '\n') {
foundNewLineAtChar = true;
}
if (!foundNewLineAtChar) {
if (lastWasNewLine && !Character.isWhitespace(c)) {
if (lastLine.length() > 0 && Character.isWhitespace(lastLine.charAt(0))) {
buffer.append(delimiter);
}
}
currLine.append(c);
lastWasNewLine = false;
} else {
lastWasNewLine = true;
}
if (foundNewLineAtChar || i == code.length() - 1) {
if (!PySelection.containsOnlyWhitespaces(currLine.toString())) {
buffer.append(currLine);
lastLine = currLine;
currLine = new FastStringBuffer();
buffer.append(delimiter);
foundNewLine = true;
} else { //found a line only with whitespaces
currLine = new FastStringBuffer();
}
}
}
if (!foundNewLine) {
buffer.append(delimiter);
} else {
if (!StringUtils.endsWith(buffer, '\r') && !StringUtils.endsWith(buffer, '\n')) {
buffer.append(delimiter);
}
if (lastLine.length() > 0 && Character.isWhitespace(lastLine.charAt(0))
&& (code.indexOf('\r') != -1 || code.indexOf('\n') != -1)) {
buffer.append(delimiter);
}
}
return buffer.toString();
}
public static String removeComments(String line) {
int i = line.indexOf('#');
if (i != -1) {
return line.substring(0, i);
}
return line;
}
public static boolean isStringContentType(String contentType) {
return IPythonPartitions.PY_MULTILINE_BYTES1.equals(contentType)
|| IPythonPartitions.PY_MULTILINE_BYTES2.equals(contentType)
|| IPythonPartitions.PY_SINGLELINE_BYTES1.equals(contentType)
|| IPythonPartitions.PY_SINGLELINE_BYTES2.equals(contentType)
|| IPythonPartitions.PY_MULTILINE_UNICODE1.equals(contentType)
|| IPythonPartitions.PY_MULTILINE_UNICODE2.equals(contentType)
|| IPythonPartitions.PY_SINGLELINE_UNICODE1.equals(contentType)
|| IPythonPartitions.PY_SINGLELINE_UNICODE2.equals(contentType)
|| IPythonPartitions.PY_MULTILINE_BYTES_OR_UNICODE1.equals(contentType)
|| IPythonPartitions.PY_MULTILINE_BYTES_OR_UNICODE2.equals(contentType)
|| IPythonPartitions.PY_SINGLELINE_BYTES_OR_UNICODE1.equals(contentType)
|| IPythonPartitions.PY_SINGLELINE_BYTES_OR_UNICODE2.equals(contentType)
;
}
public static boolean isCommentContentType(String contentType) {
return IPythonPartitions.PY_COMMENT.equals(contentType);
}
public static boolean isStringPartition(IDocument document, int offset) {
String contentType = getContentType(document, offset);
return isStringContentType(contentType);
}
public static boolean isCommentPartition(IDocument document, int offset) {
String contentType = getContentType(document, offset);
return isCommentContentType(contentType);
}
public static String removeCalls(String activationToken) {
ParsingUtils parsingUtils = ParsingUtils.create(activationToken);
FastStringBuffer buf = new FastStringBuffer(activationToken.length());
int i = 0;
while (true) {
int nextParI = parsingUtils.findNextChar(i, '(');
if (nextParI == -1) {
break;
}
buf.append(activationToken.substring(i, nextParI));
try {
int j = parsingUtils.eatPar(nextParI, null);
if (j != -1) {
i = j;
}
} catch (SyntaxErrorException e) {
}
i++;
}
if (i < parsingUtils.len()) {
//Add the remainder of the string if it didn't end with a ')'.
buf.append(activationToken.substring(i));
}
return buf.toString();
}
public static int matchClass(int currIndex, char[] cs, int length) {
if (currIndex + 5 >= length) {
return -1;
}
if (cs[currIndex + 1] == 'l' && cs[currIndex + 2] == 'a' && cs[currIndex + 3] == 's'
&& cs[currIndex + 4] == 's' && Character.isWhitespace(cs[currIndex + 5])) {
return currIndex + 5;
}
return -1;
}
public static int matchFunction(int currIndex, char[] cs, int length) {
if (currIndex + 3 >= length) {
return -1;
}
if (cs[currIndex + 1] == 'e' && cs[currIndex + 2] == 'f' && Character
.isWhitespace(cs[currIndex + 3])) {
return currIndex + 3;
}
return -1;
}
public static int matchAsyncFunction(int currIndex, char[] cs, int length) {
if (currIndex + 5 >= length) {
return -1;
}
if (cs[currIndex + 1] == 's' && cs[currIndex + 2] == 'y'
&& cs[currIndex + 3] == 'n' && cs[currIndex + 4] == 'c' && Character
.isWhitespace(cs[currIndex + 5])) {
int i = currIndex + 6;
while (i < length && Character.isWhitespace(cs[i])) {
i += 1;
}
if (i + 3 >= length) {
return -1;
}
if (cs[i] == 'd' && cs[i + 1] == 'e' && cs[i + 2] == 'f' && Character
.isWhitespace(cs[i + 3])) {
return i + 3;
}
}
return -1;
}
}
|
fabioz/Pydev
|
plugins/org.python.pydev.core/src/org/python/pydev/core/docutils/ParsingUtils.java
|
Java
|
epl-1.0
| 38,039
|
function fileSelect(evt) {
alert("hep");
if (window.File && window.FileReader && window.FileList && window.Blob) {
var files = evt.target.files;
var result = '';
var file;
for (var i = 0; file = files[i]; i++) {
// if the file is not an image, continue
// if (!file.type.match('image.*')) {
// continue;
// }
reader = new FileReader();
reader.onload = (function (tFile) {
return function (evt) {
pdfdata = evt.target.result;
var div = document.createElement('div');
processPdf(evt.target.result);
// div.innerHTML = '<img style="width: 90px;" src="' + evt.target.result + '" />';
// document.getElementById('filesInfo').appendChild(div);
};
}(file));
reader.readAsDataURL(file);
}
} else {
alert('The File APIs are not fully supported in this browser.');
}
}
var content = [];
function processPdf(data) {
PDFJS.getDocument(data).then(function(pdf) {
pdfObject = pdf;
// you can now use *pdf* here
for (var i = 1; i <= pdf.numPages; i++) {
pdf.getPage(i).then(function(page) {
pageObject = page;
page.getTextContent().then(function (tc) {
content.push((tc.items || tc).map(function (x) { return x.str; }).join(' '));
});
// you can now use *page* here
var scale = 1.5;
var viewport = page.getViewport(scale);
var canvas = document.getElementById('the-canvas');
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
var renderContext = {
canvasContext: context,
viewport: viewport
};
page.render(renderContext);
});
}
});
}
document.getElementById('filesToUpload').addEventListener('change', fileSelect, false);
function dragOver(evt) {
evt.stopPropagation();
evt.preventDefault();
evt.dataTransfer.dropEffect = 'copy';
}
var dropTarget = document.getElementById('dropTarget');
dropTarget.addEventListener('dragover', dragOver, false);
dropTarget.addEventListener('drop', fileSelect, false);
|
halla/synapticle
|
html/js/readfile.js
|
JavaScript
|
epl-1.0
| 2,364
|
/**
* Copyright (c) 2010-2021 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.modbus.e3dc.internal.handler;
import static org.openhab.binding.modbus.e3dc.internal.E3DCBindingConstants.*;
import static org.openhab.binding.modbus.e3dc.internal.modbus.E3DCModbusConstans.*;
import java.util.BitSet;
import java.util.Optional;
import java.util.OptionalInt;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.modbus.e3dc.internal.E3DCWallboxConfiguration;
import org.openhab.binding.modbus.e3dc.internal.dto.DataConverter;
import org.openhab.binding.modbus.e3dc.internal.dto.WallboxArray;
import org.openhab.binding.modbus.e3dc.internal.dto.WallboxBlock;
import org.openhab.binding.modbus.e3dc.internal.modbus.Data;
import org.openhab.binding.modbus.e3dc.internal.modbus.Data.DataType;
import org.openhab.binding.modbus.e3dc.internal.modbus.Parser;
import org.openhab.core.io.transport.modbus.AsyncModbusFailure;
import org.openhab.core.io.transport.modbus.AsyncModbusReadResult;
import org.openhab.core.io.transport.modbus.ModbusCommunicationInterface;
import org.openhab.core.io.transport.modbus.ModbusReadRequestBlueprint;
import org.openhab.core.io.transport.modbus.ModbusRegisterArray;
import org.openhab.core.io.transport.modbus.ModbusWriteRegisterRequestBlueprint;
import org.openhab.core.library.types.OnOffType;
import org.openhab.core.thing.Bridge;
import org.openhab.core.thing.ChannelUID;
import org.openhab.core.thing.Thing;
import org.openhab.core.thing.ThingStatus;
import org.openhab.core.thing.ThingStatusDetail;
import org.openhab.core.thing.binding.BaseThingHandler;
import org.openhab.core.thing.binding.ThingHandler;
import org.openhab.core.types.Command;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The {@link E3DCWallboxThingHandler} Basic modbus connection towards the E3DC device
*
* @author Bernd Weymann - Initial contribution
*/
@NonNullByDefault
public class E3DCWallboxThingHandler extends BaseThingHandler {
public enum ReadWriteSuccess {
NOT_RECEIVED,
SUCCESS,
FAILED
}
private static final String READ_WRITE_ERROR = "Modbus Data Read/Write Error";
private static final String READ_ERROR = "Modbus Read Error";
private static final String WRITE_ERROR = "Modbus Write Error";
ChannelUID wbAvailableChannel;
ChannelUID wbSunmodeChannel;
ChannelUID wbChargingAbortedChannel;
ChannelUID wbChargingChannel;
ChannelUID wbJackLockedChannel;
ChannelUID wbJackPluggedChannel;
ChannelUID wbSchukoOnChannel;
ChannelUID wbSchukoPluggedChannel;
ChannelUID wbSchukoLockedChannel;
ChannelUID wbSchukoRelay16Channel;
ChannelUID wbRelay16Channel;
ChannelUID wbRelay32Channel;
ChannelUID wb1phaseChannel;
private final Logger logger = LoggerFactory.getLogger(E3DCWallboxThingHandler.class);
private final Parser dataParser = new Parser(DataType.DATA);
private ReadWriteSuccess dataRead = ReadWriteSuccess.NOT_RECEIVED;
private ReadWriteSuccess dataWrite = ReadWriteSuccess.NOT_RECEIVED;
private volatile BitSet currentBitSet = new BitSet(16);
private @Nullable E3DCWallboxConfiguration config;
private @Nullable E3DCThingHandler bridgeHandler;
public E3DCWallboxThingHandler(Thing thing) {
super(thing);
wbAvailableChannel = new ChannelUID(thing.getUID(), WB_AVAILABLE_CHANNEL);
wbSunmodeChannel = new ChannelUID(thing.getUID(), WB_SUNMODE_CHANNEL);
wbChargingAbortedChannel = new ChannelUID(thing.getUID(), WB_CHARGING_ABORTED_CHANNEL);
wbChargingChannel = new ChannelUID(thing.getUID(), WB_CHARGING_CHANNEL);
wbJackLockedChannel = new ChannelUID(thing.getUID(), WB_JACK_LOCKED_CHANNEL);
wbJackPluggedChannel = new ChannelUID(thing.getUID(), WB_JACK_PLUGGED_CHANNEL);
wbSchukoOnChannel = new ChannelUID(thing.getUID(), WB_SCHUKO_ON_CHANNEL);
wbSchukoPluggedChannel = new ChannelUID(thing.getUID(), WB_SCHUKO_PLUGGED_CHANNEL);
wbSchukoLockedChannel = new ChannelUID(thing.getUID(), WB_SCHUKO_LOCKED_CHANNEL);
wbSchukoRelay16Channel = new ChannelUID(thing.getUID(), WB_SCHUKO_RELAY_16A_CHANNEL);
wbRelay16Channel = new ChannelUID(thing.getUID(), WB_RELAY_16A_CHANNEL);
wbRelay32Channel = new ChannelUID(thing.getUID(), WB_RELAY_32A_CHANNEL);
wb1phaseChannel = new ChannelUID(thing.getUID(), WB_1PHASE_CHANNEL);
}
@Override
public void initialize() {
updateStatus(ThingStatus.UNKNOWN);
config = getConfigAs(E3DCWallboxConfiguration.class);
Bridge bridge = getBridge();
if (bridge != null) {
ThingHandler handler = bridge.getHandler();
if (handler != null) {
bridgeHandler = ((E3DCThingHandler) handler);
} else {
logger.warn("Thing Handler null");
}
} else {
logger.warn("Bridge null");
}
}
@Override
public void handleCommand(ChannelUID channelUID, Command command) {
if (command instanceof OnOffType) {
int writeValue = 0;
synchronized (this) {
if (channelUID.getIdWithoutGroup().equals(WB_SUNMODE_CHANNEL)) {
currentBitSet.set(WB_SUNMODE_BIT, command.equals(OnOffType.ON));
} else if (channelUID.getIdWithoutGroup().equals(WB_CHARGING_ABORTED_CHANNEL)) {
currentBitSet.set(WB_CHARGING_ABORTED_BIT, command.equals(OnOffType.ON));
} else if (channelUID.getIdWithoutGroup().equals(WB_SCHUKO_ON_CHANNEL)) {
currentBitSet.set(WB_SCHUKO_ON_BIT, command.equals(OnOffType.ON));
} else if (channelUID.getIdWithoutGroup().equals(WB_1PHASE_CHANNEL)) {
currentBitSet.set(WB_1PHASE_BIT, command.equals(OnOffType.ON));
}
writeValue = DataConverter.toInt(currentBitSet);
logger.debug("Wallbox write {}", writeValue);
}
OptionalInt wallboxId = getWallboxId(config);
if (wallboxId.isPresent()) {
wallboxSet(wallboxId.getAsInt(), writeValue);
}
}
}
/**
* Wallbox Settings can be changed with one Integer
*
* @param wallboxId needed to calculate right register
* @param writeValue integer to be written
*/
public void wallboxSet(int wallboxId, int writeValue) {
E3DCThingHandler localBridgeHandler = bridgeHandler;
if (localBridgeHandler != null) {
ModbusCommunicationInterface comms = localBridgeHandler.getComms();
if (comms != null) {
ModbusRegisterArray regArray = new ModbusRegisterArray(writeValue);
ModbusWriteRegisterRequestBlueprint writeBluePrint = new ModbusWriteRegisterRequestBlueprint(
localBridgeHandler.getSlaveId(), WALLBOX_REG_START + wallboxId, regArray, false, 3);
comms.submitOneTimeWrite(writeBluePrint, result -> {
if (dataWrite != ReadWriteSuccess.SUCCESS) {
dataWrite = ReadWriteSuccess.SUCCESS;
updateStatus();
}
logger.debug("E3DC Modbus write response! {}", result.getResponse().toString());
}, failure -> {
if (dataWrite != ReadWriteSuccess.FAILED) {
dataWrite = ReadWriteSuccess.FAILED;
updateStatus();
}
logger.warn("E3DC Modbus write error! {}", failure.getRequest().toString());
});
}
}
}
private OptionalInt getWallboxId(@Nullable E3DCWallboxConfiguration c) {
if (c != null) {
return OptionalInt.of(c.wallboxId);
} else {
return OptionalInt.empty();
}
}
public void handle(AsyncModbusReadResult result) {
if (dataRead != ReadWriteSuccess.SUCCESS) {
dataRead = ReadWriteSuccess.SUCCESS;
updateStatus();
}
dataParser.handle(result);
Optional<Data> wbArrayOpt = dataParser.parse(DataType.WALLBOX);
if (wbArrayOpt.isPresent()) {
WallboxArray wbArray = (WallboxArray) wbArrayOpt.get();
OptionalInt wallboxId = getWallboxId(config);
if (wallboxId.isPresent()) {
Optional<WallboxBlock> blockOpt = wbArray.getWallboxBlock(wallboxId.getAsInt());
if (blockOpt.isPresent()) {
WallboxBlock block = blockOpt.get();
synchronized (this) {
currentBitSet = block.getBitSet();
}
updateState(wbAvailableChannel, block.wbAvailable);
updateState(wbSunmodeChannel, block.wbSunmode);
updateState(wbChargingAbortedChannel, block.wbChargingAborted);
updateState(wbChargingChannel, block.wbCharging);
updateState(wbJackLockedChannel, block.wbJackLocked);
updateState(wbJackPluggedChannel, block.wbJackPlugged);
updateState(wbSchukoOnChannel, block.wbSchukoOn);
updateState(wbSchukoPluggedChannel, block.wbSchukoPlugged);
updateState(wbSchukoLockedChannel, block.wbSchukoLocked);
updateState(wbSchukoRelay16Channel, block.wbSchukoRelay16);
updateState(wbRelay16Channel, block.wbRelay16);
updateState(wbRelay32Channel, block.wbRelay32);
updateState(wb1phaseChannel, block.wb1phase);
} else {
logger.debug("Unable to get ID {} from WallboxArray", wallboxId);
}
} else {
logger.debug("Wallbox ID {} not valid", wallboxId);
}
} else {
logger.debug("Unable to get {} from Bridge", DataType.WALLBOX);
}
}
public void handleError(AsyncModbusFailure<ModbusReadRequestBlueprint> result) {
if (dataRead != ReadWriteSuccess.FAILED) {
dataRead = ReadWriteSuccess.FAILED;
updateStatus();
}
}
private void updateStatus() {
if (dataWrite == ReadWriteSuccess.NOT_RECEIVED) {
// read success / write not happened yet => go online / offline
if (dataRead == ReadWriteSuccess.SUCCESS) {
updateStatus(ThingStatus.ONLINE);
} else {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, READ_ERROR);
}
} else {
if (dataRead == dataWrite) {
// read and write same status - either go online or offline
if (dataRead == ReadWriteSuccess.SUCCESS) {
updateStatus(ThingStatus.ONLINE);
} else {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, READ_WRITE_ERROR);
}
} else {
// either read or write failed - go offline with detailed status
if (dataRead == ReadWriteSuccess.SUCCESS) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, WRITE_ERROR);
} else {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, READ_ERROR);
}
}
}
}
}
|
MikeJMajor/openhab2-addons-dlinksmarthome
|
bundles/org.openhab.binding.modbus.e3dc/src/main/java/org/openhab/binding/modbus/e3dc/internal/handler/E3DCWallboxThingHandler.java
|
Java
|
epl-1.0
| 11,912
|
/**
* Copyright (c) 2010-2020 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.cardio2e.internal.code;
/**
* Cardio2e Binding structured HVAC control transaction model
*
* @author Manuel Alberto Guerrero Díaz
* @Since 1.11.0
*/
public class Cardio2eHvacControlTransaction extends Cardio2eTransaction {
private static final long serialVersionUID = 3140812809946223591L;
public static boolean smartSendingEnabledClass = false; // Signals whether
// the whole class
// is smart sending
// enabled.
public Cardio2eHvacSystemModes singleHvacSystemMode = null;
private Cardio2eHvacFanStates hvacFanState = null;
private Cardio2eHvacSystemModes hvacSystemMode = null;
private Cardio2eHvacSystemModes simplePowerOnNextHvacSystemMode = Cardio2eHvacSystemModes.AUTO;
private double hvacHeatingSetPoint = -1.00;
private double hvacCoolingSetPoint = -1.00;
public Cardio2eHvacControlTransaction() {
super.setObjectType(Cardio2eObjectTypes.HVAC_CONTROL);
}
public Cardio2eHvacControlTransaction(short objectNumber) { // Simple HVAC
// control GET
// constructor.
setTransactionType(Cardio2eTransactionTypes.GET);
super.setObjectType(Cardio2eObjectTypes.HVAC_CONTROL);
setObjectNumber(objectNumber);
}
public Cardio2eHvacControlTransaction(short objectNumber,
double hvacHeatingSetPoint, double hvacCoolingSetPoint,
Cardio2eHvacFanStates hvacFanState,
Cardio2eHvacSystemModes hvacSystemMode) { // Simple HVAC control SET
// constructor.
setTransactionType(Cardio2eTransactionTypes.SET);
super.setObjectType(Cardio2eObjectTypes.HVAC_CONTROL);
setObjectNumber(objectNumber);
setHvacHeatingSetPoint(hvacHeatingSetPoint);
setHvacCoolingSetPoint(hvacCoolingSetPoint);
setHvacFanState(hvacFanState);
setHvacSystemMode(hvacSystemMode);
}
public void setObjectType(Cardio2eObjectTypes objectType) {
throw new UnsupportedOperationException("setObjectType");
}
public void setObjectNumber(short objectNumber) {
isDataComplete = false;
if (objectNumber <= CARDIO2E_MAX_HVAC_ZONE_NUMBER) {
super.setObjectNumber(objectNumber);
} else {
throw new IllegalArgumentException("invalid objectNumber '"
+ objectNumber + "'");
}
}
public Cardio2eHvacFanStates getHvacFanState() {
return hvacFanState;
}
public void setHvacFanState(Cardio2eHvacFanStates hvacFanState) {
isDataComplete = false;
this.hvacFanState = hvacFanState;
}
public boolean getHvacFanRunning() {
return (hvacFanState == Cardio2eHvacFanStates.RUNNING);
}
public void setHvacFanRunning(boolean hvacFanRunning) {
if (hvacFanRunning) {
setHvacFanState(Cardio2eHvacFanStates.RUNNING);
} else {
setHvacFanState(Cardio2eHvacFanStates.STOP);
}
}
public Cardio2eHvacSystemModes getHvacSystemMode() {
return hvacSystemMode;
}
public void setHvacSystemMode(Cardio2eHvacSystemModes hvacSystemMode) {
isDataComplete = false;
this.hvacSystemMode = hvacSystemMode;
if (hvacSystemMode != Cardio2eHvacSystemModes.OFF)
simplePowerOnNextHvacSystemMode = hvacSystemMode;
}
public double getHvacHeatingSetPoint() {
return hvacHeatingSetPoint;
}
public void setHvacHeatingSetPoint(double hvacHeatingSetPoint) {
isDataComplete = false;
double min = CARDIO2E_MIN_HVAC_SET_POINT;
double max = CARDIO2E_MAX_HVAC_SET_POINT;
// Prevents exceeding limits with INFORMATION transactions when ECONOMY
// mode is active
if (getTransactionType() == Cardio2eTransactionTypes.INFORMATION) {
min = min - CARDIO2E_HVAC_SET_POINT_ECONOMY_OFFSET;
max = max + CARDIO2E_HVAC_SET_POINT_ECONOMY_OFFSET;
}
if ((hvacHeatingSetPoint >= min) && (hvacHeatingSetPoint <= max)) {
this.hvacHeatingSetPoint = hvacHeatingSetPoint;
} else {
throw new IllegalArgumentException("invalid hvacHeatingSetPoint '"
+ hvacHeatingSetPoint + "'");
}
}
public double getHvacCoolingSetPoint() {
return hvacCoolingSetPoint;
}
public void setHvacCoolingSetPoint(double hvacCoolingSetPoint) {
isDataComplete = false;
double min = CARDIO2E_MIN_HVAC_SET_POINT;
double max = CARDIO2E_MAX_HVAC_SET_POINT;
// Prevents exceeding limits with INFORMATION transactions when ECONOMY
// mode is active
if (getTransactionType() == Cardio2eTransactionTypes.INFORMATION) {
min = min - CARDIO2E_HVAC_SET_POINT_ECONOMY_OFFSET;
max = max + CARDIO2E_HVAC_SET_POINT_ECONOMY_OFFSET;
}
if ((hvacCoolingSetPoint >= min) && (hvacCoolingSetPoint <= max)) {
this.hvacCoolingSetPoint = hvacCoolingSetPoint;
} else {
throw new IllegalArgumentException("invalid hvacCoolingSetPoint '"
+ hvacCoolingSetPoint + "'");
}
}
public boolean getSingleHvacSystemModeOn() {
boolean singleHvacSystemModeOn = false;
if (singleHvacSystemMode != null) {
if (hvacSystemMode != null) {
if (singleHvacSystemMode == Cardio2eHvacSystemModes.OFF) {
singleHvacSystemModeOn = getHvacFanRunning();
} else {
singleHvacSystemModeOn = (hvacSystemMode == singleHvacSystemMode);
}
}
} else {
throw new IllegalArgumentException(
"To use getSingleHvacSystemModeOn(), singleHvacSystemMode cannot be null");
}
return singleHvacSystemModeOn;
}
public void setSingleHvacSystemModeOn(boolean singleHvacSystemModeOn) {
if (singleHvacSystemMode != null) {
if (singleHvacSystemMode == Cardio2eHvacSystemModes.OFF) {
setHvacFanRunning(singleHvacSystemModeOn);
} else {
setHvacSystemMode((singleHvacSystemModeOn) ? singleHvacSystemMode
: Cardio2eHvacSystemModes.OFF);
}
} else {
throw new IllegalArgumentException(
"To use setSingleHvacSystemModeOn(), singleHvacSystemMode cannot be null");
}
}
public double getSingleHvacSetPoint() {
double singleSetPoint = 0.00;
if (singleHvacSystemMode != null) {
if (hvacSystemMode != null) {
switch (singleHvacSystemMode) {
case COOLING:
singleSetPoint = hvacCoolingSetPoint;
break;
case HEATING:
singleSetPoint = hvacHeatingSetPoint;
break;
default:
throw new IllegalArgumentException(
"Cannot determine which setpoint option (heating or cooling) is suitable for '"
+ singleHvacSystemMode
+ "' simpleControlHvacSystemMode");
}
}
} else {
throw new IllegalArgumentException(
"To use getSingleHvacSetPoint(), singleHvacSystemMode cannot be null");
}
return singleSetPoint;
}
public void setSingleHvacSetPoint(double singleSetPoint) {
if (singleHvacSystemMode != null) {
switch (singleHvacSystemMode) {
case COOLING:
setHvacCoolingSetPoint(singleSetPoint);
break;
case HEATING:
setHvacHeatingSetPoint(singleSetPoint);
break;
default:
throw new IllegalArgumentException(
"Cannot determine which setpoint option (heating or cooling) is suitable for '"
+ singleHvacSystemMode
+ "' simpleControlHvacSystemMode");
}
} else {
throw new IllegalArgumentException(
"To use getSingleHvacSetPoint(), singleHvacSystemMode cannot be null");
}
}
public boolean isPoweredOn() {
boolean poweredOn = false;
if (hvacSystemMode != null) {
if (hvacSystemMode != Cardio2eHvacSystemModes.OFF)
poweredOn = true;
} else {
throw new IllegalArgumentException(
"Cannot determine if HVAC system is powered on, because hvacSystemMode is null");
}
return poweredOn;
}
public void simplePowerOn(boolean powerOn) {
setHvacSystemMode((powerOn) ? simplePowerOnNextHvacSystemMode
: Cardio2eHvacSystemModes.OFF);
}
public int getKnxDpt20_105() {
int dpt20_105Mode = 0;
if (hvacSystemMode != null) {
switch (hvacSystemMode) {
case AUTO:
dpt20_105Mode = 0;
break;
case HEATING:
dpt20_105Mode = 1;
break;
case COOLING:
dpt20_105Mode = 3;
break;
case OFF:
dpt20_105Mode = 6;
break;
case NORMAL:
dpt20_105Mode = 254; // No KNX DPT 20.105 compliant value
break;
case ECONOMY:
dpt20_105Mode = 255; // No KNX DPT 20.105 compliant value
break;
default:
throw new IllegalArgumentException(
"Cannot parse '"
+ hvacSystemMode
+ "' Cardio 2é HVAC System Mode to KNX DPT 20.105 value");
}
} else {
throw new IllegalArgumentException(
"Cannot parse null hvacSystemMode to KNX DPT 20.105");
}
return dpt20_105Mode;
}
public void setKnxDpt20_105(int dpt20_105) {
switch (dpt20_105) {
case 0:
setHvacSystemMode(Cardio2eHvacSystemModes.AUTO);
break;
case 1:
setHvacSystemMode(Cardio2eHvacSystemModes.HEATING);
break;
case 3:
setHvacSystemMode(Cardio2eHvacSystemModes.COOLING);
break;
case 6:
setHvacSystemMode(Cardio2eHvacSystemModes.OFF);
break;
case 254: // No KNX DPT 20.105 compliant value
setHvacSystemMode(Cardio2eHvacSystemModes.NORMAL);
break;
case 255: // No KNX DPT 20.105 compliant value
setHvacSystemMode(Cardio2eHvacSystemModes.ECONOMY);
break;
default:
throw new IllegalArgumentException("Cannot parse KNX DPT 20.105 '"
+ dpt20_105 + "' value to a Cardio 2é HVAC System Mode");
}
}
public boolean isDataVerified() { // Returns true if object data matches
// with Cardio2e data specs and data is
// congruent.
boolean verified = false;
if (super.isDataVerified()) {
switch (getTransactionType()) {
case ACK:
case GET:
verified = (getObjectNumber() != -1);
break;
case NACK:
verified = (getErrorCode() != -1);
break;
case INFORMATION:
case SET:
verified = ((getObjectNumber() != -1)
&& (hvacHeatingSetPoint != -1.00)
&& (hvacCoolingSetPoint != -1.00)
&& (hvacFanState != null) && (hvacSystemMode != null));
break;
}
}
return verified;
}
public String toString() {
String returnString = null;
if (isDataVerified()) {
switch (getTransactionType()) {
case ACK:
case GET:
returnString = String.format("%s%s %s %d%s",
CARDIO2E_START_TRANSACTION_INITIATOR,
getTransactionType().symbol, getObjectType().symbol,
getObjectNumber(), CARDIO2E_END_TRANSACTION_CHARACTER);
break;
case NACK:
if (getObjectNumber() == -1) {
returnString = String.format("%s%s %s %d%s",
CARDIO2E_START_TRANSACTION_INITIATOR,
getTransactionType().symbol,
getObjectType().symbol, getErrorCode(),
CARDIO2E_END_TRANSACTION_CHARACTER);
} else {
returnString = String.format("%s%s %s %d %d%s",
CARDIO2E_START_TRANSACTION_INITIATOR,
getTransactionType().symbol,
getObjectType().symbol, getObjectNumber(),
getErrorCode(), CARDIO2E_END_TRANSACTION_CHARACTER);
}
break;
case INFORMATION:
returnString = String.format("%s%s %s %d %.2f %.2f %s %s%s",
CARDIO2E_START_TRANSACTION_INITIATOR,
getTransactionType().symbol, getObjectType().symbol,
getObjectNumber(), hvacHeatingSetPoint,
hvacCoolingSetPoint, hvacFanState.symbol,
hvacSystemMode.symbol,
CARDIO2E_END_TRANSACTION_CHARACTER);
case SET:
returnString = String.format("%s%s %s %d %.0f %.0f %s %s%s",
CARDIO2E_START_TRANSACTION_INITIATOR,
getTransactionType().symbol, getObjectType().symbol,
getObjectNumber(), hvacHeatingSetPoint,
hvacCoolingSetPoint, hvacFanState.symbol,
hvacSystemMode.symbol,
CARDIO2E_END_TRANSACTION_CHARACTER);
break;
}
}
return returnString;
}
public static void setSmartSendingEnabledClass(boolean enabled) {
Cardio2eHvacControlTransaction.smartSendingEnabledClass = enabled;
}
public static boolean getSmartSendingEnabledClass() {
// This function replaces superclass Cardio2eTransaction
// getSmartSendingEnabledClass() function.
return Cardio2eHvacControlTransaction.smartSendingEnabledClass;
}
public boolean isSmartSendingEnabled() { // Returns true if this transaction
// or its class is smart sending
// enabled.
// This function replaces superclass Cardio2eTransaction
// isSmartSendingEnabled() function.
return (Cardio2eHvacControlTransaction.getSmartSendingEnabledClass() || smartSendingEnabledTransaction);
}
}
|
openhab/openhab
|
bundles/binding/org.openhab.binding.cardio2e/src/main/java/org/openhab/binding/cardio2e/internal/code/Cardio2eHvacControlTransaction.java
|
Java
|
epl-1.0
| 12,444
|
/**
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Eclipse Public License version 1.0, available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.jboss.forge.addon.text.highlight.encoder;
import java.awt.Color;
import java.io.OutputStream;
import java.util.Map;
import org.jboss.forge.addon.text.highlight.Encoder;
import org.jboss.forge.addon.text.highlight.Theme;
import org.jboss.forge.addon.text.highlight.TokenType;
public class TerminalEncoder extends Encoder.AbstractEncoder implements Encoder
{
public TerminalEncoder(OutputStream out, Theme theme, Map<String, Object> options)
{
super(out, theme, options);
write(TerminalString.RESET); // reset terminal colors
}
@Override
public void textToken(String text, TokenType type)
{
Color color = color(type);
if (color != null)
{
write(TerminalString.of(color, text));
}
else
{
write(text);
}
}
@Override
public void beginGroup(TokenType type)
{
}
@Override
public void endGroup(TokenType type)
{
}
@Override
public void beginLine(TokenType type)
{
}
@Override
public void endLine(TokenType type)
{
}
public static class TerminalString
{
public static final String START_COLOR = "\u001B[38;5;";
public static final String END = "m";
public static final String RESET = "\u001B[0" + END;
public static String of(Color color, String text)
{
StringBuilder sb = new StringBuilder();
sb.append(START_COLOR)
.append(from(color))
.append(END);
sb.append(text);
sb.append(RESET);
return sb.toString();
}
public static String from(Color color)
{
return String.valueOf(
rgbToAnsi(
color.getRed(),
color.getGreen(),
color.getBlue()));
}
private static int rgbToAnsi(int red, int green, int blue)
{
return 16 + (getAnsiScale(red) * 36) + (getAnsiScale(green) * 6) + getAnsiScale(blue);
}
public static int getAnsiScale(int color)
{
return Math.round(color / (255/5));
}
}
}
|
jerr/jbossforge-core
|
text/src/main/java/org/jboss/forge/addon/text/highlight/encoder/TerminalEncoder.java
|
Java
|
epl-1.0
| 2,323
|
/*
* Copyright (c) 2015-2018 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
'use strict';
import {CheAPI} from '../../../components/api/che-api.factory';
import {CheNotification} from '../../../components/notification/che-notification.factory';
import {CheWorkspace} from '../../../components/api/workspace/che-workspace.factory';
import {CheNamespaceRegistry} from '../../../components/api/namespace/che-namespace-registry.factory';
import {ConfirmDialogService} from '../../../components/service/confirm-dialog/confirm-dialog.service';
import {CheBranding} from '../../../components/branding/che-branding.factory';
/**
* @ngdoc controller
* @name workspaces.list.controller:ListWorkspacesCtrl
* @description This class is handling the controller for listing the workspaces
* @author Ann Shumilova
*/
export class ListWorkspacesCtrl {
static $inject = ['$log', '$mdDialog', '$q', 'lodash', 'cheAPI', 'cheNotification', 'cheBranding', 'cheWorkspace', 'cheNamespaceRegistry',
'confirmDialogService', '$scope', 'cheListHelperFactory'];
$q: ng.IQService;
$log: ng.ILogService;
lodash: any;
$mdDialog: ng.material.IDialogService;
cheAPI: CheAPI;
cheNotification: CheNotification;
cheWorkspace: CheWorkspace;
cheListHelper: che.widget.ICheListHelper;
state: string;
isInfoLoading: boolean;
workspaceFilter: any;
userWorkspaces: che.IWorkspace[];
workspaceCreationLink: string;
workspacesById: Map<string, che.IWorkspace>;
workspaceUsedResources: Map<string, string>;
isExactMatch: boolean = false;
namespaceFilter: {namespace: string};
namespaceLabels: string[];
onFilterChanged: Function;
onSearchChanged: Function;
cheNamespaceRegistry: CheNamespaceRegistry;
private confirmDialogService: ConfirmDialogService;
private ALL_NAMESPACES: string = 'All Teams';
/**
* Default constructor that is using resource
*/
constructor($log: ng.ILogService, $mdDialog: ng.material.IDialogService, $q: ng.IQService, lodash: any,
cheAPI: CheAPI, cheNotification: CheNotification, cheBranding: CheBranding,
cheWorkspace: CheWorkspace, cheNamespaceRegistry: CheNamespaceRegistry,
confirmDialogService: ConfirmDialogService, $scope: ng.IScope, cheListHelperFactory: che.widget.ICheListHelperFactory) {
this.cheAPI = cheAPI;
this.$q = $q;
this.$log = $log;
this.lodash = lodash;
this.$mdDialog = $mdDialog;
this.cheNotification = cheNotification;
this.cheWorkspace = cheWorkspace;
this.cheNamespaceRegistry = cheNamespaceRegistry;
this.confirmDialogService = confirmDialogService;
this.workspaceCreationLink = cheBranding.getWorkspace().creationLink;
const helperId = 'list-workspaces';
this.cheListHelper = cheListHelperFactory.getHelper(helperId);
$scope.$on('$destroy', () => {
cheListHelperFactory.removeHelper(helperId);
});
this.state = 'loading';
this.isInfoLoading = true;
this.isExactMatch = false;
this.workspaceFilter = {config: {name: ''}};
this.namespaceFilter = {namespace: ''};
// map of all workspaces with additional info by id:
this.workspacesById = new Map();
// map of workspaces' used resources (consumed GBH):
this.workspaceUsedResources = new Map();
this.getUserWorkspaces();
this.cheNamespaceRegistry.fetchNamespaces().then(() => {
this.namespaceLabels = this.getNamespaceLabelsList();
});
// callback when search value is changed
this.onSearchChanged = (str: string) => {
this.workspaceFilter.config.name = str;
this.cheListHelper.applyFilter('name', this.workspaceFilter);
};
// callback when namespace is changed
this.onFilterChanged = (label : string) => {
if (label === this.ALL_NAMESPACES) {
this.namespaceFilter.namespace = '';
} else {
let namespace = this.cheNamespaceRegistry.getNamespaces().find((namespace: che.INamespace) => {
return namespace.label === label;
});
this.namespaceFilter.namespace = namespace.id;
}
this.isExactMatch = (label === this.ALL_NAMESPACES) ? false : true;
this.cheListHelper.applyFilter('namespace', this.namespaceFilter, this.isExactMatch);
};
}
/**
* Fetch current user's workspaces (where he is a member):
*/
getUserWorkspaces(): void {
// fetch workspaces when initializing
const promise = this.cheAPI.getWorkspace().fetchWorkspaces();
promise.then(() => {
return this.updateSharedWorkspaces();
}, (error: any) => {
if (error && error.status === 304) {
// ok
return this.updateSharedWorkspaces();
}
this.state = 'error';
this.isInfoLoading = false;
return this.$q.reject(error);
}).then(() => {
this.cheListHelper.setList(this.userWorkspaces, 'id');
});
}
/**
* Update the info of all user workspaces:
*
* @return {IPromise<any>}
*/
updateSharedWorkspaces(): ng.IPromise<any> {
this.userWorkspaces = [];
let workspaces = this.cheAPI.getWorkspace().getWorkspaces();
if (workspaces.length === 0) {
this.isInfoLoading = false;
}
const promises: Array<ng.IPromise<any>> = [];
workspaces.forEach((workspace: che.IWorkspace) => {
// first check the list of already received workspace info:
if (!this.workspacesById.get(workspace.id)) {
const promise = this.cheWorkspace.fetchWorkspaceDetails(workspace.id)
.catch((error: any) => {
if (error && error.status === 304) {
return this.$q.when();
}
let message = error.data && error.data.message ? ' Reason: ' + error.data.message : '';
let workspaceName = this.cheWorkspace.getWorkspaceDataManager().getName(workspace);
this.cheNotification.showError('Failed to retrieve workspace ' + workspaceName + ' data.' + message) ;
return this.$q.reject(error);
})
.then(() => {
let userWorkspace = this.cheAPI.getWorkspace().getWorkspaceById(workspace.id);
this.getWorkspaceInfo(userWorkspace);
this.userWorkspaces.push(userWorkspace);
return this.$q.when();
});
promises.push(promise);
} else {
let userWorkspace = this.workspacesById.get(workspace.id);
this.userWorkspaces.push(userWorkspace);
this.isInfoLoading = false;
}
});
this.state = 'loaded';
return this.$q.all(promises);
}
/**
* Represents given account resources as a map with workspace id as a key.
*
* @param {any[]} resources
*/
processUsedResources(resources: any[]): void {
resources.forEach((resource: any) => {
this.workspaceUsedResources.set(resource.workspaceId, resource.memory.toFixed(2));
});
}
/**
* Gets all necessary workspace info to be displayed.
*
* @param {che.IWorkspace} workspace
*/
getWorkspaceInfo(workspace: che.IWorkspace): void {
let promises = [];
this.workspacesById.set(workspace.id, workspace);
workspace.isLocked = false;
workspace.usedResources = this.workspaceUsedResources.get(workspace.id);
// no access to runner resources if workspace is locked:
if (!workspace.isLocked) {
let promiseWorkspace = this.cheAPI.getWorkspace().fetchWorkspaceDetails(workspace.id);
promises.push(promiseWorkspace);
}
this.$q.all(promises).finally(() => {
this.isInfoLoading = false;
});
}
/**
* Delete all selected workspaces
*/
deleteSelectedWorkspaces(): void {
const selectedWorkspaces = this.cheListHelper.getSelectedItems(),
selectedWorkspacesIds = selectedWorkspaces.map((workspace: che.IWorkspace) => {
return workspace.id;
});
let queueLength = selectedWorkspacesIds.length;
if (!queueLength) {
this.cheNotification.showError('No such workspace.');
return;
}
let confirmationPromise = this.showDeleteWorkspacesConfirmation(queueLength);
confirmationPromise.then(() => {
let numberToDelete = queueLength;
let isError = false;
let deleteWorkspacePromises = [];
let workspaceName;
selectedWorkspacesIds.forEach((workspaceId: string) => {
this.cheListHelper.itemsSelectionStatus[workspaceId] = false;
let workspace = this.cheWorkspace.getWorkspaceById(workspaceId);
if (!workspace) {
return;
}
workspaceName = this.cheWorkspace.getWorkspaceDataManager().getName(workspace);
let stoppedStatusPromise = this.cheWorkspace.fetchStatusChange(workspaceId, 'STOPPED');
// stop workspace if it's status is RUNNING
if (workspace.status === 'RUNNING') {
this.cheWorkspace.stopWorkspace(workspaceId);
}
// delete stopped workspace
let promise = stoppedStatusPromise.then(() => {
return this.cheWorkspace.deleteWorkspaceConfig(workspaceId);
}).then(() => {
this.workspacesById.delete(workspaceId);
queueLength--;
},
(error: any) => {
isError = true;
this.$log.error('Cannot delete workspace: ', error);
});
deleteWorkspacePromises.push(promise);
});
this.$q.all(deleteWorkspacePromises).finally(() => {
this.getUserWorkspaces();
if (isError) {
this.cheNotification.showError('Delete failed.');
} else {
if (numberToDelete === 1) {
this.cheNotification.showInfo(workspaceName + ' has been removed.');
} else {
this.cheNotification.showInfo('Selected workspaces have been removed.');
}
}
});
});
}
/**
* Show confirmation popup before workspaces to delete
* @param numberToDelete{number}
* @returns {ng.IPromise<any>}
*/
showDeleteWorkspacesConfirmation(numberToDelete: number): ng.IPromise<any> {
let content = 'Would you like to delete ';
if (numberToDelete > 1) {
content += 'these ' + numberToDelete + ' workspaces?';
} else {
content += 'this selected workspace?';
}
return this.confirmDialogService.showConfirmDialog('Remove workspaces', content, 'Delete');
}
/**
* Returns the list of labels of available namespaces.
*
* @returns {Array} array of namespaces
*/
getNamespaceLabelsList(): string[] {
let namespaces = this.lodash.pluck(this.cheNamespaceRegistry.getNamespaces(), 'label');
if (namespaces.length > 0) {
return [this.ALL_NAMESPACES].concat(namespaces);
}
return namespaces;
}
}
|
akervern/che
|
dashboard/src/app/workspaces/list-workspaces/list-workspaces.controller.ts
|
TypeScript
|
epl-1.0
| 10,895
|
/******************************************************************************
* Copyright (c) 2000-2016 Ericsson Telecom AB
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Balasko, Jeno
* Delic, Adam
* Forstner, Matyas
* Koppany, Csaba
* Lovassy, Arpad
* Raduly, Csaba
* Szabo, Janos Zoltan – initial implementation
*
******************************************************************************/
// This Test Port skeleton source file was generated by the
// TTCN-3 Compiler of the TTCN-3 Test Executor version 1.3.pl0
// for Matyas Forstner (tmpmfr@saussure) on Thu Apr 10 16:06:07 2003
// You may modify this file. Complete the body of empty functions and
// add your member functions here.
#include "MyPort1.hh"
#ifndef OLD_NAMES
using namespace X682;
namespace X {
#endif
MyPort1::MyPort1(const char *par_port_name)
: MyPort1_BASE(par_port_name)
{
}
MyPort1::~MyPort1()
{
}
void MyPort1::set_parameter(const char *parameter_name,
const char *parameter_value)
{
}
void MyPort1::Event_Handler(const fd_set *read_fds,
const fd_set *write_fds, const fd_set *error_fds,
double time_since_last_call)
{
}
void MyPort1::user_map(const char *system_port)
{
}
void MyPort1::user_unmap(const char *system_port)
{
}
void MyPort1::user_start()
{
}
void MyPort1::user_stop()
{
}
void MyPort1::outgoing_send(const ErrorReturn& send_par)
{
TTCN_Buffer buf;
send_par.encode(ErrorReturn_descr_, buf,
TTCN_EncDec::CT_BER, BER_ENCODE_DER);
OCTETSTRING os;
buf.get_string(os);
incoming_message(os);
}
#ifndef OLD_NAMES
}
#endif
|
BenceJanosSzabo/titan.core
|
regression_test/BER_x682/MyPort1.cc
|
C++
|
epl-1.0
| 1,816
|
// Copyright © Syterra Software Inc. All rights reserved.
// The use and distribution terms for this software are covered by the Common Public License 1.0 (http://opensource.org/licenses/cpl.php)
// which can be found in the file license.txt at the root of this distribution. By using this software in any fashion, you are agreeing
// to be bound by the terms of this license. You must not remove this notice, or any other, from this software.
using System;
using System.Collections.Generic;
using fitnesse.mtee.engine;
using fitnesse.mtee.model;
using fitnesse.slim;
using fitnesse.slim.operators;
using NUnit.Framework;
namespace fitnesse.unitTest.slim {
[TestFixture] public class ParseOperatorsTest {
private Processor<string> processor;
[SetUp] public void SetUp() {
processor = new Processor<string>(new ApplicationUnderTest());
processor.AddMemory<Symbol>();
}
[Test] public void ParseSymbolReplacesWithValue() {
processor.Store(new Symbol("$symbol", "testvalue"));
Assert.AreEqual("testvalue", Parse(new ParseSymbol(), typeof(object), new TreeLeaf<string>("$symbol")));
}
[Test] public void ParseSymbolReplacesEmbeddedValues() {
processor.Store(new Symbol("$symbol1", "test"));
processor.Store(new Symbol("$symbol2", "value"));
Assert.AreEqual("-testvalue-", Parse(new ParseSymbol(), typeof(object), new TreeLeaf<string>("-$symbol1$symbol2-")));
}
[Test] public void TreeIsParsedForList() {
var list =
Parse(new ParseList(), typeof (List<int>), new TreeList<string>().AddBranchValue("5").AddBranchValue("4")) as List<int>;
Assert.IsNotNull(list);
Assert.AreEqual(2, list.Count);
Assert.AreEqual(5, list[0]);
Assert.AreEqual(4, list[1]);
}
private object Parse(ParseOperator<string> parseOperator, Type type, Tree<string> parameters) {
TypedValue result = TypedValue.Void;
Assert.IsTrue(parseOperator.TryParse(processor, type, TypedValue.Void, parameters, ref result));
return result.Value;
}
}
}
|
unclebob/nslim
|
source/unitTest/slim/ParseOperatorsTest.cs
|
C#
|
epl-1.0
| 2,207
|
if(!ORYX.Plugins){ORYX.Plugins=new Object()
}ORYX.Plugins.BPMN2XPDL20=ORYX.Plugins.AbstractPlugin.extend({construct:function(){arguments.callee.$.construct.apply(this,arguments);
this.facade.offer({name:ORYX.I18N.BPMN2XPDL.xpdlExport,functionality:this.transform.bind(this),group:ORYX.I18N.BPMN2XPDL.group,dropDownGroupIcon:ORYX.BASE_FILE_PATH+"images/export2.png",icon:ORYX.BASE_FILE_PATH+"images/page_white_gear.png",description:ORYX.I18N.BPMN2XPDL.xpdlExport,index:1,minShape:0,maxShape:0});
this.facade.offer({name:ORYX.I18N.BPMN2XPDL.xpdlImport,functionality:this.importXPDL.bind(this),group:ORYX.I18N.BPMN2XPDL.group,dropDownGroupIcon:ORYX.BASE_FILE_PATH+"images/import.png",icon:ORYX.BASE_FILE_PATH+"images/page_white_gear.png",description:ORYX.I18N.BPMN2XPDL.xpdlImport,index:1,minShape:0,maxShape:0})
},transform:function(){var a=ORYX.CONFIG.BPMN2XPDLPATH;
var b=this.facade.getSerializedJSON();
Ext.Ajax.request({url:a,method:"POST",success:function(c){this.openDownloadWindow(window.document.title+".xml",c.responseText)
}.bind(this),failure:function(){Ext.Msg.alert("Conversion failed")
},params:{data:b,action:"Export"}})
},importXPDL:function(a){var b=ORYX.CONFIG.BPMN2XPDLPATH;
var d=new Ext.form.FormPanel({baseCls:"x-plain",labelWidth:50,defaultType:"textfield",items:[{text:ORYX.I18N.BPMN2XPDL.selectFile,style:"font-size:12px;margin-bottom:10px;display:block;",anchor:"100%",xtype:"label"},{fieldLabel:ORYX.I18N.BPMN2XPDL.file,name:"subject",inputType:"file",style:"margin-bottom:10px;display:block;",itemCls:"ext_specific_window_overflow"},{xtype:"textarea",hideLabel:true,name:"msg",anchor:"100% -63"}]});
var c=new Ext.Window({autoCreate:true,layout:"fit",plain:true,bodyStyle:"padding:5px;",title:ORYX.I18N.BPMN2XPDL.impXPDL,height:350,width:500,modal:true,fixedcenter:true,shadow:true,proxyDrag:true,resizable:true,items:[d],buttons:[{text:ORYX.I18N.BPMN2XPDL.impBtn,handler:function(){var e=new Ext.LoadMask(Ext.getBody(),{msg:ORYX.I18N.BPMN2XPDL.impProgress});
e.show();
window.setTimeout(function(){var f=d.items.items[2].getValue();
Ext.Ajax.request({url:b,method:"POST",success:function(g){this.facade.importJSON(g.responseText);
e.hide();
c.hide()
}.bind(this),failure:function(){e.hide();
Ext.Msg.alert("Import failed")
},params:{data:f,action:"Import"}})
}.bind(this),100)
}.bind(this)},{text:ORYX.I18N.BPMN2XPDL.close,handler:function(){c.hide()
}.bind(this)}]});
c.on("hide",function(){c.destroy(true);
delete c
});
c.show();
d.items.items[1].getEl().dom.addEventListener("change",function(e){var f=e.target.files[0].getAsText("UTF-8");
d.items.items[2].setValue(f)
},true)
}});
|
asantoya/jbpm
|
src/main/webapp/org.jbpm.designer.jBPMDesigner/js/Plugins/bpmn2xpdl20-min.js
|
JavaScript
|
epl-1.0
| 2,612
|
html,
body {
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
height: 100%;
padding-top: 35px;
}
.table>tbody>tr>td {
padding: 3px;
}
.table-bordered>tbody>tr>td {
border: 2px solid #060606;
}
td.cue-cell {
width: 90px;
max-width: 100px;
height: 50px;
max-height: 60px;
text-align: center;
overflow: hidden;
-ms-text-overflow: ellipsis;
-o-text-overflow: ellipsis;
text-overflow: ellipsis;
word-wrap: break-word;
-webkit-user-select: none; /* webkit (safari, chrome) browsers */
-moz-user-select: none; /* mozilla browsers */
-khtml-user-select: none; /* webkit (konqueror) browsers */
-ms-user-select: none; /* IE10+ */
}
.btn-mini {
padding: 2px 6px;
font-size: 11px;
line-height: 13px;
}
table.metronome {
text-align: center;
}
.table tbody>tr>th.division {
text-align: center;
}
.table>tbody>tr>td.metronome {
padding: 0px;
-webkit-user-select: none; /* webkit (safari, chrome) browsers */
-moz-user-select: none; /* mozilla browsers */
-khtml-user-select: none; /* webkit (konqueror) browsers */
-ms-user-select: none; /* IE10+ */
}
.table>tbody>tr>th.metronome {
padding: 0px;
-webkit-user-select: none; /* webkit (safari, chrome) browsers */
-moz-user-select: none; /* mozilla browsers */
-khtml-user-select: none; /* webkit (konqueror) browsers */
-ms-user-select: none; /* IE10+ */
}
.table tbody>tr>td.metronome-sync {
text-align: left;
vertical-align: middle;
}
.table tbody>tr>td.metronome-sync .metronome-active {
background-color: lightblue;
}
.table tbody>tr>td.metronome-sync .metronome-blink {
color: yellow;
}
.table tbody>tr>td.metronome-adjust .metronome-active {
color: lightblue;
}
.table tbody>tr>td.metronome-reset {
color: red;
}
.table tbody>tr>td.metronome-reset .metronome-active {
color: #f77;
}
#slider-in-bpm .slider-track-high {
background: darkslategray;
}
#slider-in-bpm .slider-selection {
background: slategray;
}
#loadBar {
vertical-align: text-top;
}
|
dandaka/afterglow
|
resources/public/css/screen.css
|
CSS
|
epl-1.0
| 2,090
|
package name.abuchen.portfolio.ui.util;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import org.eclipse.jface.databinding.swt.WidgetValueProperty;
import org.eclipse.nebula.widgets.cdatetime.CDateTime;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.DateTime;
public class SimpleDateTimeSelectionProperty extends WidgetValueProperty
{
public SimpleDateTimeSelectionProperty()
{
super(SWT.Selection);
}
public Object getValueType()
{
return LocalDate.class;
}
@Override
protected Object doGetValue(Object source)
{
if (source instanceof DateTime)
{
DateTime dateTime = (DateTime) source;
// DateTime widget has zero-based months
return LocalDate.of(dateTime.getYear(), dateTime.getMonth() + 1, dateTime.getDay());
}
else if (source instanceof CDateTime)
{
Date date = ((CDateTime) source).getSelection();
return date == null ? null
: LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()).toLocalDate();
}
else
{
throw new UnsupportedOperationException();
}
}
@Override
protected void doSetValue(Object source, Object value)
{
if (source instanceof DateTime)
{
LocalDate date = (LocalDate) value;
DateTime dateTime = (DateTime) source;
// DateTime widget has zero-based months
dateTime.setDate(date.getYear(), date.getMonthValue() - 1, date.getDayOfMonth());
}
else if (source instanceof CDateTime)
{
LocalDate date = (LocalDate) value;
CDateTime dateTime = (CDateTime) source;
dateTime.setSelection(Date.from(date.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()));
}
else
{
throw new UnsupportedOperationException();
}
}
}
|
simpsus/portfolio
|
name.abuchen.portfolio.ui/src/name/abuchen/portfolio/ui/util/SimpleDateTimeSelectionProperty.java
|
Java
|
epl-1.0
| 2,037
|
/*******************************************************************************
* Copyright (c) 2017,2020 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package test.resource.internal;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.ConfigurationPolicy;
import org.osgi.service.component.annotations.Deactivate;
import com.ibm.wsspi.resource.ResourceFactory;
import com.ibm.wsspi.resource.ResourceInfo;
/**
* A resource factory that runs a test that needs to access the service registry.
*/
@Component(configurationPolicy = ConfigurationPolicy.IGNORE,
service = { ResourceFactory.class },
property = { "jndiName=testresource/testServiceRankings", "creates.objectClass=java.lang.Object" })
public class TestResource implements ResourceFactory {
private ComponentContext context;
@Activate
protected void activate(ComponentContext context) {
this.context = context;
}
@Deactivate
protected void deactivate() {
}
// Used by test.concurrent.app.EEConcurrencyUtilsTestServlet.testServiceRankings
// in order to perform a test that queries the service registry.
// An exception is returned as the result if the test fails. The message "SUCCESS" is returned if successful.
@Override
public Object createResource(ResourceInfo info) throws Exception {
try {
return AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
BundleContext bundleContext = context.getBundleContext();
ServiceReference<ExecutorService> execSvcRef = bundleContext.getServiceReference(ExecutorService.class);
String componentName = (String) execSvcRef.getProperty("component.name");
if (!"com.ibm.ws.threading".equals(componentName))
throw new Exception("Unexpected ExecutorService with highest service.ranking: " + execSvcRef);
ServiceReference<ScheduledExecutorService> schedExecSvcRef = bundleContext.getServiceReference(ScheduledExecutorService.class);
componentName = (String) schedExecSvcRef.getProperty("component.name");
if (!"com.ibm.ws.threading.internal.ScheduledExecutorImpl".equals(componentName))
throw new Exception("Unexpected ScheduledExecutorService with highest service.ranking: " + schedExecSvcRef);
ServiceReference<?> mgdExecSvcRef = bundleContext.getServiceReference("jakarta.enterprise.concurrent.ManagedExecutorService");
if (mgdExecSvcRef == null)
mgdExecSvcRef = bundleContext.getServiceReference("javax.enterprise.concurrent.ManagedExecutorService");
String displayId = (String) mgdExecSvcRef.getProperty("config.displayId");
if (!"managedExecutorService[DefaultManagedExecutorService]".equals(displayId))
throw new Exception("Unexpected ManagedExecutorService with highest service.ranking: " + displayId);
ServiceReference<?> mgdSchedExecSvcRef = bundleContext.getServiceReference("javax.enterprise.concurrent.ManagedScheduledExecutorService");
if (mgdSchedExecSvcRef == null)
mgdSchedExecSvcRef = bundleContext.getServiceReference("jakarta.enterprise.concurrent.ManagedScheduledExecutorService");
displayId = (String) mgdSchedExecSvcRef.getProperty("config.displayId");
if (!"managedScheduledExecutorService[DefaultManagedScheduledExecutorService]".equals(displayId))
throw new Exception("Unexpected ManagedScheduledExecutorService with highest service.ranking: " + displayId);
return "SUCCESS";
}
});
} catch (PrivilegedActionException x) {
return x.getCause();
}
}
}
|
OpenLiberty/open-liberty
|
dev/com.ibm.ws.concurrent_fat/test-bundles/test.resource/src/test/resource/internal/TestResource.java
|
Java
|
epl-1.0
| 4,868
|
/*******************************************************************************
* Copyright (c) 2018 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package jaxrs21.fat.interceptor;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import org.junit.Test;
import componenttest.app.FATServlet;
@SuppressWarnings("serial")
@WebServlet(urlPatterns = "/InterceptorTestServlet")
public class InterceptorTestServlet extends FATServlet {
private static final int HTTP_PORT = Integer.getInteger("bvt.prop.HTTP_default", 8010);
private static final String SCOPE_REQUEST = "requestScoped";
private static final String SCOPE_APP = "applicationScoped";
private Client client;
@Override
public void init() throws ServletException {
client = ClientBuilder.newBuilder().build();
}
@Override
public void destroy() {
client.close();
}
@Test
public void testCDIInterceptorsInvokedOnResourceMethodWhenInterceptorAppliedToClass_RequestScoped(
HttpServletRequest req, HttpServletResponse resp) throws Exception {
testCDIInterceptorsInvokedOnResourceMethodWhenInterceptorAppliedToClass(req, resp, SCOPE_REQUEST);
}
@Test
public void testCDIInterceptorsInvokedOnResourceMethodWhenInterceptorAppliedToClass_ApplicationScoped(
HttpServletRequest req, HttpServletResponse resp) throws Exception {
testCDIInterceptorsInvokedOnResourceMethodWhenInterceptorAppliedToClass(req, resp, SCOPE_APP);
}
public void testCDIInterceptorsInvokedOnResourceMethodWhenInterceptorAppliedToClass(
HttpServletRequest req, HttpServletResponse resp, String scope) throws Exception {
String response = invoke(req, "interceptorapp/" + scope + "/justOne");
String[] interceptorsInvoked = response.split(" ");
assertTrue("Unexpected number of businessInterceptors invoked (expected exactly one), got " + interceptorsInvoked.length,
interceptorsInvoked.length == 1);
assertEquals("Unexpected interceptor invoked", "InterceptorOne", response);
}
@Test
public void testCDIInterceptorsInvokedOnResourceMethodWhenInterceptorAppliedToClassAndMethod_RequestScoped(
HttpServletRequest req, HttpServletResponse resp) throws Exception {
testCDIInterceptorsInvokedOnResourceMethodWhenInterceptorAppliedToClassAndMethod(req, resp, SCOPE_REQUEST);
}
@Test
public void testCDIInterceptorsInvokedOnResourceMethodWhenInterceptorAppliedToClassAndMethod_ApplicationScoped(
HttpServletRequest req, HttpServletResponse resp) throws Exception {
testCDIInterceptorsInvokedOnResourceMethodWhenInterceptorAppliedToClassAndMethod(req, resp, SCOPE_APP);
}
public void testCDIInterceptorsInvokedOnResourceMethodWhenInterceptorAppliedToClassAndMethod(
HttpServletRequest req, HttpServletResponse resp, String scope) throws Exception {
String response = invoke(req, "interceptorapp/" + scope + "/oneAndThree");
String[] interceptorsInvoked = response.split(" ");
assertTrue("Unexpected number of businessInterceptors invoked (expected exactly two), got " + interceptorsInvoked.length,
interceptorsInvoked.length == 2);
assertTrue("Class level interceptor not invoked", response.contains("InterceptorOne"));
assertTrue("Method level interceptor not invoked", response.contains("InterceptorThree"));
}
@Test
public void testAllCDIInterceptorsInvokedOnResourceMethod_RequestScoped(
HttpServletRequest req, HttpServletResponse resp) throws Exception {
testAllCDIInterceptorsInvokedOnResourceMethod_ApplicationScoped(req, resp, SCOPE_REQUEST);
}
@Test
public void testAllCDIInterceptorsInvokedOnResourceMethod_ApplicationScoped(
HttpServletRequest req, HttpServletResponse resp) throws Exception {
testAllCDIInterceptorsInvokedOnResourceMethod_ApplicationScoped(req, resp, SCOPE_REQUEST);
}
public void testAllCDIInterceptorsInvokedOnResourceMethod_ApplicationScoped(
HttpServletRequest req, HttpServletResponse resp, String scope) throws Exception {
String response = invoke(req, "interceptorapp/" + scope + "/all");
String[] interceptorsInvoked = response.split(" ");
assertTrue("Unexpected number of businessInterceptors invoked (expected exactly three) got " + interceptorsInvoked.length,
interceptorsInvoked.length == 3);
assertTrue("Class level interceptor not invoked", response.contains("InterceptorOne"));
assertTrue("Method level interceptor not invoked", response.contains("InterceptorTwo"));
assertTrue("Method level interceptor not invoked", response.contains("InterceptorThree"));
}
@Test
public void testCDIInterceptorsInvokedOnResourcePostConstructMethodWhenInterceptorAppliedToClassAndMethod_RequestScoped(
HttpServletRequest req, HttpServletResponse resp) throws Exception {
testCDIInterceptorsInvokedOnResourcePostConstructMethodWhenInterceptorAppliedToClassAndMethod(req, resp, SCOPE_REQUEST);
}
@Test
public void testCDIInterceptorsInvokedOnResourcePostConstructMethodWhenInterceptorAppliedToClassAndMethod_ApplicationScoped(
HttpServletRequest req, HttpServletResponse resp) throws Exception {
testCDIInterceptorsInvokedOnResourcePostConstructMethodWhenInterceptorAppliedToClassAndMethod(req, resp, SCOPE_APP);
}
public void testCDIInterceptorsInvokedOnResourcePostConstructMethodWhenInterceptorAppliedToClassAndMethod(
HttpServletRequest req, HttpServletResponse resp, String scope) throws Exception {
String response = invoke(req, "interceptorapp/" + scope + "/postConstruct");
String[] interceptorsInvoked = response.split(" ");
assertTrue("Unexpected number of businessInterceptors invoked (expected exactly one), got " + interceptorsInvoked.length,
interceptorsInvoked.length == 1);
assertTrue("Unexpected interceptor invoked: " + response, response.equals("LifecycleInterceptorTwo"));
}
private String invoke(HttpServletRequest request, String path) {
String base = "http://" + request.getServerName() + ':' + HTTP_PORT + '/';
WebTarget target = client.target(base + path);
String response = target.request().get(String.class).trim();
System.out.println("Response = " + response);
return response;
}
}
|
OpenLiberty/open-liberty
|
dev/com.ibm.ws.jaxrs.2.1.cdi.2.0_fat/test-applications/interceptorapp/src/jaxrs21/fat/interceptor/InterceptorTestServlet.java
|
Java
|
epl-1.0
| 7,345
|
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Verifiable Secret Sharing</title>
</head>
<body>
<h1>Verifiable Secret Sharing</h1>
<p>
The <b>Verifiable Secret Sharing</b> algorithm has been developed by Paul Feldman in 1987
and is based on the Shamir's Secret Sharing algorithm from Adi Shamir from 1979. With this algorithm it is possible
to divide a secret into parts and distribute it to multiple persons. For retrieving the secret, just a few of this persons is necessary.
</p>
<p>
The following explains how the <b>Verifiable Secret Sharing</b> plug-in works.
</p>
<p>
The plug-in can be started in the menu bar at <b>Visualization</b> or at the view <b>Algorithms</b> at the tab <b>Visualization</b>.
</p>
<p><img src="vss_plugin_1.jpg" width="60%" height="60%"></p>
<p>The plug-in is splitted into 4 parts: <b>header</b>, <b>input mask</b>, <b>description</b> and the tab <b>reconstruction chart</b>.
<p>The <b>Header</b> shows a short description of the plug-in.</p>
<p>The <b>input mask</b> contains the boxes to set the parameters and all other computations of the Verifiable Secret Sharing-algorithm. The results are also shown there.</p>
<p>At the bottom of the screen you can find the area <b>description</b> where additional information for the current step is shown.</p>
<p>Additionally there is a tab <b>Reconstruction Chart</b> where the reconstruction is visualized.</p>
<h3>Setting the parameters</h3>
<p>The parameters, which are necessary for the algorithm, are set in the box <b>Parameters</b>.</p>
<p>At first there will be chosen the number <b>persons n</b>, which are concerned to get a share of the secret.
Furthermore you have to decide about a number <b> persons t</b> how many persons will be needed to reconstruct it.
The number of <b>persons t</b> may not be bigger than <b>persons n</b>. Both numbers have to be at least 2, as far
as <b>Verifiable Secret Sharing</b> doesn't make sense for less involved people than 2.</p>
<p>The next parameter to choose is the <b>secret s</b>. After that, the <b>module p</b>, which have to be a
safe prime, is calculated automatically. As far as the calculation of safe primes is quite complex, it is
highly recommended to use the given value. If you don't like to use the proposed safe prime, you still have
the possibility to enter any other safe prime as long it is at least twice as big than the <b>secret s</b>.
The last parameter is the <b>generator g</b> and is calculated automatically and cannot be changed.
The <b>generator g</b> will be calculated automatically like <b>p</b>. The <b>generator g</b> is an element of the field Z_p* and has the order <b>q</b>.
</p>
<p><img src="vss_parameter_2.jpg"></p>
<p>If all parameters are set correctly, it is possible to go on to the next step with a click on <b>Determine coefficients</b>.</p>
<h3>Determining the coefficients for the polynomial and calculating the commitments</h3>
<p>The <b>coefficients</b> for the polynomial are set in this box.
They can be generated by <b>JCrypTool</b> or chosen by yourself.
The coefficients have to be natural numbers smaller than the <b>module p</b>
The first coefficient is fixed, and is the <b>secret s</b> which already has been chosen.</p>
<p><img src="vss_coefficients_3.jpg"></p>
<p>In this box you can also find the button <b>Commit</b>. The computation of the commitments is necessary for the verification of the shares afterwards.
The commitments are shown in a separate box after they are calculated.
</p>
<p><img src="vss_commitments_4.jpg"></p>
<p>The computation of the commitments is optional, as far as they are just needed to check the shares afterwards.
They are not needed for the reconstruction of the secret. If you want to do the reconstruction without checking the shares, you don't need the commitments.
</p>
<p>Go on to the next step for calculating the shares with a click on <b>Calculate shares</b></p>
<h3>Checking the shares and reconstruction</h3>
<p>The last step is splitted up in 2 boxes: <b>Shares</b> and <b>Reconstruction</b></p>
<p>The box <b>Shares</b> shows the shares and the shares mod q. For checking the shares, a click on the respective <b>Check</b>-button is necessary.
Keep in mind that the check won't be successful if you didn't have done the calculating of the commitments first. To show the sense of checking the shares
it is possible to change one or more shares. The change of one or more shares has 2 consequences. At first the check for the modified share won't be successful anymore.
And second the reconstruct won't return the primordial secret.
</p>
<p><img src="vss_shares_5.jpg"></p>
<p>The reconstruction can be done in the box <b>Reconstruction</b>. Before you can start with a click on <b>reconstruct</b>
it is essential to choose the shares you want to use. It is irrelevant which ones you take as long as equal or more than the minimum.
The minimum is the number of <b>persons t</b> you have chosen in the beginning.</p>
<p><img src="vss_reconstruct_6.jpg"></p>
</body>
</html>
|
kevinott/crypto
|
org.jcryptool.visual.verifiablesecretsharing/nl/en/help/content/index.html
|
HTML
|
epl-1.0
| 5,284
|
/******************************************************************************
* Copyright (c) 2000-2016 Ericsson Telecom AB
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Balasko, Jeno
* Delic, Adam
* Raduly, Csaba
* Szabados, Kristof
* Szabo, Janos Zoltan – initial implementation
* Szalai, Gabor
*
******************************************************************************/
#include <string.h>
#include <sys/types.h>
#include <regex.h>
#include "../common/memory.h"
#include "../common/pattern.hh"
#include "TEXT.hh"
#include "Addfunc.hh"
#include "Logger.hh"
#include "Integer.hh"
#include "Charstring.hh"
#define ERRMSG_BUFSIZE2 500
Token_Match::Token_Match(const char *posix_str, boolean case_sensitive,
boolean fixed)
: posix_regexp_begin()
, posix_regexp_first()
, token_str(posix_str)
, fixed_len(0)
, null_match(FALSE)
{
if (posix_str == NULL || posix_str[0] == '\0') {
token_str = "";
null_match = TRUE;
return;
}
if (fixed) {
// no regexp
fixed_len = strlen(posix_str);
if (!case_sensitive) {
// Can't happen. The compiler should always generate
// case sensitive matching for fixed strings.
TTCN_EncDec_ErrorContext::error_internal(
"Case insensitive fixed string matching not implemented");
}
}
else {
int regcomp_flags = REG_EXTENDED;
if (!case_sensitive) regcomp_flags |= REG_ICASE;
int ret_val = regcomp(&posix_regexp_begin, posix_str, regcomp_flags);
if (ret_val != 0) {
char msg[ERRMSG_BUFSIZE2];
regerror(ret_val, &posix_regexp_begin, msg, ERRMSG_BUFSIZE2);
TTCN_error("Internal error: regcomp() failed on posix_regexp_begin when "
"constructing Token_Match: %s", msg);
}
ret_val = regcomp(&posix_regexp_first, posix_str + 1, regcomp_flags);
if (ret_val != 0) {
regfree(&posix_regexp_begin);
char msg[ERRMSG_BUFSIZE2];
regerror(ret_val, &posix_regexp_first, msg, ERRMSG_BUFSIZE2);
TTCN_error("Internal error: regcomp() failed on posix_regexp_first when "
"constructing Token_Match: %s", msg);
}
}
}
Token_Match::~Token_Match()
{
if (!null_match && fixed_len == 0) {
regfree(&posix_regexp_begin);
regfree(&posix_regexp_first);
}
}
int Token_Match::match_begin(TTCN_Buffer& buff) const
{
int retval=-1;
int ret_val=-1;
if(null_match){
if (TTCN_EncDec::get_error_behavior(TTCN_EncDec::ET_LOG_MATCHING) !=
TTCN_EncDec::EB_IGNORE) {
char msg[ERRMSG_BUFSIZE2];
regerror(ret_val, &posix_regexp_begin, msg, ERRMSG_BUFSIZE2);
TTCN_Logger::log(TTCN_Logger::DEBUG_ENCDEC, "match_begin data: %s",
(const char*)buff.get_read_data());
TTCN_Logger::begin_event(TTCN_Logger::DEBUG_ENCDEC);
TTCN_Logger::log_event_str("match_begin token: null_match");
TTCN_Logger::end_event();
TTCN_Logger::log(TTCN_Logger::DEBUG_ENCDEC, "match_begin result: 0");
}
return 0;
}
if (fixed_len != 0) { //
retval=strncmp((const char*)buff.get_read_data(), token_str, fixed_len)
? -1 // not matched
: fixed_len;
} else {
regmatch_t pmatch[2];
ret_val=regexec(&posix_regexp_begin,(const char*)buff.get_read_data(),
2, pmatch, 0);
if(ret_val==0) {
retval=pmatch[1].rm_eo-pmatch[1].rm_so; // pmatch[1] is the capture group
} else if (ret_val==REG_NOMATCH) {
retval=-1;
} else {
/* regexp error */
char msg[ERRMSG_BUFSIZE2];
regerror(ret_val, &posix_regexp_begin, msg, ERRMSG_BUFSIZE2);
TTCN_error("Internal error: regexec() failed in "
"Token_Match::match_begin(): %s", msg);
}
}
if (TTCN_EncDec::get_error_behavior(TTCN_EncDec::ET_LOG_MATCHING) !=
TTCN_EncDec::EB_IGNORE) {
TTCN_Logger::log(TTCN_Logger::DEBUG_ENCDEC, "match_begin data: %s",
(const char*)buff.get_read_data());
TTCN_Logger::begin_event(TTCN_Logger::DEBUG_ENCDEC);
TTCN_Logger::log_event_str("match_begin token: \"");
for (size_t i = 0; token_str[i] != '\0'; i++)
TTCN_Logger::log_char_escaped(token_str[i]);
TTCN_Logger::log_char('"');
TTCN_Logger::end_event();
if(fixed_len == 0){
char msg[ERRMSG_BUFSIZE2];
regerror(ret_val, &posix_regexp_begin, msg, ERRMSG_BUFSIZE2);
TTCN_Logger::log(TTCN_Logger::DEBUG_ENCDEC, "match_begin regexec result: %d, %s",
ret_val,msg);
}
TTCN_Logger::log(TTCN_Logger::DEBUG_ENCDEC, "match_begin result: %d",
retval);
}
return retval;
}
int Token_Match::match_first(TTCN_Buffer& buff) const
{
int retval=-1;
int ret_val=-1;
if(null_match){
if (TTCN_EncDec::get_error_behavior(TTCN_EncDec::ET_LOG_MATCHING) !=
TTCN_EncDec::EB_IGNORE) {
char msg[ERRMSG_BUFSIZE2];
regerror(ret_val, &posix_regexp_begin, msg, ERRMSG_BUFSIZE2);
TTCN_Logger::log(TTCN_Logger::DEBUG_ENCDEC, "match_first data: %s",
(const char*)buff.get_read_data());
TTCN_Logger::begin_event(TTCN_Logger::DEBUG_ENCDEC);
TTCN_Logger::log_event_str("match_first token: null_match");
TTCN_Logger::end_event();
TTCN_Logger::log(TTCN_Logger::DEBUG_ENCDEC, "match_first result: 0");
}
return 0;
}
//TTCN_Logger::log(TTCN_Logger::DEBUG_ENCDEC,"match_first data: %s\n\r",(const char*)buff.get_read_data());
//TTCN_Logger::log(TTCN_Logger::DEBUG_ENCDEC,"match_first token: %s\n\r",token);
if (fixed_len != 0) {
const char *haystack = (const char*)buff.get_read_data();
const char *pos = strstr(haystack, token_str); // TODO smarter search: Boyer-Moore / Shift-Or
retval = (pos == NULL) ? -1 : (pos - haystack);
} else {
regmatch_t pmatch[2];
ret_val=regexec(&posix_regexp_first,(const char*)buff.get_read_data(),
2, pmatch, REG_NOTBOL);
if(ret_val==0) {
retval=pmatch[1].rm_so;
} else if (ret_val==REG_NOMATCH) {
retval=-1;
} else {
/* regexp error */
char msg[ERRMSG_BUFSIZE2];
regerror(ret_val, &posix_regexp_begin, msg, ERRMSG_BUFSIZE2);
TTCN_error("Internal error: regexec() failed in "
"Token_Match::match_first(): %s", msg);
}
}
if (TTCN_EncDec::get_error_behavior(TTCN_EncDec::ET_LOG_MATCHING) !=
TTCN_EncDec::EB_IGNORE) {
TTCN_Logger::log(TTCN_Logger::DEBUG_ENCDEC, "match_first data: %s",
(const char*)buff.get_read_data());
TTCN_Logger::begin_event(TTCN_Logger::DEBUG_ENCDEC);
TTCN_Logger::log_event_str("match_first token: \"");
for (size_t i = 0; token_str[i] != '\0'; i++)
TTCN_Logger::log_char_escaped(token_str[i]);
TTCN_Logger::log_char('"');
TTCN_Logger::end_event();
if (fixed_len == 0) {
char msg[ERRMSG_BUFSIZE2];
regerror(ret_val, &posix_regexp_begin, msg, ERRMSG_BUFSIZE2);
TTCN_Logger::log(TTCN_Logger::DEBUG_ENCDEC, "match_begin regexec result: %d, %s",
ret_val,msg);
}
TTCN_Logger::log(TTCN_Logger::DEBUG_ENCDEC, "match_first result: %d",
retval);
}
return retval;
}
Limit_Token_List::Limit_Token_List(){
num_of_tokens=0;
size_of_list=16;
list=(const Token_Match **)Malloc(size_of_list*sizeof(Token_Match *));
last_match=(int *)Malloc(size_of_list*sizeof(int));
last_ret_val=-1;
last_pos=NULL;
}
Limit_Token_List::~Limit_Token_List(){
Free(list);
Free(last_match);
}
void Limit_Token_List::add_token(const Token_Match *token){
if(num_of_tokens==size_of_list){
size_of_list*=2;
list=(const Token_Match **)Realloc(list,size_of_list*sizeof(Token_Match *));
last_match=(int *)Realloc(last_match,size_of_list*sizeof(int));
}
list[num_of_tokens]=token;
last_match[num_of_tokens]=-1;
num_of_tokens++;
}
void Limit_Token_List::remove_tokens(size_t num){
if(num_of_tokens<num) num_of_tokens=0;
else num_of_tokens-=num;
}
int Limit_Token_List::match(TTCN_Buffer& buff, size_t lim){
int ret_val=-1;
const char* curr_pos=(const char*)buff.get_read_data();
//TTCN_Logger::log(TTCN_Logger::DEBUG_ENCDEC,"Limit Token begin: %s\n\r",(const char*)buff.get_read_data());
if(last_pos!=NULL){
int diff=curr_pos-last_pos;
if(diff){
for(size_t a=0;a<num_of_tokens;a++){
last_match[a]-=diff;
}
last_ret_val-=diff;
}
}
last_pos=curr_pos;
// if(last_ret_val<0){
for(size_t a=0;a<num_of_tokens-lim;a++){
if(last_match[a]<0) last_match[a]=list[a]->match_first(buff);
if(last_match[a]>=0){
if(ret_val==-1) ret_val=last_match[a];
else if(last_match[a]<ret_val) ret_val=last_match[a];
}
}
last_ret_val=ret_val;
// }
if (TTCN_EncDec::get_error_behavior(TTCN_EncDec::ET_LOG_MATCHING)!=
TTCN_EncDec::EB_IGNORE) {
TTCN_Logger::log(TTCN_Logger::DEBUG_ENCDEC,
"match_list data: %s",(const char*)buff.get_read_data());
TTCN_Logger::log(TTCN_Logger::DEBUG_ENCDEC,"match_list result: %d",ret_val);
}
return ret_val;
}
const TTCN_TEXTdescriptor_t INTEGER_text_ = { NULL, NULL, NULL, NULL,
NULL, NULL, NULL, { NULL } };
const TTCN_TEXTdescriptor_t BOOLEAN_text_ = { NULL, NULL, NULL, NULL,
NULL, NULL, NULL, { NULL } };
const TTCN_TEXTdescriptor_t CHARSTRING_text_ = { NULL, NULL, NULL, NULL,
NULL, NULL, NULL, { NULL } };
const TTCN_TEXTdescriptor_t UNIVERSAL_CHARSTRING_text_ = { NULL, NULL, NULL, NULL,
NULL, NULL, NULL, { NULL } };
const TTCN_TEXTdescriptor_t BITSTRING_text_ = { NULL, NULL, NULL, NULL,
NULL, NULL, NULL, { NULL } };
const TTCN_TEXTdescriptor_t HEXSTRING_text_ = { NULL, NULL, NULL, NULL,
NULL, NULL, NULL, { NULL } };
const TTCN_TEXTdescriptor_t OCTETSTRING_text_ = { NULL, NULL, NULL, NULL,
NULL, NULL, NULL, { NULL } };
|
BenceJanosSzabo/titan.core
|
core/TEXT.cc
|
C++
|
epl-1.0
| 9,846
|
/*******************************************************************************
* Copyright (c) 2017, 2020 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.wsspi.security.wim.model;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
import com.ibm.websphere.ras.annotation.Trivial;
import com.ibm.websphere.security.wim.ras.WIMTraceHelper;
/**
* <p>Java class for Country complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="Country">
* <complexContent>
* <extension base="{http://www.ibm.com/websphere/wim}GeographicLocation">
* <sequence>
* <element ref="{http://www.ibm.com/websphere/wim}c" minOccurs="0"/>
* <element ref="{http://www.ibm.com/websphere/wim}countryName" minOccurs="0"/>
* <element ref="{http://www.ibm.com/websphere/wim}description" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
* <p> The Country object extends the GeographicLocation object, and represents information related to a country.
* It contains several properties: <b>c</b>, <b>countryName</b> and <b>description</b>.
*
* <ul>
* <li><b>c</b>: short form for the <b>countryName</b> property.</li>
* <li><b>countryName</b>: defines the name of the country.</li>
* <li><b>description</b>: describes this object.</li>
* </ul>
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Country", propOrder = {
"c",
"countryName",
"description"
})
@Trivial
public class Country extends GeographicLocation {
private static final String PROP_C = "c";
private static final String PROP_COUNTRY_NAME = "countryName";
private static final String PROP_DESCRIPTION = "description";
protected String c;
protected String countryName;
protected List<String> description;
private static List propertyNames = null;
private static HashMap dataTypeMap = null;
private static ArrayList superTypeList = null;
private static HashSet subTypeList = null;
/** The set of multi-valued properties for this entity type. */
private static final Set<String> MULTI_VALUED_PROPERTIES;
static {
setDataTypeMap();
setSuperTypes();
setSubTypes();
MULTI_VALUED_PROPERTIES = new HashSet<String>();
MULTI_VALUED_PROPERTIES.add(PROP_DESCRIPTION);
}
/**
* Gets the value of the <b>c</b> property.
*
* @return
* possible object is {@link String }
*
*/
public String getC() {
return c;
}
/**
* Sets the value of the <b>c</b> property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setC(String value) {
this.c = value;
}
/**
* Returns true if the <b>c</b> property is set; false, otherwise.
*
* @return
* returned object is {@link boolean }
*
*/
public boolean isSetC() {
return (this.c != null);
}
/**
* Gets the value of the <b>countryName</b> property.
*
* @return
* possible object is {@link String }
*
*/
public String getCountryName() {
return countryName;
}
/**
* Sets the value of the <b>countryName</b> property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setCountryName(String value) {
this.countryName = value;
}
/**
* Returns true if the <b>countryName</b> property is set; false, otherwise.
*
* @return
* returned object is {@link boolean }
*
*/
public boolean isSetCountryName() {
return (this.countryName != null);
}
/**
* Gets the value of the <b>description</b> property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the description property.
*
* <p>
* For example, to add a new item, do as follows:
*
* <pre>
* getDescription().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list {@link String }
*
*
*/
public List<String> getDescription() {
if (description == null) {
description = new ArrayList<String>();
}
return this.description;
}
/**
* Returns true if the <b>description</b> property is set; false, otherwise.
*
* @return
* returned object is {@link boolean }
*
*/
public boolean isSetDescription() {
return ((this.description != null) && (!this.description.isEmpty()));
}
/**
* Resets the <b>description</b> property to null.
*
*/
public void unsetDescription() {
this.description = null;
}
/**
* Gets the value of the requested property
*
* @param propName
* allowed object is {@link String}
*
* @return
* returned object is {@link Object}
*
*/
@Override
public Object get(String propName) {
if (propName.equals(PROP_C)) {
return getC();
}
if (propName.equals(PROP_COUNTRY_NAME)) {
return getCountryName();
}
if (propName.equals(PROP_DESCRIPTION)) {
return getDescription();
}
return super.get(propName);
}
/**
* Returns true if the requested property is set; false, otherwise.
*
* @return
* returned object is {@link boolean }
*
*/
@Override
public boolean isSet(String propName) {
if (propName.equals(PROP_C)) {
return isSetC();
}
if (propName.equals(PROP_COUNTRY_NAME)) {
return isSetCountryName();
}
if (propName.equals(PROP_DESCRIPTION)) {
return isSetDescription();
}
return super.isSet(propName);
}
/**
* Sets the value of the provided property to the provided value.
*
* @param propName
* allowed object is {@link String}
* @param value
* allowed object is {@link Object}
*
*/
@Override
public void set(String propName, Object value) {
if (propName.equals(PROP_C)) {
setC(((String) value));
}
if (propName.equals(PROP_COUNTRY_NAME)) {
setCountryName(((String) value));
}
if (propName.equals(PROP_DESCRIPTION)) {
getDescription().add(((String) value));
}
super.set(propName, value);
}
/**
* Sets the value of provided property to null.
*
* @param propName
* allowed object is {@link String}
*
*/
@Override
public void unset(String propName) {
if (propName.equals(PROP_DESCRIPTION)) {
unsetDescription();
}
super.unset(propName);
}
/**
* Gets the name of this model object, <b>Country</b>
*
* @return
* returned object is {@link String}
*/
@Override
public String getTypeName() {
return "Country";
}
/**
* Gets a list of all supported properties for this model object, <b>Country</b>
*
* @param entityTypeName
* allowed object is {@link String}
*
* @return
* returned object is {@link List}
*/
public static synchronized List getPropertyNames(String entityTypeName) {
if (propertyNames != null) {
return propertyNames;
} else {
{
List names = new ArrayList();
names.add(PROP_C);
names.add(PROP_COUNTRY_NAME);
names.add(PROP_DESCRIPTION);
names.addAll(GeographicLocation.getPropertyNames("GeographicLocation"));
propertyNames = Collections.unmodifiableList(names);
return propertyNames;
}
}
}
private static synchronized void setDataTypeMap() {
if (dataTypeMap == null) {
dataTypeMap = new HashMap();
}
dataTypeMap.put(PROP_C, "String");
dataTypeMap.put(PROP_COUNTRY_NAME, "String");
dataTypeMap.put(PROP_DESCRIPTION, "String");
}
/**
* Gets the Java type of the value of the provided property. For example: String, List
*
* @param propName
* allowed object is {@link String}
*
* @return
* returned object is {@link String}
*/
@Override
public String getDataType(String propName) {
if (dataTypeMap.containsKey(propName)) {
return ((String) dataTypeMap.get(propName));
} else {
return super.getDataType(propName);
}
}
private static synchronized void setSuperTypes() {
if (superTypeList == null) {
superTypeList = new ArrayList();
}
superTypeList.add("GeographicLocation");
superTypeList.add("Entity");
}
/**
* Gets a list of any model objects which this model object, <b>Country</b>, is
* an extension of.
*
* @return
* returned object is {@link ArrayList}
*/
@Override
public ArrayList getSuperTypes() {
if (superTypeList == null) {
setSuperTypes();
}
return superTypeList;
}
/**
* Returns a true if the provided model object is one that this
* model object extends; false, otherwise.
*
* @param superTypeName
*
* allowed object is {@link String}
* @return
* returned object is {@link boolean}
*/
@Override
public boolean isSubType(String superTypeName) {
return superTypeList.contains(superTypeName);
}
private static synchronized void setSubTypes() {
if (subTypeList == null) {
subTypeList = new HashSet();
}
}
/**
* Gets a set of any model objects which extend this model object, <b>Country</b>
*
* @return
* returned object is {@link HashSet}
*/
public static HashSet getSubTypes() {
if (subTypeList == null) {
setSubTypes();
}
return subTypeList;
}
@Override
public String toString() {
return WIMTraceHelper.trace(this);
}
@Override
public boolean isMultiValuedProperty(String propName) {
return MULTI_VALUED_PROPERTIES.contains(propName) || super.isMultiValuedProperty(propName);
}
}
|
OpenLiberty/open-liberty
|
dev/com.ibm.websphere.security.wim.base/src/com/ibm/wsspi/security/wim/model/Country.java
|
Java
|
epl-1.0
| 11,612
|
##############################################################################
# Copyright (c) 2000-2016 Ericsson Telecom AB
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# Balasko, Jeno
# Delic, Adam
#
##############################################################################
import xml.etree.ElementTree as ET
tree = ET.parse('project_hierarchy_graph.xml')
root = tree.getroot()
f = open('project_hierarchy_graph.dot', 'w')
f.write("digraph PROJECT_HIERARCHY_GRAPH {\n")
for project in root:
for reference in project:
f.write(project.attrib['name'])
f.write(" -> ")
f.write(reference.attrib['name'])
f.write(";\n")
f.write("}\n")
f.close()
# use this to generate graph:
# > dot -Tpng project_hierarchy_graph.dot -o project_hierarchy_graph.png
|
BenceJanosSzabo/titan.core
|
etc/scripts/tpd_graph_xml2dot.py
|
Python
|
epl-1.0
| 978
|
package org.jboss.windup.rules.annotationtests.complex;
import javax.annotation.sql.DataSourceDefinition;
import javax.annotation.sql.DataSourceDefinitions;
/**
* @author <a href="mailto:dklingenberg@gmail.com">David Klingenberg</a>
*/
@DataSourceDefinitions({
@DataSourceDefinition(
name = "jdbc/multiple-ds-xa",
className="com.example.MyDataSource",
portNumber=6689,
serverName="example.com",
user="lance",
password="secret"
),
@DataSourceDefinition(
name = "jdbc/multiple-ds-non-xa",
className="com.example.MyDataSource",
portNumber=6689,
serverName="example.com",
user="lance",
password="secret",
transactional = false
),
@DataSourceDefinition(
name = "jdbc/has-some-nulls",
className="com.example.HasSOmeNulls",
portNumber=6689,
serverName=null,
user="otheruser",
password="othersecret",
transactional = true
),
})
public class AnnotationMultipleDs
{
}
|
windup/windup
|
rules-java/tests/src/test/resources/org/jboss/windup/rules/annotationtests/complex/AnnotationMultipleDs.java
|
Java
|
epl-1.0
| 1,230
|
/*******************************************************************************
* Copyright (c) 2019 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.jaxrs.fat.beanvalidation;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.validation.executable.ExecutableType;
import javax.validation.executable.ValidateOnExecution;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
@Path("/bookstore/")
public class BookStoreWithValidation extends AbstractBookStoreWithValidation implements BookStoreValidatable {
private final Map<String, BookWithValidation> books = new HashMap<String, BookWithValidation>();
public BookStoreWithValidation() {}
@GET
@Path("/books/{bookId}")
@Override
@NotNull
@Produces(MediaType.APPLICATION_XML)
@Consumes(MediaType.APPLICATION_XML)
public BookWithValidation getBook(@PathParam("bookId") String id) {
return books.get(id);
}
@GET
@Path("/booksResponse/{bookId}")
@Valid
@NotNull
@Produces(MediaType.APPLICATION_XML)
@Consumes(MediaType.APPLICATION_XML)
public Response getBookResponse(@PathParam("bookId") String id) {
return Response.ok(books.get(id)).build();
}
@GET
@Path("/booksResponseNoValidation/{bookId}")
@Produces(MediaType.APPLICATION_XML)
@Consumes(MediaType.APPLICATION_XML)
public Response getBookResponseNoValidation(@PathParam("bookId") String id) {
return Response.ok(books.get(id)).build();
}
@POST
@Path("/books")
public Response addBook(@Context final UriInfo uriInfo,
@NotNull @Size(min = 1, max = 50) @FormParam("id") String id,
@FormParam("name") String name) {
books.put(id, new BookWithValidation(name, id));
return Response.created(uriInfo.getRequestUriBuilder().path(id).build()).build();
}
@POST
@Path("/books/direct")
@Consumes("text/xml")
public Response addBookDirect(@Valid BookWithValidation book, @Context final UriInfo uriInfo) {
books.put(book.getId(), book);
return Response.created(uriInfo.getRequestUriBuilder().path(book.getId()).build()).build();
}
@POST
@Path("/booksNoValidate")
@ValidateOnExecution(type = ExecutableType.NONE)
public Response addBookNoValidation(@NotNull @FormParam("id") String id) {
return Response.ok().build();
}
@POST
@Path("/booksValidate")
@ValidateOnExecution(type = ExecutableType.IMPLICIT)
public Response addBookValidate(@NotNull @FormParam("id") String id) {
return Response.ok().build();
}
@POST
@Path("/books/directmany")
@Produces(MediaType.APPLICATION_XML)
@Consumes(MediaType.APPLICATION_XML)
public Response addBooksDirect(@Valid List<BookWithValidation> list, @Context final UriInfo uriInfo) {
books.put(list.get(0).getId(), list.get(0));
return Response.created(uriInfo.getRequestUriBuilder().path(list.get(0).getId()).build()).build();
}
@Override
@GET
@Path("/books")
@Produces(MediaType.APPLICATION_XML)
@Consumes(MediaType.APPLICATION_XML)
public Collection<BookWithValidation> list(@DefaultValue("1") @QueryParam("page") int page) {
return books.values();
}
@DELETE
@Path("/books")
public Response clear() {
books.clear();
return Response.ok().build();
}
}
|
OpenLiberty/open-liberty
|
dev/com.ibm.ws.jaxrs.2.0_fat/test-applications/beanvalidation/src/com/ibm/ws/jaxrs/fat/beanvalidation/BookStoreWithValidation.java
|
Java
|
epl-1.0
| 4,343
|
/*******************************************************************************
* Copyright (c) 2000, 2015 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.wst.jsdt.internal.core;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.ISafeRunnable;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.SafeRunner;
import org.eclipse.core.runtime.Status;
import org.eclipse.wst.jsdt.core.IIncludePathEntry;
import org.eclipse.wst.jsdt.core.IElementChangedListener;
import org.eclipse.wst.jsdt.core.IJavaScriptElement;
import org.eclipse.wst.jsdt.core.IJavaScriptModel;
import org.eclipse.wst.jsdt.core.IJavaScriptProject;
import org.eclipse.wst.jsdt.core.JavaScriptCore;
import org.eclipse.wst.jsdt.core.JavaScriptModelException;
import org.eclipse.wst.jsdt.internal.core.util.Util;
/**
* Keep the global states used during Java element delta processing.
*/
public class DeltaProcessingState implements IResourceChangeListener {
/*
* Collection of listeners for Java element deltas
*/
public IElementChangedListener[] elementChangedListeners = new IElementChangedListener[5];
public int[] elementChangedListenerMasks = new int[5];
public int elementChangedListenerCount = 0;
/*
* Collection of pre Java resource change listeners
*/
public IResourceChangeListener[] preResourceChangeListeners = new IResourceChangeListener[1];
public int[] preResourceChangeEventMasks = new int[1];
public int preResourceChangeListenerCount = 0;
/*
* The delta processor for the current thread.
*/
private ThreadLocal deltaProcessors = new ThreadLocal();
/* A table from IPath (from a classpath entry) to DeltaProcessor.RootInfo */
public HashMap roots = new HashMap();
/* A table from IPath (from a classpath entry) to ArrayList of DeltaProcessor.RootInfo
* Used when an IPath corresponds to more than one root */
public HashMap otherRoots = new HashMap();
/* A table from IPath (from a classpath entry) to DeltaProcessor.RootInfo
* from the last time the delta processor was invoked. */
public HashMap oldRoots = new HashMap();
/* A table from IPath (from a classpath entry) to ArrayList of DeltaProcessor.RootInfo
* from the last time the delta processor was invoked.
* Used when an IPath corresponds to more than one root */
public HashMap oldOtherRoots = new HashMap();
/* A table from IPath (a source attachment path from a classpath entry) to IPath (a root path) */
public HashMap sourceAttachments = new HashMap();
/* A table from IJavaScriptProject to IJavaScriptProject[] (the list of direct dependent of the key) */
public HashMap projectDependencies = new HashMap();
/* Whether the roots tables should be recomputed */
public boolean rootsAreStale = true;
/* Threads that are currently running initializeRoots() */
private Set initializingThreads = Collections.synchronizedSet(new HashSet());
/* A table from file system absoulte path (String) to timestamp (Long) */
public Hashtable externalTimeStamps;
/* A table from JavaProject to ClasspathValidation */
private HashMap classpathValidations = new HashMap();
/* A table from JavaProject to ProjectReferenceChange */
private HashMap projectReferenceChanges= new HashMap();
/**
* Workaround for bug 15168 circular errors not reported
* This is a cache of the projects before any project addition/deletion has started.
*/
private HashSet javaProjectNamesCache;
/*
* Need to clone defensively the listener information, in case some listener is reacting to some notification iteration by adding/changing/removing
* any of the other (for example, if it deregisters itself).
*/
public synchronized void addElementChangedListener(IElementChangedListener listener, int eventMask) {
for (int i = 0; i < this.elementChangedListenerCount; i++){
if (this.elementChangedListeners[i] == listener){
// only clone the masks, since we could be in the middle of notifications and one listener decide to change
// any event mask of another listeners (yet not notified).
int cloneLength = this.elementChangedListenerMasks.length;
System.arraycopy(this.elementChangedListenerMasks, 0, this.elementChangedListenerMasks = new int[cloneLength], 0, cloneLength);
this.elementChangedListenerMasks[i] |= eventMask; // could be different
return;
}
}
// may need to grow, no need to clone, since iterators will have cached original arrays and max boundary and we only add to the end.
int length;
if ((length = this.elementChangedListeners.length) == this.elementChangedListenerCount){
System.arraycopy(this.elementChangedListeners, 0, this.elementChangedListeners = new IElementChangedListener[length*2], 0, length);
System.arraycopy(this.elementChangedListenerMasks, 0, this.elementChangedListenerMasks = new int[length*2], 0, length);
}
this.elementChangedListeners[this.elementChangedListenerCount] = listener;
this.elementChangedListenerMasks[this.elementChangedListenerCount] = eventMask;
this.elementChangedListenerCount++;
}
public synchronized void addPreResourceChangedListener(IResourceChangeListener listener, int eventMask) {
for (int i = 0; i < this.preResourceChangeListenerCount; i++){
if (this.preResourceChangeListeners[i] == listener) {
this.preResourceChangeEventMasks[i] |= eventMask;
return;
}
}
// may need to grow, no need to clone, since iterators will have cached original arrays and max boundary and we only add to the end.
int length;
if ((length = this.preResourceChangeListeners.length) == this.preResourceChangeListenerCount) {
System.arraycopy(this.preResourceChangeListeners, 0, this.preResourceChangeListeners = new IResourceChangeListener[length*2], 0, length);
System.arraycopy(this.preResourceChangeEventMasks, 0, this.preResourceChangeEventMasks = new int[length*2], 0, length);
}
this.preResourceChangeListeners[this.preResourceChangeListenerCount] = listener;
this.preResourceChangeEventMasks[this.preResourceChangeListenerCount] = eventMask;
this.preResourceChangeListenerCount++;
}
public DeltaProcessor getDeltaProcessor() {
DeltaProcessor deltaProcessor = (DeltaProcessor)this.deltaProcessors.get();
if (deltaProcessor != null) return deltaProcessor;
deltaProcessor = new DeltaProcessor(this, JavaModelManager.getJavaModelManager());
this.deltaProcessors.set(deltaProcessor);
return deltaProcessor;
}
public synchronized ClasspathValidation addClasspathValidation(JavaProject project) {
ClasspathValidation validation = (ClasspathValidation) this.classpathValidations.get(project);
if (validation == null) {
validation = new ClasspathValidation(project);
this.classpathValidations.put(project, validation);
}
return validation;
}
public synchronized void addProjectReferenceChange(JavaProject project, IIncludePathEntry[] oldResolvedClasspath) {
ProjectReferenceChange change = (ProjectReferenceChange) this.projectReferenceChanges.get(project);
if (change == null) {
change = new ProjectReferenceChange(project, oldResolvedClasspath);
this.projectReferenceChanges.put(project, change);
}
}
public void initializeRoots() {
// recompute root infos only if necessary
HashMap newRoots = null;
HashMap newOtherRoots = null;
HashMap newSourceAttachments = null;
HashMap newProjectDependencies = null;
if (this.rootsAreStale) {
Thread currentThread = Thread.currentThread();
boolean addedCurrentThread = false;
try {
// if reentering initialization (through a container initializer for example) no need to compute roots again
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=47213
if (!this.initializingThreads.add(currentThread)) return;
addedCurrentThread = true;
// all classpaths in the workspace are going to be resolved
// ensure that containers are initialized in one batch
JavaModelManager.getJavaModelManager().batchContainerInitializations = true;
newRoots = new HashMap();
newOtherRoots = new HashMap();
newSourceAttachments = new HashMap();
newProjectDependencies = new HashMap();
IJavaScriptModel model = JavaModelManager.getJavaModelManager().getJavaModel();
IJavaScriptProject[] projects;
try {
projects = model.getJavaScriptProjects();
} catch (JavaScriptModelException e) {
// nothing can be done
return;
}
for (int i = 0, length = projects.length; i < length; i++) {
JavaProject project = (JavaProject) projects[i];
IIncludePathEntry[] classpath;
try {
classpath = project.getResolvedClasspath();
} catch (JavaScriptModelException e) {
// continue with next project
continue;
}
for (int j= 0, classpathLength = classpath.length; j < classpathLength; j++) {
IIncludePathEntry entry = classpath[j];
if (entry.getEntryKind() == IIncludePathEntry.CPE_PROJECT) {
IJavaScriptProject key = model.getJavaScriptProject(entry.getPath().segment(0)); // TODO (jerome) reuse handle
IJavaScriptProject[] dependents = (IJavaScriptProject[]) newProjectDependencies.get(key);
if (dependents == null) {
dependents = new IJavaScriptProject[] {project};
} else {
int dependentsLength = dependents.length;
System.arraycopy(dependents, 0, dependents = new IJavaScriptProject[dependentsLength+1], 0, dependentsLength);
dependents[dependentsLength] = project;
}
newProjectDependencies.put(key, dependents);
continue;
}
// root path
IPath path = entry.getPath();
if (newRoots.get(path) == null) {
newRoots.put(path, new DeltaProcessor.RootInfo(project, path, ((ClasspathEntry)entry).fullInclusionPatternChars(), ((ClasspathEntry)entry).fullExclusionPatternChars(), entry.getEntryKind()));
} else {
ArrayList rootList = (ArrayList)newOtherRoots.get(path);
if (rootList == null) {
rootList = new ArrayList();
newOtherRoots.put(path, rootList);
}
rootList.add(new DeltaProcessor.RootInfo(project, path, ((ClasspathEntry)entry).fullInclusionPatternChars(), ((ClasspathEntry)entry).fullExclusionPatternChars(), entry.getEntryKind()));
}
// source attachment path
if (entry.getEntryKind() != IIncludePathEntry.CPE_LIBRARY) continue;
String propertyString = null;
try {
propertyString = Util.getSourceAttachmentProperty(path);
} catch (JavaScriptModelException e) {
e.printStackTrace();
}
IPath sourceAttachmentPath;
if (propertyString != null) {
int index= propertyString.lastIndexOf(PackageFragmentRoot.ATTACHMENT_PROPERTY_DELIMITER);
sourceAttachmentPath = (index < 0) ? new Path(propertyString) : new Path(propertyString.substring(0, index));
} else {
sourceAttachmentPath = entry.getSourceAttachmentPath();
}
if (sourceAttachmentPath != null) {
newSourceAttachments.put(sourceAttachmentPath, path);
}
}
}
} finally {
if (addedCurrentThread) {
this.initializingThreads.remove(currentThread);
}
}
}
synchronized(this) {
this.oldRoots = this.roots;
this.oldOtherRoots = this.otherRoots;
if (this.rootsAreStale && newRoots != null) { // double check again
this.roots = newRoots;
this.otherRoots = newOtherRoots;
this.sourceAttachments = newSourceAttachments;
this.projectDependencies = newProjectDependencies;
this.rootsAreStale = false;
}
}
}
public synchronized ClasspathValidation[] removeClasspathValidations() {
int length = this.classpathValidations.size();
if (length == 0) return null;
ClasspathValidation[] validations = new ClasspathValidation[length];
this.classpathValidations.values().toArray(validations);
this.classpathValidations.clear();
return validations;
}
public synchronized ProjectReferenceChange[] removeProjectReferenceChanges() {
int length = this.projectReferenceChanges.size();
if (length == 0) return null;
ProjectReferenceChange[] updates = new ProjectReferenceChange[length];
this.projectReferenceChanges.values().toArray(updates);
this.projectReferenceChanges.clear();
return updates;
}
public synchronized void removeElementChangedListener(IElementChangedListener listener) {
for (int i = 0; i < this.elementChangedListenerCount; i++){
if (this.elementChangedListeners[i] == listener){
// need to clone defensively since we might be in the middle of listener notifications (#fire)
int length = this.elementChangedListeners.length;
IElementChangedListener[] newListeners = new IElementChangedListener[length];
System.arraycopy(this.elementChangedListeners, 0, newListeners, 0, i);
int[] newMasks = new int[length];
System.arraycopy(this.elementChangedListenerMasks, 0, newMasks, 0, i);
// copy trailing listeners
int trailingLength = this.elementChangedListenerCount - i - 1;
if (trailingLength > 0){
System.arraycopy(this.elementChangedListeners, i+1, newListeners, i, trailingLength);
System.arraycopy(this.elementChangedListenerMasks, i+1, newMasks, i, trailingLength);
}
// update manager listener state (#fire need to iterate over original listeners through a local variable to hold onto
// the original ones)
this.elementChangedListeners = newListeners;
this.elementChangedListenerMasks = newMasks;
this.elementChangedListenerCount--;
return;
}
}
}
public synchronized void removePreResourceChangedListener(IResourceChangeListener listener) {
for (int i = 0; i < this.preResourceChangeListenerCount; i++){
if (this.preResourceChangeListeners[i] == listener){
// need to clone defensively since we might be in the middle of listener notifications (#fire)
int length = this.preResourceChangeListeners.length;
IResourceChangeListener[] newListeners = new IResourceChangeListener[length];
int[] newEventMasks = new int[length];
System.arraycopy(this.preResourceChangeListeners, 0, newListeners, 0, i);
System.arraycopy(this.preResourceChangeEventMasks, 0, newEventMasks, 0, i);
// copy trailing listeners
int trailingLength = this.preResourceChangeListenerCount - i - 1;
if (trailingLength > 0) {
System.arraycopy(this.preResourceChangeListeners, i+1, newListeners, i, trailingLength);
System.arraycopy(this.preResourceChangeEventMasks, i+1, newEventMasks, i, trailingLength);
}
// update manager listener state (#fire need to iterate over original listeners through a local variable to hold onto
// the original ones)
this.preResourceChangeListeners = newListeners;
this.preResourceChangeEventMasks = newEventMasks;
this.preResourceChangeListenerCount--;
return;
}
}
}
public void resourceChanged(final IResourceChangeEvent event) {
for (int i = 0; i < this.preResourceChangeListenerCount; i++) {
// wrap callbacks with Safe runnable for subsequent listeners to be called when some are causing grief
final IResourceChangeListener listener = this.preResourceChangeListeners[i];
if ((this.preResourceChangeEventMasks[i] & event.getType()) != 0)
SafeRunner.run(new ISafeRunnable() {
public void handleException(Throwable exception) {
Util.log(exception, "Exception occurred in listener of pre Java resource change notification"); //$NON-NLS-1$
}
public void run() throws Exception {
listener.resourceChanged(event);
}
});
}
try {
getDeltaProcessor().resourceChanged(event);
} finally {
// TODO (jerome) see 47631, may want to get rid of following so as to reuse delta processor ?
if (event.getType() == IResourceChangeEvent.POST_CHANGE) {
this.deltaProcessors.set(null);
}
}
}
public Hashtable getExternalLibTimeStamps() {
if (this.externalTimeStamps == null) {
Hashtable timeStamps = new Hashtable();
File timestampsFile = getTimeStampsFile();
DataInputStream in = null;
try {
in = new DataInputStream(new BufferedInputStream(new FileInputStream(timestampsFile)));
int size = in.readInt();
while (size-- > 0) {
String key = in.readUTF();
long timestamp = in.readLong();
timeStamps.put(Path.fromPortableString(key), Long.valueOf(timestamp));
}
} catch (IOException e) {
if (timestampsFile.exists())
Util.log(e, "Unable to read external time stamps"); //$NON-NLS-1$
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// nothing we can do: ignore
}
}
}
this.externalTimeStamps = timeStamps;
}
return this.externalTimeStamps;
}
public IJavaScriptProject findJavaProject(String name) {
if (getOldJavaProjecNames().contains(name))
return JavaModelManager.getJavaModelManager().getJavaModel().getJavaScriptProject(name);
return null;
}
/*
* Workaround for bug 15168 circular errors not reported
* Returns the list of java projects before resource delta processing
* has started.
*/
public synchronized HashSet getOldJavaProjecNames() {
if (this.javaProjectNamesCache == null) {
HashSet result = new HashSet();
IJavaScriptProject[] projects;
try {
projects = JavaModelManager.getJavaModelManager().getJavaModel().getJavaScriptProjects();
} catch (JavaScriptModelException e) {
return this.javaProjectNamesCache;
}
for (int i = 0, length = projects.length; i < length; i++) {
IJavaScriptProject project = projects[i];
result.add(project.getElementName());
}
return this.javaProjectNamesCache = result;
}
return this.javaProjectNamesCache;
}
public synchronized void resetOldJavaProjectNames() {
this.javaProjectNamesCache = null;
}
private File getTimeStampsFile() {
return JavaScriptCore.getPlugin().getStateLocation().append("externalLibsTimeStamps").toFile(); //$NON-NLS-1$
}
public void saveExternalLibTimeStamps() throws CoreException {
if (this.externalTimeStamps == null) return;
File timestamps = getTimeStampsFile();
DataOutputStream out = null;
try {
out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(timestamps)));
out.writeInt(this.externalTimeStamps.size());
Iterator entries = this.externalTimeStamps.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
IPath key = (IPath) entry.getKey();
out.writeUTF(key.toPortableString());
Long timestamp = (Long) entry.getValue();
out.writeLong(timestamp.longValue());
}
} catch (IOException e) {
IStatus status = new Status(IStatus.ERROR, JavaScriptCore.PLUGIN_ID, IStatus.ERROR, "Problems while saving timestamps", e); //$NON-NLS-1$
throw new CoreException(status);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// nothing we can do: ignore
}
}
}
}
/*
* Update the roots that are affected by the addition or the removal of the given container resource.
*/
public synchronized void updateRoots(IPath containerPath, IResourceDelta containerDelta, DeltaProcessor deltaProcessor) {
Map updatedRoots;
Map otherUpdatedRoots;
if (containerDelta.getKind() == IResourceDelta.REMOVED) {
updatedRoots = this.oldRoots;
otherUpdatedRoots = this.oldOtherRoots;
} else {
updatedRoots = this.roots;
otherUpdatedRoots = this.otherRoots;
}
int containerSegmentCount = containerPath.segmentCount();
boolean containerIsProject = containerSegmentCount == 1;
Iterator iterator = updatedRoots.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry) iterator.next();
IPath path = (IPath) entry.getKey();
if (containerPath.isPrefixOf(path) && !containerPath.equals(path)) {
IResourceDelta rootDelta = containerDelta.findMember(path.removeFirstSegments(containerSegmentCount));
if (rootDelta == null) continue;
DeltaProcessor.RootInfo rootInfo = (DeltaProcessor.RootInfo) entry.getValue();
if (!containerIsProject
|| !rootInfo.project.getPath().isPrefixOf(path)) { // only consider folder roots that are not included in the container
deltaProcessor.updateCurrentDeltaAndIndex(rootDelta, IJavaScriptElement.PACKAGE_FRAGMENT_ROOT, rootInfo);
}
ArrayList rootList = (ArrayList)otherUpdatedRoots.get(path);
if (rootList != null) {
Iterator otherProjects = rootList.iterator();
while (otherProjects.hasNext()) {
rootInfo = (DeltaProcessor.RootInfo)otherProjects.next();
if (!containerIsProject
|| !rootInfo.project.getPath().isPrefixOf(path)) { // only consider folder roots that are not included in the container
deltaProcessor.updateCurrentDeltaAndIndex(rootDelta, IJavaScriptElement.PACKAGE_FRAGMENT_ROOT, rootInfo);
}
}
}
}
}
}
}
|
boniatillo-com/PhaserEditor
|
source/thirdparty/jsdt/org.eclipse.wst.jsdt.core/src/org/eclipse/wst/jsdt/internal/core/DeltaProcessingState.java
|
Java
|
epl-1.0
| 21,933
|
/*******************************************************************************
* Copyright (c) 2017 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
@org.osgi.annotation.versioning.Version("1.0.16")
package org.apache.myfaces.shared.renderkit.html;
|
OpenLiberty/open-liberty
|
dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/shared/renderkit/html/package-info.java
|
Java
|
epl-1.0
| 635
|
package rlpark.example.demos.scheduling;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import rlpark.plugin.rltoys.experiments.scheduling.interfaces.JobDoneEvent;
import rlpark.plugin.rltoys.experiments.scheduling.queue.LocalQueue;
import rlpark.plugin.rltoys.experiments.scheduling.schedulers.LocalScheduler;
import zephyr.plugin.core.api.signals.Listener;
public class LocalScheduling {
static Iterator<? extends Runnable> createJobList() {
List<Runnable> jobs = new ArrayList<Runnable>();
for (int i = 0; i < 100; i++)
jobs.add(new Job());
return jobs.iterator();
}
static Listener<JobDoneEvent> createJobDoneListener() {
return new Listener<JobDoneEvent>() {
@Override
public void listen(JobDoneEvent eventInfo) {
System.out.println("Job done. Result: " + ((Job) eventInfo.done).result());
}
};
}
public static void main(String[] args) {
LocalScheduler scheduler = new LocalScheduler();
Iterator<? extends Runnable> jobList = createJobList();
Listener<JobDoneEvent> jobDoneListener = createJobDoneListener();
((LocalQueue) scheduler.queue()).add(jobList, jobDoneListener);
scheduler.start();
scheduler.waitAll();
}
}
|
rlpark/rlpark
|
rlpark.example.demos/src/rlpark/example/demos/scheduling/LocalScheduling.java
|
Java
|
epl-1.0
| 1,248
|
# SEMSPortal Binding
This binding can help you include statistics of your SEMS / GoodWe solar panel installation into openHAB.
It is a read-only connection that maps collected parameters to openHAB channels.
It provides current, day, month and total yields, as well as some income statistics if you have configured these in the SEMS portal.
It requires a power station that is connected through the internet to the SEMS portal.
## Supported Things
This binding provides two Thing types: a bridge to the SEMS Portal, and the Power Stations which are found at the Portal.
The Portal (``semsportal:portal``) represents your account in the SEMS portal.
The Power Station (``semsportal:station``) is an installation of a Power Station or inverter that reports to the SEMS portal and is available to your account.
## Discovery
Once you have configured a Portal Bridge, the binding will discover all Power Stations that are available to this account.
You can trigger discovery in the add new Thing section of openHAB.
Select the SEMS binding and press the Scan button.
The discovered Power Stations will appear as new Things.
## Thing Configuration
The configuration of the Portal Thing (Bridge) is pretty straight forward.
You need to have your power station set up in the SEMS portal, and you need to have an account that is allowed to view the power station data.
You should log in at least once in the portal with this account to activate it.
The Portal needs the username and password to connect and retrieve the data.
You can configure the update frequency between 1 and 60 minutes.
The default is 5 minutes.
Power Stations have no settings and will be auto discovered when you add a Portal Bridge.
If you prefer manual configuration of things in thing files, you need to supply the power station UUID.
It can be found in the SEMS portal URL after you have logged in.
The URL will look like this:
```
https://www.semsportal.com/PowerStation/PowerStatusSnMin/xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
```
Where the part after the last / character is the UUID to be used.
Example portal configuration with a station:
```
Bridge semsportal:portal:myPortal [ username="my@username.com", password="MyPassword" ] {
station solarPanels "Solar Panels" [ stationUUID="xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" ]
}
```
## Channels
The Portal(Bridge) has no channels.
The Power Station Thing has the following channels:
| channel | type | description |
| ------------- | ---------------- | ---------------------------------------------------------------------------------------------------------- |
| lastUpdate | DateTime | Last time the powerStation sent information to the portal |
| currentOutput | Number:Power | The current output of the powerStation in Watt |
| todayTotal | Number:Energy | Todays total generation of the station in kWh |
| monthTotal | Number:Energy | This month's total generation of the station in kWh |
| overallTotal | Number:Energy | The total generation of the station since installation, in kWh |
| todayIncome | Number | Todays income as reported by the portal, if you have configured the power rates of your energy provider |
| totalIncome | Number | The total income as reported by the portal, if you have configured the power rates of your energy provider |
## Parameters
The Power Station Thing has no configuration parameters when auto discovered.
When using thing files you need to provide the station UUID.
| Parameter | Required? | Description |
| ----------- |:---------:| ---------------------------------------------------------------------------------------------------------- |
| stationUUID | X | UUID of the station. Can be found on the SEMS portal URL (see description above) |
The Bridge has the following configuration parameters:
| Parameter | Required? | Description |
| ----------- |:---------:| ---------------------------------------------------------------------------------------------------------- |
| username | X | Account name (email address) at the SEMS portal. Account must have been used at least once to log in. |
| password | X | Password of the SEMS portal |
| interval | | Number of minutes between two updates. Between 1 and 60 minutes, defaults to 5 minutes |
## Credits
This binding has been created using the information provided by RogerG007 in this forum topic: https://community.openhab.org/t/connecting-goodwe-solar-panel-inverter-to-openhab/85480
|
paulianttila/openhab2
|
bundles/org.openhab.binding.semsportal/README.md
|
Markdown
|
epl-1.0
| 5,247
|
/*******************************************************************************
* Copyright (c) 2012 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.kernel.boot.jmx.service;
/**
* Service for injection and removal of MBeanServerForwarder
* filters into and from the platform MBeanServer.
*/
public interface MBeanServerPipeline {
/**
* Returns true if this MBeanServerPipeline contains the
* given MBeanServerForwarderDelegate.
*/
public boolean contains(MBeanServerForwarderDelegate filter);
/**
* Inserts an MBeanServerForwarderDelegate into the MBeanServerPipeline.
* Returns true if successful; false otherwise.
*/
public boolean insert(MBeanServerForwarderDelegate filter);
/**
* Removes an MBeanServerForwarderDelegate from the MBeanServerPipeline.
* Returns true if successful; false otherwise.
*/
public boolean remove(MBeanServerForwarderDelegate filter);
}
|
OpenLiberty/open-liberty
|
dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/boot/jmx/service/MBeanServerPipeline.java
|
Java
|
epl-1.0
| 1,349
|
/*
* SupportPac MS0S
* (c) Copyright IBM Corp. 2007. All rights reserved.
*
* Created on Jan 29, 2007
*
*/
package com.ibm.mq.explorer.ms0s.mqscscripts.pages;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import com.ibm.mq.explorer.ui.extensions.ContentPage;
import com.ibm.mq.explorer.ui.extensions.IContentPageFactory;
/**
* @author Jeff Lowrey
*/
/**
* <p>
* A very basic factory. Minimal code is required here.
*
**/
public class FileContentPageFactory implements IContentPageFactory {
FileNodeTreeContentPage myPage = null;
/*
* <p>
* standard getPageId method that returns the class name.
*/
public String getPageId() {
return "com.ibm.mq.explorer.ms0s.mqscscripts.fileNodeTreeContentPage";
}
/*
* (non-Javadoc)
*
* @see com.ibm.mq.explorer.ui.extensions.IContentPageFactory#makePage(org.eclipse.swt.widgets.Composite)
*/
public ContentPage makePage(Composite arg0) {
if (myPage == null)
myPage = new FileNodeTreeContentPage(arg0, SWT.NONE);
return myPage;
}
}
|
ibm-messaging/mq-mqsc-editor-plugin
|
com.ibm.mq.explorer.ms0s.mqscscripts/src/com/ibm/mq/explorer/ms0s/mqscscripts/pages/FileContentPageFactory.java
|
Java
|
epl-1.0
| 1,114
|
package p;
interface I {
default strictfp void m() {
}
}
abstract class A implements I {
}
|
khatchad/Migrate-Skeletal-Implementation-to-Interface-Refactoring
|
edu.cuny.citytech.defaultrefactoring.tests/resources/MigrateSkeletalImplementationToInterface/testStrictFPMethod/out/A.java
|
Java
|
epl-1.0
| 94
|
#!/usr/bin/env python3
# This is a simple command line script that can be used to backup the
# TACTIC database. It is independent of TACTIC, so can be run on
# servers where TACTIC is not install with the database.
import datetime
import os
import time
import subprocess
import tacticenv
from pyasm.common import Environment
from pyasm.security import Batch
# Location of zip executable
#ZIP_EXE = "C:\\Users\\user\\Documents\\backups\\7za920\\7za.exe"
ZIP_EXE = "zip"
# Location of all back-up types
BACKUP_DIR = "/spt/tactic/tactic_temp/"
# Locations of different backup types
DB_DIR = "backup_db"
PROJECT_DIR = "backup_tactic"
ASSETS_DIR = "backup_assets"
# Location of TACTIC src code
TACTIC_DIR = "/spt/tactic/tactic/"
class DatabaseBackup(object):
def execute(my):
base_dir = "%s%s" % (BACKUP_DIR, DB_DIR)
import datetime
now = datetime.datetime.now()
date = now.strftime("%Y%m%d_%H%M")
file_name = 'tacticDatabase_%s.sql' % date
path = "%s/%s" % (base_dir, file_name)
print("Backing up database to: [%s]" % path)
# Check if base_dir is exists and writable.
if not os.path.exists(base_dir):
os.mkdir(base_dir)
# Create backup, and if successful, prune old
# backups.
try:
cmd = 'pg_dumpall -U postgres -c > %s' % path
os.system(cmd)
except Exception as e:
print("Could not run database backup: %s" % e)
else:
cmd = PruneBackup()
cmd.execute(base_dir, 30)
#cmd = 'gzip -f %s' % path
#os.system(cmd)
class ProjectBackup(object):
def execute(my):
base_dir = "%s%s" % (BACKUP_DIR, PROJECT_DIR)
zip_exe = ZIP_EXE
now = datetime.datetime.now()
date = now.strftime("%Y%m%d_%H%M")
file_path = '%s/tactic_%s.zip' % (base_dir, date)
# Check if base_dir is exists and writable.
if not os.path.exists(base_dir):
os.mkdir(base_dir)
# Create backup, and if successful, prune old
# backups.
try:
subprocess.call([zip_exe, "-r", file_path, TACTIC_DIR])
except Exception as e:
print("Could not zip project directory. %s" % e)
else:
cmd = PruneBackup()
cmd.execute(base_dir, 1)
class AssetsBackup(object):
def execute(my):
base_dir = "%s%s" % (BACKUP_DIR, ASSETS_DIR)
asset_dir = Environment.get_asset_dir()
zip_exe = ZIP_EXE
now = datetime.datetime.now()
date = now.strftime("%Y%m%d_%H%M")
file_path = '%s/assets_%s.zip' % (base_dir, date)
# Check if base_dir is exists and writable.
if not os.path.exists(base_dir):
os.mkdir(base_dir)
# Create backup, and if successful, prune old
# backups.
try:
subprocess.call([zip_exe, "-r", file_path, asset_dir])
except Exception as e:
print("Could not zip assets directory: %s" % e)
else:
cmd = PruneBackup()
cmd.execute(base_dir, 3)
class PruneBackup(object):
def execute(my, directory, days):
'''Removes files in directory older than specified days.'''
dir = directory
print("Pruning backup files older than [%s] days" % days)
import datetime
today = datetime.datetime.today()
files = os.listdir(dir)
for file in files:
path = "%s/%s" % (dir, file)
(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(path)
ctime = datetime.datetime.fromtimestamp(ctime)
if today - ctime > datetime.timedelta(days=days):
os.unlink(path)
if __name__ == '__main__':
'''
# TODO
os.system("vacuumdb -U postgres --all --analyze")
'''
Batch()
cmd = DatabaseBackup()
cmd.execute()
cmd = AssetsBackup()
cmd.execute()
cmd = ProjectBackup()
#cmd.execute()
|
Southpaw-TACTIC/TACTIC
|
src/install/backup/tactic_backup.py
|
Python
|
epl-1.0
| 4,220
|
"""A library of helper functions for the CherryPy test suite."""
import datetime
import io
import logging
import os
import re
import subprocess
import sys
import time
import unittest
import warnings
import portend
import pytest
import six
from cheroot.test import webtest
import cherrypy
from cherrypy._cpcompat import text_or_bytes, HTTPSConnection, ntob
from cherrypy.lib import httputil
from cherrypy.lib import gctools
log = logging.getLogger(__name__)
thisdir = os.path.abspath(os.path.dirname(__file__))
serverpem = os.path.join(os.getcwd(), thisdir, 'test.pem')
class Supervisor(object):
"""Base class for modeling and controlling servers during testing."""
def __init__(self, **kwargs):
for k, v in kwargs.items():
if k == 'port':
setattr(self, k, int(v))
setattr(self, k, v)
def log_to_stderr(msg, level):
return sys.stderr.write(msg + os.linesep)
class LocalSupervisor(Supervisor):
"""Base class for modeling/controlling servers which run in the same
process.
When the server side runs in a different process, start/stop can dump all
state between each test module easily. When the server side runs in the
same process as the client, however, we have to do a bit more work to
ensure config and mounted apps are reset between tests.
"""
using_apache = False
using_wsgi = False
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
cherrypy.server.httpserver = self.httpserver_class
# This is perhaps the wrong place for this call but this is the only
# place that i've found so far that I KNOW is early enough to set this.
cherrypy.config.update({'log.screen': False})
engine = cherrypy.engine
if hasattr(engine, 'signal_handler'):
engine.signal_handler.subscribe()
if hasattr(engine, 'console_control_handler'):
engine.console_control_handler.subscribe()
def start(self, modulename=None):
"""Load and start the HTTP server."""
if modulename:
# Unhook httpserver so cherrypy.server.start() creates a new
# one (with config from setup_server, if declared).
cherrypy.server.httpserver = None
cherrypy.engine.start()
self.sync_apps()
def sync_apps(self):
"""Tell the server about any apps which the setup functions mounted."""
pass
def stop(self):
td = getattr(self, 'teardown', None)
if td:
td()
cherrypy.engine.exit()
servers_copy = list(six.iteritems(getattr(cherrypy, 'servers', {})))
for name, server in servers_copy:
server.unsubscribe()
del cherrypy.servers[name]
class NativeServerSupervisor(LocalSupervisor):
"""Server supervisor for the builtin HTTP server."""
httpserver_class = 'cherrypy._cpnative_server.CPHTTPServer'
using_apache = False
using_wsgi = False
def __str__(self):
return 'Builtin HTTP Server on %s:%s' % (self.host, self.port)
class LocalWSGISupervisor(LocalSupervisor):
"""Server supervisor for the builtin WSGI server."""
httpserver_class = 'cherrypy._cpwsgi_server.CPWSGIServer'
using_apache = False
using_wsgi = True
def __str__(self):
return 'Builtin WSGI Server on %s:%s' % (self.host, self.port)
def sync_apps(self):
"""Hook a new WSGI app into the origin server."""
cherrypy.server.httpserver.wsgi_app = self.get_app()
def get_app(self, app=None):
"""Obtain a new (decorated) WSGI app to hook into the origin server."""
if app is None:
app = cherrypy.tree
if self.validate:
try:
from wsgiref import validate
except ImportError:
warnings.warn(
'Error importing wsgiref. The validator will not run.')
else:
# wraps the app in the validator
app = validate.validator(app)
return app
def get_cpmodpy_supervisor(**options):
from cherrypy.test import modpy
sup = modpy.ModPythonSupervisor(**options)
sup.template = modpy.conf_cpmodpy
return sup
def get_modpygw_supervisor(**options):
from cherrypy.test import modpy
sup = modpy.ModPythonSupervisor(**options)
sup.template = modpy.conf_modpython_gateway
sup.using_wsgi = True
return sup
def get_modwsgi_supervisor(**options):
from cherrypy.test import modwsgi
return modwsgi.ModWSGISupervisor(**options)
def get_modfcgid_supervisor(**options):
from cherrypy.test import modfcgid
return modfcgid.ModFCGISupervisor(**options)
def get_modfastcgi_supervisor(**options):
from cherrypy.test import modfastcgi
return modfastcgi.ModFCGISupervisor(**options)
def get_wsgi_u_supervisor(**options):
cherrypy.server.wsgi_version = ('u', 0)
return LocalWSGISupervisor(**options)
class CPWebCase(webtest.WebCase):
script_name = ''
scheme = 'http'
available_servers = {'wsgi': LocalWSGISupervisor,
'wsgi_u': get_wsgi_u_supervisor,
'native': NativeServerSupervisor,
'cpmodpy': get_cpmodpy_supervisor,
'modpygw': get_modpygw_supervisor,
'modwsgi': get_modwsgi_supervisor,
'modfcgid': get_modfcgid_supervisor,
'modfastcgi': get_modfastcgi_supervisor,
}
default_server = 'wsgi'
@classmethod
def _setup_server(cls, supervisor, conf):
v = sys.version.split()[0]
log.info('Python version used to run this test script: %s' % v)
log.info('CherryPy version: %s' % cherrypy.__version__)
if supervisor.scheme == 'https':
ssl = ' (ssl)'
else:
ssl = ''
log.info('HTTP server version: %s%s' % (supervisor.protocol, ssl))
log.info('PID: %s' % os.getpid())
cherrypy.server.using_apache = supervisor.using_apache
cherrypy.server.using_wsgi = supervisor.using_wsgi
if sys.platform[:4] == 'java':
cherrypy.config.update({'server.nodelay': False})
if isinstance(conf, text_or_bytes):
parser = cherrypy.lib.reprconf.Parser()
conf = parser.dict_from_file(conf).get('global', {})
else:
conf = conf or {}
baseconf = conf.copy()
baseconf.update({'server.socket_host': supervisor.host,
'server.socket_port': supervisor.port,
'server.protocol_version': supervisor.protocol,
'environment': 'test_suite',
})
if supervisor.scheme == 'https':
# baseconf['server.ssl_module'] = 'builtin'
baseconf['server.ssl_certificate'] = serverpem
baseconf['server.ssl_private_key'] = serverpem
# helper must be imported lazily so the coverage tool
# can run against module-level statements within cherrypy.
# Also, we have to do "from cherrypy.test import helper",
# exactly like each test module does, because a relative import
# would stick a second instance of webtest in sys.modules,
# and we wouldn't be able to globally override the port anymore.
if supervisor.scheme == 'https':
webtest.WebCase.HTTP_CONN = HTTPSConnection
return baseconf
@classmethod
def setup_class(cls):
''
# Creates a server
conf = {
'scheme': 'http',
'protocol': 'HTTP/1.1',
'port': 54583,
'host': '127.0.0.1',
'validate': False,
'server': 'wsgi',
}
supervisor_factory = cls.available_servers.get(
conf.get('server', 'wsgi'))
if supervisor_factory is None:
raise RuntimeError('Unknown server in config: %s' % conf['server'])
supervisor = supervisor_factory(**conf)
# Copied from "run_test_suite"
cherrypy.config.reset()
baseconf = cls._setup_server(supervisor, conf)
cherrypy.config.update(baseconf)
setup_client()
if hasattr(cls, 'setup_server'):
# Clear the cherrypy tree and clear the wsgi server so that
# it can be updated with the new root
cherrypy.tree = cherrypy._cptree.Tree()
cherrypy.server.httpserver = None
cls.setup_server()
# Add a resource for verifying there are no refleaks
# to *every* test class.
cherrypy.tree.mount(gctools.GCRoot(), '/gc')
cls.do_gc_test = True
supervisor.start(cls.__module__)
cls.supervisor = supervisor
@classmethod
def teardown_class(cls):
''
if hasattr(cls, 'setup_server'):
cls.supervisor.stop()
do_gc_test = False
def test_gc(self):
if not self.do_gc_test:
return
self.getPage('/gc/stats')
try:
self.assertBody('Statistics:')
except Exception:
'Failures occur intermittently. See #1420'
def prefix(self):
return self.script_name.rstrip('/')
def base(self):
if ((self.scheme == 'http' and self.PORT == 80) or
(self.scheme == 'https' and self.PORT == 443)):
port = ''
else:
port = ':%s' % self.PORT
return '%s://%s%s%s' % (self.scheme, self.HOST, port,
self.script_name.rstrip('/'))
def exit(self):
sys.exit()
def getPage(self, url, headers=None, method='GET', body=None,
protocol=None, raise_subcls=None):
"""Open the url. Return status, headers, body.
`raise_subcls` must be a tuple with the exceptions classes
or a single exception class that are not going to be considered
a socket.error regardless that they were are subclass of a
socket.error and therefore not considered for a connection retry.
"""
if self.script_name:
url = httputil.urljoin(self.script_name, url)
return webtest.WebCase.getPage(self, url, headers, method, body,
protocol, raise_subcls)
def skip(self, msg='skipped '):
pytest.skip(msg)
def assertErrorPage(self, status, message=None, pattern=''):
"""Compare the response body with a built in error page.
The function will optionally look for the regexp pattern,
within the exception embedded in the error page."""
# This will never contain a traceback
page = cherrypy._cperror.get_error_page(status, message=message)
# First, test the response body without checking the traceback.
# Stick a match-all group (.*) in to grab the traceback.
def esc(text):
return re.escape(ntob(text))
epage = re.escape(page)
epage = epage.replace(
esc('<pre id="traceback"></pre>'),
esc('<pre id="traceback">') + b'(.*)' + esc('</pre>'))
m = re.match(epage, self.body, re.DOTALL)
if not m:
self._handlewebError(
'Error page does not match; expected:\n' + page)
return
# Now test the pattern against the traceback
if pattern is None:
# Special-case None to mean that there should be *no* traceback.
if m and m.group(1):
self._handlewebError('Error page contains traceback')
else:
if (m is None) or (
not re.search(ntob(re.escape(pattern), self.encoding),
m.group(1))):
msg = 'Error page does not contain %s in traceback'
self._handlewebError(msg % repr(pattern))
date_tolerance = 2
def assertEqualDates(self, dt1, dt2, seconds=None):
"""Assert abs(dt1 - dt2) is within Y seconds."""
if seconds is None:
seconds = self.date_tolerance
if dt1 > dt2:
diff = dt1 - dt2
else:
diff = dt2 - dt1
if not diff < datetime.timedelta(seconds=seconds):
raise AssertionError('%r and %r are not within %r seconds.' %
(dt1, dt2, seconds))
def _test_method_sorter(_, x, y):
"""Monkeypatch the test sorter to always run test_gc last in each suite."""
if x == 'test_gc':
return 1
if y == 'test_gc':
return -1
if x > y:
return 1
if x < y:
return -1
return 0
unittest.TestLoader.sortTestMethodsUsing = _test_method_sorter
def setup_client():
"""Set up the WebCase classes to match the server's socket settings."""
webtest.WebCase.PORT = cherrypy.server.socket_port
webtest.WebCase.HOST = cherrypy.server.socket_host
if cherrypy.server.ssl_certificate:
CPWebCase.scheme = 'https'
# --------------------------- Spawning helpers --------------------------- #
class CPProcess(object):
pid_file = os.path.join(thisdir, 'test.pid')
config_file = os.path.join(thisdir, 'test.conf')
config_template = """[global]
server.socket_host: '%(host)s'
server.socket_port: %(port)s
checker.on: False
log.screen: False
log.error_file: r'%(error_log)s'
log.access_file: r'%(access_log)s'
%(ssl)s
%(extra)s
"""
error_log = os.path.join(thisdir, 'test.error.log')
access_log = os.path.join(thisdir, 'test.access.log')
def __init__(self, wait=False, daemonize=False, ssl=False,
socket_host=None, socket_port=None):
self.wait = wait
self.daemonize = daemonize
self.ssl = ssl
self.host = socket_host or cherrypy.server.socket_host
self.port = socket_port or cherrypy.server.socket_port
def write_conf(self, extra=''):
if self.ssl:
serverpem = os.path.join(thisdir, 'test.pem')
ssl = """
server.ssl_certificate: r'%s'
server.ssl_private_key: r'%s'
""" % (serverpem, serverpem)
else:
ssl = ''
conf = self.config_template % {
'host': self.host,
'port': self.port,
'error_log': self.error_log,
'access_log': self.access_log,
'ssl': ssl,
'extra': extra,
}
with io.open(self.config_file, 'w', encoding='utf-8') as f:
f.write(six.text_type(conf))
def start(self, imports=None):
"""Start cherryd in a subprocess."""
portend.free(self.host, self.port, timeout=1)
args = [
'-m',
'cherrypy',
'-c', self.config_file,
'-p', self.pid_file,
]
r"""
Command for running cherryd server with autoreload enabled
Using
```
['-c',
"__requires__ = 'CherryPy'; \
import pkg_resources, re, sys; \
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]); \
sys.exit(\
pkg_resources.load_entry_point(\
'CherryPy', 'console_scripts', 'cherryd')())"]
```
doesn't work as it's impossible to reconstruct the `-c`'s contents.
Ref: https://github.com/cherrypy/cherrypy/issues/1545
"""
if not isinstance(imports, (list, tuple)):
imports = [imports]
for i in imports:
if i:
args.append('-i')
args.append(i)
if self.daemonize:
args.append('-d')
env = os.environ.copy()
# Make sure we import the cherrypy package in which this module is
# defined.
grandparentdir = os.path.abspath(os.path.join(thisdir, '..', '..'))
if env.get('PYTHONPATH', ''):
env['PYTHONPATH'] = os.pathsep.join(
(grandparentdir, env['PYTHONPATH']))
else:
env['PYTHONPATH'] = grandparentdir
self._proc = subprocess.Popen([sys.executable] + args, env=env)
if self.wait:
self.exit_code = self._proc.wait()
else:
portend.occupied(self.host, self.port, timeout=5)
# Give the engine a wee bit more time to finish STARTING
if self.daemonize:
time.sleep(2)
else:
time.sleep(1)
def get_pid(self):
if self.daemonize:
return int(open(self.pid_file, 'rb').read())
return self._proc.pid
def join(self):
"""Wait for the process to exit."""
if self.daemonize:
return self._join_daemon()
self._proc.wait()
def _join_daemon(self):
try:
try:
# Mac, UNIX
os.wait()
except AttributeError:
# Windows
try:
pid = self.get_pid()
except IOError:
# Assume the subprocess deleted the pidfile on shutdown.
pass
else:
os.waitpid(pid, 0)
except OSError:
x = sys.exc_info()[1]
if x.args != (10, 'No child processes'):
raise
|
Southpaw-TACTIC/TACTIC
|
3rd_party/python2/site-packages/cherrypy/test/helper.py
|
Python
|
epl-1.0
| 17,316
|
---
name: Release📦
about: Create new release issue for Eclipse Che
title: ''
labels: 'kind/release'
assignees: ''
---
### List of pending issues / PRs
* [ ] description #xxx https://github.com/eclipse/che/issues/xxx
### Release status
The following will be released via [che-release](https://github.com/eclipse/che-release/blob/master/cico_release.sh) according to a series of phases:
1. [ ] che-machine-exec, che-theia, che-devfile-registry, che-dashboard, devworkspace-operator, jwtproxy, kubernetes image puller
2. [ ] che-plugin-registry (once che-theia and machine-exec are done)
3. [ ] che-parent and che server
4. [ ] devworkspace-che-operator
5. [ ] che-operator
Each phase will [send a Mattermost notification to the Eclipse Che releases channel](https://mattermost.eclipse.org/eclipse/channels/eclipse-che-releases).
Then, these steps will be done, once the above projects are released and PRs are merged:
- [ ] [chectl](https://github.com/che-incubator/chectl/actions/workflows/release-stable-PRs.yml) _(depends on che-operator)_
- [ ] [Che community operator PRs](https://github.com/operator-framework/community-operators/pulls?q=%22Update+eclipse-che+operator%22+is%3Aopen) _(depends on che-operator)_
- [ ] [che-docs PR](https://github.com/eclipse/che-docs/pulls/che-bot) _(depends on che-operator)_
If this is a .0 release:
- [ ] complete current milestone
- [ ] move incomplete *deferred* issues to backlog
- [ ] move incomplete *WIP* issues to next milestone
- [ ] close completed issues
- [ ] close milestone
| Process <sup>[1]</sup> | Script | Action | Container(s) + Artifact(s) |
| --- | --- | --- | --- |
| [che-release](https://github.com/eclipse/che-release/blob/master/RELEASE.md) | [cico_release.sh](https://github.com/eclipse/che-release/blob/master/cico_release.sh) | [Action](https://github.com/eclipse/che-release/actions?query=workflow%3A%22Release+-+Orchestrate+Overall+Release+Phases%22) | n/a |
| [che-theia](https://github.com/eclipse/che-theia/blob/master/RELEASE.md) | [make-release.sh](https://github.com/eclipse/che-theia/blob/master/make-release.sh) | [Action](https://github.com/eclipse/che-theia/actions?query=workflow%3A%22Release+Che+Theia%22) | [`eclipse/che-theia`](https://quay.io/eclipse/che-theia) |
| [che-machine-exec](https://github.com/eclipse-che/che-machine-exec/blob/master/RELEASE.md) | [make-release.sh](https://github.com/eclipse-che/che-machine-exec/blob/master/make-release.sh) | [Action](https://github.com/eclipse-che/che-machine-exec/actions?query=workflow%3A%22Release+Che+Machine+Exec%22) | [`eclipse/che-machine-exec`](https://quay.io/eclipse/che-machine-exec)|
| [che-devfile-registry](https://github.com/eclipse/che-devfile-registry/blob/master/RELEASE.md) | [make-release.sh](https://github.com/eclipse/che-devfile-registry/blob/master/make-release.sh) | [Action](https://github.com/eclipse/che-devfile-registry/actions?query=workflow%3A%22Release+Che+Devfile+Registry%22) | [`eclipse/che-devfile-registry`](https://quay.io/eclipse/che-devfile-registry)|
| [che-plugin-registry](https://github.com/eclipse/che-plugin-registry/blob/master/RELEASE.md) | [make-release.sh](https://github.com/eclipse/che-plugin-registry/blob/master/make-release.sh) | [Action](https://github.com/eclipse/che-plugin-registry/actions?query=workflow%3A%22Release+Che+Plugin+Registry%22) | [`eclipse/che-plugin-registry`](https://quay.io/eclipse/che-plugin-registry)|
| [che-parent](https://github.com/eclipse/che-parent/blob/master/RELEASE.md) | [make-release.sh](https://github.com/eclipse/che-parent/blob/master/make-release.sh) | [Action](https://github.com/eclipse/che/actions?query=workflow%3A%22Release+Che+Server%22) | [che-server](https://search.maven.org/search?q=a:che-server) <sup>[2]</sup> |
| [che-dashboard](https://github.com/eclipse-che/che-dashboard/blob/main/RELEASE.md) | [make-release.sh](https://github.com/eclipse-che/che-dashboard/blob/master/make-release.sh) | [Action](https://github.com/eclipse-che/che-dashboard/actions?query=workflow%3A%22Release+Che+Dashboard%22) | [`che-dashboard`](https://quay.io/repository/eclipse/che-dashboard?tag=next&tab=tags) |
| [che](https://github.com/eclipse/che/blob/master/RELEASE.md) | [make-release.sh](https://github.com/eclipse/che/blob/master/make-release.sh) | [Action](https://github.com/eclipse/che/actions?query=workflow%3A%22Release+Che+Server%22) | [`eclipse/che-server`](https://quay.io/eclipse/che-server),<br/>[`eclipse/che-endpoint-watcher`](https://quay.io/eclipse/che-endpoint-watcher),<br/> [`eclipse/che-keycloak`](https://quay.io/eclipse/che-keycloak),<br/> [`eclipse/che-postgres`](https://quay.io/eclipse/che-postgres),<br/> [`eclipse/che-server`](https://quay.io/eclipse/che-server),<br/> [`eclipse/che-e2e`](https://quay.io/eclipse/che-e2e) |
| [devworkspace-operator (controller)](https://github.com/devfile/devworkspace-operator/) | [make-release.sh](https://github.com/devfile/devworkspace-operator/blob/main/make-release.sh) | [Action](https://github.com/devfile/devworkspace-operator/actions/workflows/release.yml) | [`devfile/devworkspace-controller`](https://quay.io/repository/devfile/devworkspace-controller?tab=tags)|
| [devworkspace-che-operator](https://github.com/che-incubator/devworkspace-che-operator/) | [make-release.sh](https://github.com/che-incubator/devworkspace-che-operator/blob/main/make-release.sh) | [Action](https://github.com/che-incubator/devworkspace-che-operator/actions/workflows/release.yml) | [`che-incubator/devworkspace-che-operator`](https://quay.io/repository/che-incubator/devworkspace-che-operator?tab=tags)|
| [che-operator](https://github.com/eclipse-che/che-operator/blob/master/RELEASE.md) | [make-release.sh](https://github.com/eclipse-che/che-operator/blob/master/make-release.sh) | [Action](https://github.com/eclipse-che/che-operator/actions?query=workflow%3A%22Release+Che+Operator%22) | [`eclipse/che-operator`](https://quay.io/eclipse/che-operator)|
| [chectl](https://github.com/che-incubator/chectl/blob/master/RELEASE.md) | [make-release.sh](https://github.com/che-incubator/chectl/blob/master/make-release.sh) | [Action](https://github.com/che-incubator/chectl/actions) | [chectl releases](https://github.com/che-incubator/chectl/releases)
<sup>[1]</sup> Overall process owner: @mkuznyetsov
|
codenvy/che
|
.github/ISSUE_TEMPLATE/release.md
|
Markdown
|
epl-1.0
| 6,302
|
/*******************************************************************************
* Copyright (c) 2014, 2014 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Bruno Medeiros - initial API and implementation
*******************************************************************************/
package melnorme.lang.ide.core.utils.prefs;
import static melnorme.utilbox.core.Assert.AssertNamespace.assertNotNull;
import static melnorme.utilbox.core.CoreUtil.array;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ProjectScope;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.preferences.DefaultScope;
import org.eclipse.core.runtime.preferences.IPreferencesService;
import org.eclipse.core.runtime.preferences.IScopeContext;
import org.eclipse.core.runtime.preferences.InstanceScope;
public class PreferencesLookupHelper implements IPreferencesAccess {
public final String qualifier;
protected final IScopeContext[] contexts;
public PreferencesLookupHelper(String qualifier) {
this(qualifier, null);
}
public PreferencesLookupHelper(String qualifier, IProject project) {
this.qualifier = qualifier;
if(project != null) {
contexts = array(new ProjectScope(project), InstanceScope.INSTANCE, DefaultScope.INSTANCE);
} else {
contexts = array(InstanceScope.INSTANCE, DefaultScope.INSTANCE);
}
}
protected static IPreferencesService preferences() {
return Platform.getPreferencesService();
}
protected String assertKeyHasDefault(String key) {
return assertNotNull(DefaultScope.INSTANCE.getNode(qualifier).get(key, null));
}
@Override
public String getString(String key) {
assertKeyHasDefault(key);
return getString(key, "");
}
@Override
public int getInt(String key) {
assertKeyHasDefault(key);
return getInt(key, 0);
}
@Override
public boolean getBoolean(String key) {
assertKeyHasDefault(key);
return getBoolean(key, false);
}
public String getString(String key, String defaultValue) {
return preferences().getString(qualifier, key, defaultValue, contexts);
}
public int getInt(String key, int defaultValue) {
return preferences().getInt(qualifier, key, defaultValue, contexts);
}
public boolean getBoolean(String key, boolean defaultValue) {
return preferences().getBoolean(qualifier, key, defaultValue, contexts);
}
}
|
fredyw/goclipse
|
plugin_ide.core/src-lang/melnorme/lang/ide/core/utils/prefs/PreferencesLookupHelper.java
|
Java
|
epl-1.0
| 2,690
|
//*****************************************************************************
//
//! \file xdebug.h
//! \brief Drivers for assisting debug of the peripheral library.
//! \version V2.2.1.0
//! \date 11/20/2011
//! \author CooCox
//! \copy
//!
//! Copyright (c) 2011, CooCox
//! All rights reserved.
//!
//! 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.
//! * Neither the name of the <ORGANIZATION> nor the names of its
//! contributors may be used to endorse or promote products derived
//! from this software without specific prior written permission.
//!
//! 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.
//
//*****************************************************************************
//*****************************************************************************
//
//! \brief Error Function to be called when assert runs false.
//!
//! \param pcFilename is the current file name.
//! \param ulLine is the current line number.
//!
//! This is just an default error handler function, Users should implement
//! this function with your own way when debug.
//!
//! \note This is only used when doing a \b xDEBUG build.
//!
//! \return None.
//
//*****************************************************************************
#ifdef xDEBUG
void __xerror__(char *pcFilename, unsigned long ulLine)
{
//
// Add your own error handling
//
while(1)
{
}
}
#endif
|
sangwook236/general-development-and-testing
|
hw_dev/processor/arm/ext/test/stm32_emide/CoX_Peripheral/src/xdebug.c
|
C
|
gpl-2.0
| 2,699
|
/* Copyright (c) 2012-2014, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/of.h>
#include <linux/module.h>
#include <linux/workqueue.h>
#include <linux/delay.h>
#include <linux/types.h>
#include <linux/list.h>
#include <linux/ioctl.h>
#include <linux/spinlock.h>
#include <linux/proc_fs.h>
#include <linux/atomic.h>
#include <linux/wait.h>
#include <linux/videodev2.h>
#include <linux/msm_ion.h>
#include <linux/iommu.h>
#include <linux/platform_device.h>
#include <media/v4l2-fh.h>
#include "camera.h"
#include "msm.h"
#include "msm_vb2.h"
#define fh_to_private(__fh) \
container_of(__fh, struct camera_v4l2_private, fh)
static DEFINE_MUTEX(v4l2_sync_lock); /*LGE_CHANGE, add the mutex to fix the poison overwritten, 2015-03-31, freeso.kim@lge.com*/
struct camera_v4l2_private {
struct v4l2_fh fh;
unsigned int stream_id;
unsigned int is_vb2_valid; /*0 if no vb2 buffers on stream, else 1*/
struct vb2_queue vb2_q;
};
static void camera_pack_event(struct file *filep, int evt_id,
int command, int value, struct v4l2_event *event)
{
struct msm_v4l2_event_data *event_data =
(struct msm_v4l2_event_data *)&event->u.data[0];
struct msm_video_device *pvdev = video_drvdata(filep);
struct camera_v4l2_private *sp = fh_to_private(filep->private_data);
/* always MSM_CAMERA_V4L2_EVENT_TYPE */
event->type = MSM_CAMERA_V4L2_EVENT_TYPE;
event->id = evt_id;
event_data->command = command;
event_data->session_id = pvdev->vdev->num;
event_data->stream_id = sp->stream_id;
event_data->arg_value = value;
}
static int camera_check_event_status(struct v4l2_event *event)
{
struct msm_v4l2_event_data *event_data =
(struct msm_v4l2_event_data *)&event->u.data[0];
if (event_data->status > MSM_CAMERA_ERR_EVT_BASE) {
pr_err("%s : event_data status out of bounds\n",
__func__);
pr_err("%s : Line %d event_data->status 0X%x\n",
__func__, __LINE__, event_data->status);
switch (event_data->status) {
case MSM_CAMERA_ERR_CMD_FAIL:
case MSM_CAMERA_ERR_MAPPING:
return -EFAULT;
case MSM_CAMERA_ERR_DEVICE_BUSY:
return -EBUSY;
default:
return -EFAULT;
}
}
return 0;
}
static int camera_v4l2_querycap(struct file *filep, void *fh,
struct v4l2_capability *cap)
{
int rc;
struct v4l2_event event;
/* can use cap->driver to make differentiation */
camera_pack_event(filep, MSM_CAMERA_GET_PARM,
MSM_CAMERA_PRIV_QUERY_CAP, -1, &event);
rc = msm_post_event(&event, MSM_POST_EVT_TIMEOUT);
if (rc < 0)
return rc;
rc = camera_check_event_status(&event);
return rc;
}
static int camera_v4l2_s_crop(struct file *filep, void *fh,
const struct v4l2_crop *crop)
{
int rc = 0;
struct v4l2_event event;
if (crop->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
camera_pack_event(filep, MSM_CAMERA_SET_PARM,
MSM_CAMERA_PRIV_S_CROP, -1, &event);
rc = msm_post_event(&event, MSM_POST_EVT_TIMEOUT);
if (rc < 0)
return rc;
rc = camera_check_event_status(&event);
}
return rc;
}
static int camera_v4l2_g_crop(struct file *filep, void *fh,
struct v4l2_crop *crop)
{
int rc = 0;
struct v4l2_event event;
if (crop->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
camera_pack_event(filep, MSM_CAMERA_GET_PARM,
MSM_CAMERA_PRIV_G_CROP, -1, &event);
rc = msm_post_event(&event, MSM_POST_EVT_TIMEOUT);
if (rc < 0)
return rc;
rc = camera_check_event_status(&event);
}
return rc;
}
static int camera_v4l2_queryctrl(struct file *filep, void *fh,
struct v4l2_queryctrl *ctrl)
{
int rc = 0;
struct v4l2_event event;
if (ctrl->type == V4L2_CTRL_TYPE_MENU) {
camera_pack_event(filep, MSM_CAMERA_GET_PARM,
ctrl->id, -1, &event);
rc = msm_post_event(&event, MSM_POST_EVT_TIMEOUT);
if (rc < 0)
return rc;
rc = camera_check_event_status(&event);
}
return rc;
}
static int camera_v4l2_g_ctrl(struct file *filep, void *fh,
struct v4l2_control *ctrl)
{
int rc = 0;
struct v4l2_event event;
if (ctrl->id >= V4L2_CID_PRIVATE_BASE) {
camera_pack_event(filep, MSM_CAMERA_GET_PARM, ctrl->id, -1,
&event);
rc = msm_post_event(&event, MSM_POST_EVT_TIMEOUT);
if (rc < 0)
return rc;
rc = camera_check_event_status(&event);
}
return rc;
}
static int camera_v4l2_s_ctrl(struct file *filep, void *fh,
struct v4l2_control *ctrl)
{
int rc = 0;
struct v4l2_event event;
struct msm_v4l2_event_data *event_data;
if (ctrl->id >= V4L2_CID_PRIVATE_BASE) {
camera_pack_event(filep, MSM_CAMERA_SET_PARM, ctrl->id,
ctrl->value, &event);
rc = msm_post_event(&event, MSM_POST_EVT_TIMEOUT);
if (rc < 0)
return rc;
event_data = (struct msm_v4l2_event_data *)event.u.data;
ctrl->value = event_data->ret_value;
rc = camera_check_event_status(&event);
}
return rc;
}
static int camera_v4l2_reqbufs(struct file *filep, void *fh,
struct v4l2_requestbuffers *req)
{
int ret;
struct msm_session *session;
struct camera_v4l2_private *sp = fh_to_private(fh);
struct msm_video_device *pvdev = video_drvdata(filep);
unsigned int session_id = pvdev->vdev->num;
session = msm_session_find(session_id);
if (WARN_ON(!session))
return -EIO;
mutex_lock(&session->lock);
ret = vb2_reqbufs(&sp->vb2_q, req);
mutex_unlock(&session->lock);
return ret;
}
static int camera_v4l2_querybuf(struct file *filep, void *fh,
struct v4l2_buffer *pb)
{
return 0;
}
static int camera_v4l2_qbuf(struct file *filep, void *fh,
struct v4l2_buffer *pb)
{
int ret;
struct msm_session *session;
struct camera_v4l2_private *sp = fh_to_private(fh);
struct msm_video_device *pvdev = video_drvdata(filep);
unsigned int session_id = pvdev->vdev->num;
session = msm_session_find(session_id);
if (WARN_ON(!session))
return -EIO;
mutex_lock(&session->lock);
ret = vb2_qbuf(&sp->vb2_q, pb);
mutex_unlock(&session->lock);
return ret;
}
static int camera_v4l2_dqbuf(struct file *filep, void *fh,
struct v4l2_buffer *pb)
{
int ret;
struct msm_session *session;
struct camera_v4l2_private *sp = fh_to_private(fh);
struct msm_video_device *pvdev = video_drvdata(filep);
unsigned int session_id = pvdev->vdev->num;
session = msm_session_find(session_id);
if (WARN_ON(!session))
return -EIO;
mutex_lock(&session->lock);
ret = vb2_dqbuf(&sp->vb2_q, pb, filep->f_flags & O_NONBLOCK);
mutex_unlock(&session->lock);
return ret;
}
static int camera_v4l2_streamon(struct file *filep, void *fh,
enum v4l2_buf_type buf_type)
{
struct v4l2_event event;
int rc;
struct camera_v4l2_private *sp = fh_to_private(fh);
rc = vb2_streamon(&sp->vb2_q, buf_type);
camera_pack_event(filep, MSM_CAMERA_SET_PARM,
MSM_CAMERA_PRIV_STREAM_ON, -1, &event);
rc = msm_post_event(&event, MSM_POST_EVT_TIMEOUT);
if (rc < 0)
return rc;
rc = camera_check_event_status(&event);
return rc;
}
static int camera_v4l2_streamoff(struct file *filep, void *fh,
enum v4l2_buf_type buf_type)
{
struct v4l2_event event;
int rc;
struct camera_v4l2_private *sp = fh_to_private(fh);
camera_pack_event(filep, MSM_CAMERA_SET_PARM,
MSM_CAMERA_PRIV_STREAM_OFF, -1, &event);
rc = msm_post_event(&event, MSM_POST_EVT_TIMEOUT);
if (rc < 0)
return rc;
rc = camera_check_event_status(&event);
vb2_streamoff(&sp->vb2_q, buf_type);
return rc;
}
static int camera_v4l2_g_fmt_vid_cap_mplane(struct file *filep, void *fh,
struct v4l2_format *pfmt)
{
int rc = -EINVAL;
if (pfmt->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
struct v4l2_event event;
camera_pack_event(filep, MSM_CAMERA_GET_PARM,
MSM_CAMERA_PRIV_G_FMT, -1, &event);
rc = msm_post_event(&event, MSM_POST_EVT_TIMEOUT);
if (rc < 0)
return rc;
rc = camera_check_event_status(&event);
}
return rc;
}
static int camera_v4l2_s_fmt_vid_cap_mplane(struct file *filep, void *fh,
struct v4l2_format *pfmt)
{
int rc = 0;
int i = 0;
struct v4l2_event event;
struct camera_v4l2_private *sp = fh_to_private(fh);
struct msm_v4l2_format_data *user_fmt;
if (pfmt->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
if (WARN_ON(!sp->vb2_q.drv_priv))
return -ENOMEM;
memcpy(sp->vb2_q.drv_priv, pfmt->fmt.raw_data,
sizeof(struct msm_v4l2_format_data));
user_fmt = (struct msm_v4l2_format_data *)sp->vb2_q.drv_priv;
pr_debug("%s: num planes :%c\n", __func__,
user_fmt->num_planes);
/*num_planes need to bound checked, otherwise for loop
can execute forever */
if (WARN_ON(user_fmt->num_planes > VIDEO_MAX_PLANES))
return -EINVAL;
for (i = 0; i < user_fmt->num_planes; i++)
pr_debug("%s: plane size[%d]\n", __func__,
user_fmt->plane_sizes[i]);
camera_pack_event(filep, MSM_CAMERA_SET_PARM,
MSM_CAMERA_PRIV_S_FMT, -1, &event);
rc = msm_post_event(&event, MSM_POST_EVT_TIMEOUT);
if (rc < 0)
return rc;
rc = camera_check_event_status(&event);
if (rc < 0)
return rc;
sp->is_vb2_valid = 1;
}
return rc;
}
static int camera_v4l2_try_fmt_vid_cap_mplane(struct file *filep, void *fh,
struct v4l2_format *pfmt)
{
return 0;
}
static int camera_v4l2_g_parm(struct file *filep, void *fh,
struct v4l2_streamparm *a)
{
/* TODO */
return 0;
}
static int camera_v4l2_s_parm(struct file *filep, void *fh,
struct v4l2_streamparm *parm)
{
int rc = 0;
struct v4l2_event event;
struct msm_v4l2_event_data *event_data =
(struct msm_v4l2_event_data *)&event.u.data[0];
struct camera_v4l2_private *sp = fh_to_private(fh);
camera_pack_event(filep, MSM_CAMERA_SET_PARM,
MSM_CAMERA_PRIV_NEW_STREAM, -1, &event);
rc = msm_create_stream(event_data->session_id,
event_data->stream_id, &sp->vb2_q);
if (rc < 0)
return rc;
rc = msm_post_event(&event, MSM_POST_EVT_TIMEOUT);
if (rc < 0)
goto error;
rc = camera_check_event_status(&event);
if (rc < 0)
goto error;
/* use stream_id as stream index */
parm->parm.capture.extendedmode = sp->stream_id;
return rc;
error:
msm_delete_stream(event_data->session_id,
event_data->stream_id);
return rc;
}
static int camera_v4l2_subscribe_event(struct v4l2_fh *fh,
const struct v4l2_event_subscription *sub)
{
int rc = 0;
struct camera_v4l2_private *sp = fh_to_private(fh);
rc = v4l2_event_subscribe(&sp->fh, sub, 5, NULL);
return rc;
}
static int camera_v4l2_unsubscribe_event(struct v4l2_fh *fh,
const struct v4l2_event_subscription *sub)
{
int rc = 0;
struct camera_v4l2_private *sp = fh_to_private(fh);
rc = v4l2_event_unsubscribe(&sp->fh, sub);
return rc;
}
static const struct v4l2_ioctl_ops camera_v4l2_ioctl_ops = {
.vidioc_querycap = camera_v4l2_querycap,
.vidioc_s_crop = camera_v4l2_s_crop,
.vidioc_g_crop = camera_v4l2_g_crop,
.vidioc_queryctrl = camera_v4l2_queryctrl,
.vidioc_g_ctrl = camera_v4l2_g_ctrl,
.vidioc_s_ctrl = camera_v4l2_s_ctrl,
.vidioc_reqbufs = camera_v4l2_reqbufs,
.vidioc_querybuf = camera_v4l2_querybuf,
.vidioc_qbuf = camera_v4l2_qbuf,
.vidioc_dqbuf = camera_v4l2_dqbuf,
.vidioc_streamon = camera_v4l2_streamon,
.vidioc_streamoff = camera_v4l2_streamoff,
.vidioc_g_fmt_vid_cap_mplane = camera_v4l2_g_fmt_vid_cap_mplane,
.vidioc_s_fmt_vid_cap_mplane = camera_v4l2_s_fmt_vid_cap_mplane,
.vidioc_try_fmt_vid_cap_mplane = camera_v4l2_try_fmt_vid_cap_mplane,
/* Stream type-dependent parameter ioctls */
.vidioc_g_parm = camera_v4l2_g_parm,
.vidioc_s_parm = camera_v4l2_s_parm,
/* event subscribe/unsubscribe */
.vidioc_subscribe_event = camera_v4l2_subscribe_event,
.vidioc_unsubscribe_event = camera_v4l2_unsubscribe_event,
};
static int camera_v4l2_fh_open(struct file *filep)
{
struct msm_video_device *pvdev = video_drvdata(filep);
struct camera_v4l2_private *sp;
unsigned int stream_id;
sp = kzalloc(sizeof(*sp), GFP_KERNEL);
if (!sp) {
pr_err("%s : memory not available\n", __func__);
return -ENOMEM;
}
filep->private_data = &sp->fh;
/* stream_id = open id */
stream_id = atomic_read(&pvdev->opened);
sp->stream_id = find_first_zero_bit(
(const unsigned long *)&stream_id, MSM_CAMERA_STREAM_CNT_BITS);
pr_debug("%s: Found stream_id=%d\n", __func__, sp->stream_id);
v4l2_fh_init(&sp->fh, pvdev->vdev);
v4l2_fh_add(&sp->fh);
return 0;
}
static int camera_v4l2_fh_release(struct file *filep)
{
struct camera_v4l2_private *sp = fh_to_private(filep->private_data);
if (sp) {
v4l2_fh_del(&sp->fh);
v4l2_fh_exit(&sp->fh);
}
kzfree(sp);
return 0;
}
static int camera_v4l2_vb2_q_init(struct file *filep)
{
struct camera_v4l2_private *sp = fh_to_private(filep->private_data);
struct vb2_queue *q = &sp->vb2_q;
memset(q, 0, sizeof(struct vb2_queue));
/* free up this buffer when stream is done */
q->drv_priv =
kzalloc(sizeof(struct msm_v4l2_format_data), GFP_KERNEL);
if (!q->drv_priv) {
pr_err("%s : memory not available\n", __func__);
return -ENOMEM;
}
q->mem_ops = msm_vb2_get_q_mem_ops();
q->ops = msm_vb2_get_q_ops();
/* default queue type */
q->type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
q->io_modes = VB2_USERPTR;
q->io_flags = 0;
q->buf_struct_size = sizeof(struct msm_vb2_buffer);
q->timestamp_type = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
return vb2_queue_init(q);
}
static void camera_v4l2_vb2_q_release(struct file *filep)
{
struct camera_v4l2_private *sp = filep->private_data;
kzfree(sp->vb2_q.drv_priv);
vb2_queue_release(&sp->vb2_q);
}
static int camera_v4l2_open(struct file *filep)
{
int rc = 0;
struct v4l2_event event;
struct msm_video_device *pvdev = video_drvdata(filep);
unsigned int opn_idx, idx;
BUG_ON(!pvdev);
mutex_lock(&v4l2_sync_lock);/*LGE_CHANGE, add the mutex to fix the poison overwritten, 2015-03-31, freeso.kim@lge.com*/
rc = camera_v4l2_fh_open(filep);
if (rc < 0) {
pr_err("%s : camera_v4l2_fh_open failed Line %d rc %d\n",
__func__, __LINE__, rc);
goto fh_open_fail;
}
opn_idx = atomic_read(&pvdev->opened);
idx = opn_idx;
/* every stream has a vb2 queue */
rc = camera_v4l2_vb2_q_init(filep);
if (rc < 0) {
pr_err("%s : vb2 queue init fails Line %d rc %d\n",
__func__, __LINE__, rc);
goto vb2_q_fail;
}
if (!atomic_read(&pvdev->opened)) {
pm_stay_awake(&pvdev->vdev->dev);
/* create a new session when first opened */
pr_err("%s: msm_create_session id=%d\n", __func__, pvdev->vdev->num); /*LGE_CHANGE, add the mutex to fix the poison overwritten, 2015-03-31, freeso.kim@lge.com*/
rc = msm_create_session(pvdev->vdev->num, pvdev->vdev);
if (rc < 0) {
pr_err("%s : session creation failed Line %d rc %d\n",
__func__, __LINE__, rc);
goto session_fail;
}
rc = msm_create_command_ack_q(pvdev->vdev->num,
find_first_zero_bit((const unsigned long *)&opn_idx,
MSM_CAMERA_STREAM_CNT_BITS));
if (rc < 0) {
pr_err("%s : creation of command_ack queue failed\n",
__func__);
pr_err("%s : Line %d rc %d\n", __func__, __LINE__, rc);
goto command_ack_q_fail;
}
camera_pack_event(filep, MSM_CAMERA_NEW_SESSION, 0, -1, &event);
rc = msm_post_event(&event, MSM_POST_EVT_TIMEOUT);
if (rc < 0) {
pr_err("%s : posting of NEW_SESSION event failed\n",
__func__);
pr_err("%s : Line %d rc %d\n", __func__, __LINE__, rc);
goto post_fail;
}
rc = camera_check_event_status(&event);
if (rc < 0) {
pr_err("%s : checking event status fails Line %d rc %d\n",
__func__, __LINE__, rc);
goto post_fail;
}
} else {
pr_err("%s: msm_create_command_ack_q id=%d\n", __func__, pvdev->vdev->num); /*LGE_CHANGE, add the mutex to fix the poison overwritten, 2015-03-31, freeso.kim@lge.com*/
rc = msm_create_command_ack_q(pvdev->vdev->num,
find_first_zero_bit((const unsigned long *)&opn_idx,
MSM_CAMERA_STREAM_CNT_BITS));
if (rc < 0) {
pr_err("%s : creation of command_ack queue failed Line %d rc %d\n",
__func__, __LINE__, rc);
goto session_fail;
}
}
idx |= (1 << find_first_zero_bit((const unsigned long *)&opn_idx,
MSM_CAMERA_STREAM_CNT_BITS));
atomic_cmpxchg(&pvdev->opened, opn_idx, idx);
mutex_unlock(&v4l2_sync_lock);/*LGE_CHANGE, add the mutex to fix the poison overwritten, 2015-03-31, freeso.kim@lge.com*/
return rc;
post_fail:
msm_delete_command_ack_q(pvdev->vdev->num, 0);
command_ack_q_fail:
msm_destroy_session(pvdev->vdev->num);
session_fail:
pm_relax(&pvdev->vdev->dev);
camera_v4l2_vb2_q_release(filep);
vb2_q_fail:
camera_v4l2_fh_release(filep);
fh_open_fail:
mutex_unlock(&v4l2_sync_lock);/*LGE_CHANGE, add the mutex to fix the poison overwritten, 2015-03-31, freeso.kim@lge.com*/
return rc;
}
static unsigned int camera_v4l2_poll(struct file *filep,
struct poll_table_struct *wait)
{
int rc = 0;
struct camera_v4l2_private *sp = fh_to_private(filep->private_data);
if (sp->is_vb2_valid == 1)
rc = vb2_poll(&sp->vb2_q, filep, wait);
poll_wait(filep, &sp->fh.wait, wait);
if (v4l2_event_pending(&sp->fh))
rc |= POLLPRI;
return rc;
}
static int camera_v4l2_close(struct file *filep)
{
int rc = 0;
struct v4l2_event event;
struct msm_video_device *pvdev = video_drvdata(filep);
struct camera_v4l2_private *sp = fh_to_private(filep->private_data);
unsigned int opn_idx, mask;
BUG_ON(!pvdev);
mutex_lock(&v4l2_sync_lock);/*LGE_CHANGE, add the mutex to fix the poison overwritten, 2015-03-31, freeso.kim@lge.com*/
opn_idx = atomic_read(&pvdev->opened);
pr_err("%s: close stream_id=%d\n", __func__, sp->stream_id); /*LGE_CHANGE, add the mutex to fix the poison overwritten, 2015-03-31, freeso.kim@lge.com*/
mask = (1 << sp->stream_id);
opn_idx &= ~mask;
atomic_set(&pvdev->opened, opn_idx);
if (atomic_read(&pvdev->opened) == 0) {
camera_pack_event(filep, MSM_CAMERA_SET_PARM,
MSM_CAMERA_PRIV_DEL_STREAM, -1, &event);
/* Donot wait, imaging server may have crashed */
msm_post_event(&event, MSM_POST_EVT_TIMEOUT);
camera_pack_event(filep, MSM_CAMERA_DEL_SESSION, 0, -1, &event);
/* Donot wait, imaging server may have crashed */
msm_post_event(&event, -1);
msm_delete_command_ack_q(pvdev->vdev->num, 0);
/* This should take care of both normal close
* and application crashes */
msm_destroy_session(pvdev->vdev->num);
pm_relax(&pvdev->vdev->dev);
} else {
camera_pack_event(filep, MSM_CAMERA_SET_PARM,
MSM_CAMERA_PRIV_DEL_STREAM, -1, &event);
/* Donot wait, imaging server may have crashed */
msm_post_event(&event, MSM_POST_EVT_TIMEOUT);
msm_delete_command_ack_q(pvdev->vdev->num,
sp->stream_id);
msm_delete_stream(pvdev->vdev->num, sp->stream_id);
}
camera_v4l2_vb2_q_release(filep);
camera_v4l2_fh_release(filep);
mutex_unlock(&v4l2_sync_lock);/*LGE_CHANGE, add the mutex to fix the poison overwritten, 2015-03-31, freeso.kim@lge.com*/
return rc;
}
#ifdef CONFIG_COMPAT
long camera_v4l2_compat_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
return -ENOIOCTLCMD;
}
#endif
static struct v4l2_file_operations camera_v4l2_fops = {
.owner = THIS_MODULE,
.open = camera_v4l2_open,
.poll = camera_v4l2_poll,
.release = camera_v4l2_close,
.ioctl = video_ioctl2,
#ifdef CONFIG_COMPAT
.compat_ioctl32 = camera_v4l2_compat_ioctl,
#endif
};
int camera_init_v4l2(struct device *dev, unsigned int *session)
{
struct msm_video_device *pvdev;
struct v4l2_device *v4l2_dev;
int rc = 0;
pvdev = kzalloc(sizeof(struct msm_video_device),
GFP_KERNEL);
if (WARN_ON(!pvdev)) {
rc = -ENOMEM;
goto init_end;
}
pvdev->vdev = video_device_alloc();
if (WARN_ON(!pvdev->vdev)) {
rc = -ENOMEM;
goto video_fail;
}
v4l2_dev = kzalloc(sizeof(struct v4l2_device), GFP_KERNEL);
if (WARN_ON(!v4l2_dev)) {
rc = -ENOMEM;
goto v4l2_fail;
}
#if defined(CONFIG_MEDIA_CONTROLLER)
v4l2_dev->mdev = kzalloc(sizeof(struct media_device),
GFP_KERNEL);
if (!v4l2_dev->mdev) {
rc = -ENOMEM;
goto mdev_fail;
}
strlcpy(v4l2_dev->mdev->model, MSM_CAMERA_NAME,
sizeof(v4l2_dev->mdev->model));
v4l2_dev->mdev->dev = dev;
rc = media_device_register(v4l2_dev->mdev);
if (WARN_ON(rc < 0))
goto media_fail;
rc = media_entity_init(&pvdev->vdev->entity, 0, NULL, 0);
if (WARN_ON(rc < 0))
goto entity_fail;
pvdev->vdev->entity.type = MEDIA_ENT_T_DEVNODE_V4L;
pvdev->vdev->entity.group_id = QCAMERA_VNODE_GROUP_ID;
#endif
v4l2_dev->notify = NULL;
pvdev->vdev->v4l2_dev = v4l2_dev;
rc = v4l2_device_register(dev, pvdev->vdev->v4l2_dev);
if (WARN_ON(rc < 0))
goto register_fail;
strlcpy(pvdev->vdev->name, "msm-sensor", sizeof(pvdev->vdev->name));
pvdev->vdev->release = video_device_release;
pvdev->vdev->fops = &camera_v4l2_fops;
pvdev->vdev->ioctl_ops = &camera_v4l2_ioctl_ops;
pvdev->vdev->minor = -1;
pvdev->vdev->vfl_type = VFL_TYPE_GRABBER;
rc = video_register_device(pvdev->vdev,
VFL_TYPE_GRABBER, -1);
if (WARN_ON(rc < 0))
goto video_register_fail;
#if defined(CONFIG_MEDIA_CONTROLLER)
/* FIXME: How to get rid of this messy? */
pvdev->vdev->entity.name = video_device_node_name(pvdev->vdev);
#endif
*session = pvdev->vdev->num;
atomic_set(&pvdev->opened, 0);
video_set_drvdata(pvdev->vdev, pvdev);
device_init_wakeup(&pvdev->vdev->dev, 1);
goto init_end;
video_register_fail:
v4l2_device_unregister(pvdev->vdev->v4l2_dev);
register_fail:
#if defined(CONFIG_MEDIA_CONTROLLER)
media_entity_cleanup(&pvdev->vdev->entity);
entity_fail:
media_device_unregister(v4l2_dev->mdev);
media_fail:
kzfree(v4l2_dev->mdev);
mdev_fail:
#endif
kzfree(v4l2_dev);
v4l2_fail:
video_device_release(pvdev->vdev);
video_fail:
kzfree(pvdev);
init_end:
return rc;
}
|
LG-V10/LGV10__pplus_msm8992_kernel
|
drivers/media/platform/msm/camera_v2/camera/camera.c
|
C
|
gpl-2.0
| 21,596
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.etec.util.view;
/**
*
* @author dfelix3
*/
public class Utils {
public static final int PAGE_SIZE = 10;
}
|
diegoneri/ctps-atribuicao
|
src/main/java/br/com/etec/util/view/Utils.java
|
Java
|
gpl-2.0
| 229
|
{- |
Module : ./HasCASL/Builtin.hs
Description : builtin types and functions
Copyright : (c) Christian Maeder and Uni Bremen 2003
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Christian.Maeder@dfki.de
Stability : experimental
Portability : portable
HasCASL's builtin types and functions
-}
module HasCASL.Builtin
( cpoMap
, bList
, bTypes
, bOps
, preEnv
, addBuiltins
, aTypeArg
, bTypeArg
, cTypeArg
, aType
, bType
, cType
, botId
, whenElse
, ifThenElse
, defId
, eqId
, exEq
, falseId
, trueId
, notId
, negId
, andId
, orId
, logId
, predTypeId
, implId
, infixIf
, eqvId
, resId
, resType
, botType
, whenType
, defType
, eqType
, notType
, logType
, mkQualOp
, mkEqTerm
, mkLogTerm
, toBinJunctor
, mkTerm
, mkTermInst
, unitTerm
, unitTypeScheme
) where
import Common.Id
import Common.Keywords
import Common.GlobalAnnotations
import Common.AS_Annotation
import Common.AnnoParser
import Common.AnalyseAnnos
import Common.Result
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Common.Lib.Rel as Rel
import HasCASL.As
import HasCASL.AsUtils
import HasCASL.Le
import Text.ParserCombinators.Parsec
-- * buitln identifiers
trueId :: Id
trueId = mkId [mkSimpleId trueS]
falseId :: Id
falseId = mkId [mkSimpleId falseS]
ifThenElse :: Id
ifThenElse = mkId (map mkSimpleId [ifS, place, thenS, place, elseS, place])
whenElse :: Id
whenElse = mkId (map mkSimpleId [place, whenS, place, elseS, place])
infixIf :: Id
infixIf = mkInfix ifS
andId :: Id
andId = mkInfix lAnd
orId :: Id
orId = mkInfix lOr
implId :: Id
implId = mkInfix implS
eqvId :: Id
eqvId = mkInfix equivS
resId :: Id
resId = mkInfix "res"
{-
make these prefix identifier to allow "not def x" to be recognized
as "not (def x)" by giving def__ higher precedence then not__.
Simple identifiers usually have higher precedence then ____,
otherwise "def x" would be rejected. But with simple identifiers
"not def x" would be parsed as "(not def) x" because ____ is left
associative.
-}
defId :: Id
defId = mkId [mkSimpleId defS, placeTok]
notId :: Id
notId = mkId [mkSimpleId notS, placeTok]
negId :: Id
negId = mkId [mkSimpleId negS, placeTok]
builtinRelIds :: Set.Set Id
builtinRelIds = Set.fromList [typeId, eqId, exEq, defId]
builtinLogIds :: Set.Set Id
builtinLogIds = Set.fromList [andId, eqvId, implId, orId, infixIf, notId]
-- | add builtin identifiers
addBuiltins :: GlobalAnnos -> GlobalAnnos
addBuiltins ga =
let ass = assoc_annos ga
newAss = Map.union ass $ Map.fromList
[(applId, ALeft), (andId, ALeft), (orId, ALeft),
(implId, ARight), (infixIf, ALeft),
(whenElse, ARight)]
precs = prec_annos ga
pMap = Rel.toMap precs
opIds = Set.unions (Map.keysSet pMap : Map.elems pMap)
opIs = Set.toList
(((Set.filter (\ i -> begPlace i || endPlace i) opIds
Set.\\ builtinRelIds) Set.\\ builtinLogIds)
Set.\\ Set.fromList [applId, whenElse])
logs = [(eqvId, implId), (implId, andId), (implId, orId),
(eqvId, infixIf), (infixIf, andId), (infixIf, orId),
(andId, notId), (orId, notId),
(andId, negId), (orId, negId)]
rels1 = map ( \ i -> (notId, i)) $ Set.toList builtinRelIds
rels1b = map ( \ i -> (negId, i)) $ Set.toList builtinRelIds
rels2 = map ( \ i -> (i, whenElse)) $ Set.toList builtinRelIds
ops1 = map ( \ i -> (whenElse, i)) (applId : opIs)
ops2 = map ( \ i -> (i, applId)) opIs
newPrecs = foldl (\ p (a, b) -> if Rel.path b a p then p else
Rel.insertDiffPair a b p) precs $
concat [logs, rels1, rels1b, rels2, ops1, ops2]
in case addGlobalAnnos ga { assoc_annos = newAss
, prec_annos = Rel.transClosure newPrecs } $
map parseDAnno displayStrings of
Result _ (Just newGa) -> newGa
_ -> error "addBuiltins"
displayStrings :: [String]
displayStrings =
[ "%display __\\/__ %LATEX __\\vee__"
, "%display __/\\__ %LATEX __\\wedge__"
, "%display __=>__ %LATEX __\\Rightarrow__"
, "%display __<=>__ %LATEX __\\Leftrightarrow__"
, "%display not__ %LATEX \\neg__"
]
parseDAnno :: String -> Annotation
parseDAnno str = case parse annotationL "" str of
Left _ -> error "parseDAnno"
Right a -> a
aVar :: Id
aVar = stringToId "a"
bVar :: Id
bVar = stringToId "b"
cVar :: Id
cVar = stringToId "c"
aType :: Type
aType = typeArgToType aTypeArg
bType :: Type
bType = typeArgToType bTypeArg
cType :: Type
cType = typeArgToType cTypeArg
lazyAType :: Type
lazyAType = mkLazyType aType
varToTypeArgK :: Id -> Int -> Variance -> Kind -> TypeArg
varToTypeArgK i n v k = TypeArg i v (VarKind k) (toRaw k) n Other nullRange
varToTypeArg :: Id -> Int -> Variance -> TypeArg
varToTypeArg i n v = varToTypeArgK i n v universe
mkATypeArg :: Variance -> TypeArg
mkATypeArg = varToTypeArg aVar (-1)
aTypeArg :: TypeArg
aTypeArg = mkATypeArg NonVar
aTypeArgK :: Kind -> TypeArg
aTypeArgK = varToTypeArgK aVar (-1) NonVar
bTypeArg :: TypeArg
bTypeArg = varToTypeArg bVar (-2) NonVar
cTypeArg :: TypeArg
cTypeArg = varToTypeArg cVar (-3) NonVar
bindVarA :: TypeArg -> Type -> TypeScheme
bindVarA a t = TypeScheme [a] t nullRange
bindA :: Type -> TypeScheme
bindA = bindVarA aTypeArg
resType :: TypeScheme
resType = TypeScheme [aTypeArg, bTypeArg]
(mkFunArrType (mkProductType [lazyAType, mkLazyType bType]) FunArr aType)
nullRange
lazyLog :: Type
lazyLog = mkLazyType unitType
aPredType :: Type
aPredType = TypeAbs (mkATypeArg ContraVar)
(mkFunArrType aType PFunArr unitType) nullRange
eqType :: TypeScheme
eqType = bindA $ mkFunArrType (mkProductType [lazyAType, lazyAType])
PFunArr unitType
logType :: TypeScheme
logType = simpleTypeScheme $ mkFunArrType
(mkProductType [lazyLog, lazyLog]) PFunArr unitType
notType :: TypeScheme
notType = simpleTypeScheme $ mkFunArrType lazyLog PFunArr unitType
whenType :: TypeScheme
whenType = bindA $ mkFunArrType
(mkProductType [lazyAType, lazyLog, lazyAType]) PFunArr aType
unitTypeScheme :: TypeScheme
unitTypeScheme = simpleTypeScheme lazyLog
botId :: Id
botId = mkId [mkSimpleId "bottom"]
predTypeId :: Id
predTypeId = mkId [mkSimpleId "Pred"]
logId :: Id
logId = mkId [mkSimpleId "Logical"]
botType :: TypeScheme
botType = let a = aTypeArgK cppoCl in bindVarA a $ mkLazyType $ typeArgToType a
defType :: TypeScheme
defType = bindA $ mkFunArrType lazyAType PFunArr unitType
-- | builtin functions
bList :: [(Id, TypeScheme)]
bList = (botId, botType) : (defId, defType) : (notId, notType) :
(negId, notType) : (whenElse, whenType) :
(trueId, unitTypeScheme) : (falseId, unitTypeScheme) :
(eqId, eqType) : (exEq, eqType) : (resId, resType) :
map ( \ o -> (o, logType)) [andId, orId, eqvId, implId, infixIf]
mkTypesEntry :: Id -> Kind -> [Kind] -> [Id] -> TypeDefn -> (Id, TypeInfo)
mkTypesEntry i k cs s d =
(i, TypeInfo (toRaw k) (Set.fromList cs) (Set.fromList s) d)
funEntry :: Arrow -> [Arrow] -> [Kind] -> (Id, TypeInfo)
funEntry a s cs =
mkTypesEntry (arrowId a) funKind (funKind : cs) (map arrowId s) NoTypeDefn
mkEntry :: Id -> Kind -> [Kind] -> TypeDefn -> (Id, TypeInfo)
mkEntry i k cs = mkTypesEntry i k cs []
pEntry :: Id -> Kind -> TypeDefn -> (Id, TypeInfo)
pEntry i k = mkEntry i k [k]
-- | builtin data type map
bTypes :: TypeMap
bTypes = Map.fromList $ funEntry PFunArr [] []
: funEntry FunArr [PFunArr] []
: funEntry PContFunArr [PFunArr] [funKind3 cpoCl cpoCl cppoCl]
: funEntry ContFunArr [PContFunArr, FunArr]
[funKind3 cpoCl cpoCl cpoCl, funKind3 cpoCl cppoCl cppoCl]
: pEntry unitTypeId cppoCl NoTypeDefn
: pEntry predTypeId (FunKind ContraVar universe universe nullRange)
(AliasTypeDefn aPredType)
: pEntry lazyTypeId coKind NoTypeDefn
: pEntry logId universe (AliasTypeDefn $ mkLazyType unitType)
: map (\ n -> let k = prodKind n nullRange in
mkEntry (productId n nullRange) k
(k : map (prodKind1 n nullRange) [cpoCl, cppoCl]) NoTypeDefn)
[2 .. 5]
cpoId :: Id
cpoId = stringToId "Cpo"
cpoCl :: Kind
cpoCl = ClassKind cpoId
cppoId :: Id
cppoId = stringToId "Cppo"
cppoCl :: Kind
cppoCl = ClassKind cppoId
-- | builtin class map
cpoMap :: ClassMap
cpoMap = Map.fromList
[ (cpoId, ClassInfo rStar $ Set.singleton universe)
, (cppoId, ClassInfo rStar $ Set.singleton cpoCl)]
-- | builtin function map
bOps :: Assumps
bOps = Map.fromList $ map ( \ (i, sc) ->
(i, Set.singleton $ OpInfo sc Set.empty $ NoOpDefn Fun)) bList
-- | environment with predefined names
preEnv :: Env
preEnv = initialEnv { classMap = cpoMap, typeMap = bTypes, assumps = bOps }
mkQualOpInst :: InstKind -> Id -> TypeScheme -> [Type] -> Range -> Term
mkQualOpInst k i sc tys ps = QualOp Fun (PolyId i [] ps) sc tys k ps
mkQualOp :: Id -> TypeScheme -> [Type] -> Range -> Term
mkQualOp = mkQualOpInst Infer
mkTermInst :: InstKind -> Id -> TypeScheme -> [Type] -> Range -> Term -> Term
mkTermInst k i sc tys ps t = ApplTerm (mkQualOpInst k i sc tys ps) t ps
mkTerm :: Id -> TypeScheme -> [Type] -> Range -> Term -> Term
mkTerm = mkTermInst Infer
mkBinTerm :: Id -> TypeScheme -> [Type] -> Range -> Term -> Term -> Term
mkBinTerm i sc tys ps t1 t2 = mkTerm i sc tys ps $ TupleTerm [t1, t2] ps
mkLogTerm :: Id -> Range -> Term -> Term -> Term
mkLogTerm i = mkBinTerm i logType []
mkEqTerm :: Id -> Type -> Range -> Term -> Term -> Term
mkEqTerm i ty = mkBinTerm i eqType [ty]
unitTerm :: Id -> Range -> Term
unitTerm i = mkQualOp i unitTypeScheme []
toBinJunctor :: Id -> [Term] -> Range -> Term
toBinJunctor i ts ps = case ts of
[] -> error "toBinJunctor"
[t] -> t
t : rs -> mkLogTerm i ps t (toBinJunctor i rs ps)
|
spechub/Hets
|
HasCASL/Builtin.hs
|
Haskell
|
gpl-2.0
| 10,052
|
/*
* Copyright 2000 by Hans Reiser, licensing governed by reiserfs/README
*
* Trivial changes by Alan Cox to remove EHASHCOLLISION for compatibility
*
* Trivial Changes:
* Rights granted to Hans Reiser to redistribute under other terms providing
* he accepts all liability including but not limited to patent, fitness
* for purpose, and direct or indirect claims arising from failure to perform.
*
* NO WARRANTY
*/
#include <linux/config.h>
#include <linux/sched.h>
#include <linux/bitops.h>
#include <linux/reiserfs_fs.h>
#include <linux/smp_lock.h>
#define INC_DIR_INODE_NLINK(i) if (i->i_nlink != 1) { i->i_nlink++; if (i->i_nlink >= REISERFS_LINK_MAX) i->i_nlink=1; }
#define DEC_DIR_INODE_NLINK(i) if (i->i_nlink != 1) i->i_nlink--;
// directory item contains array of entry headers. This performs
// binary search through that array
static int bin_search_in_dir_item (struct reiserfs_dir_entry * de, loff_t off)
{
struct item_head * ih = de->de_ih;
struct reiserfs_de_head * deh = de->de_deh;
int rbound, lbound, j;
lbound = 0;
rbound = I_ENTRY_COUNT (ih) - 1;
for (j = (rbound + lbound) / 2; lbound <= rbound; j = (rbound + lbound) / 2) {
if (off < deh_offset (deh + j)) {
rbound = j - 1;
continue;
}
if (off > deh_offset (deh + j)) {
lbound = j + 1;
continue;
}
// this is not name found, but matched third key component
de->de_entry_num = j;
return NAME_FOUND;
}
de->de_entry_num = lbound;
return NAME_NOT_FOUND;
}
// comment? maybe something like set de to point to what the path points to?
static inline void set_de_item_location (struct reiserfs_dir_entry * de, struct path * path)
{
de->de_bh = get_last_bh (path);
de->de_ih = get_ih (path);
de->de_deh = B_I_DEH (de->de_bh, de->de_ih);
de->de_item_num = PATH_LAST_POSITION (path);
}
// de_bh, de_ih, de_deh (points to first element of array), de_item_num is set
inline void set_de_name_and_namelen (struct reiserfs_dir_entry * de)
{
struct reiserfs_de_head * deh = de->de_deh + de->de_entry_num;
if (de->de_entry_num >= ih_entry_count (de->de_ih))
BUG ();
de->de_entrylen = entry_length (de->de_bh, de->de_ih, de->de_entry_num);
de->de_namelen = de->de_entrylen - (de_with_sd (deh) ? SD_SIZE : 0);
de->de_name = B_I_PITEM (de->de_bh, de->de_ih) + deh_location(deh);
if (de->de_name[de->de_namelen - 1] == 0)
de->de_namelen = strlen (de->de_name);
}
// what entry points to
static inline void set_de_object_key (struct reiserfs_dir_entry * de)
{
if (de->de_entry_num >= ih_entry_count (de->de_ih))
BUG ();
de->de_dir_id = deh_dir_id( &(de->de_deh[de->de_entry_num]));
de->de_objectid = deh_objectid( &(de->de_deh[de->de_entry_num]));
}
static inline void store_de_entry_key (struct reiserfs_dir_entry * de)
{
struct reiserfs_de_head * deh = de->de_deh + de->de_entry_num;
if (de->de_entry_num >= ih_entry_count (de->de_ih))
BUG ();
/* store key of the found entry */
de->de_entry_key.version = KEY_FORMAT_3_5;
de->de_entry_key.on_disk_key.k_dir_id = le32_to_cpu (de->de_ih->ih_key.k_dir_id);
de->de_entry_key.on_disk_key.k_objectid = le32_to_cpu (de->de_ih->ih_key.k_objectid);
set_cpu_key_k_offset (&(de->de_entry_key), deh_offset (deh));
set_cpu_key_k_type (&(de->de_entry_key), TYPE_DIRENTRY);
}
/* We assign a key to each directory item, and place multiple entries
in a single directory item. A directory item has a key equal to the
key of the first directory entry in it.
This function first calls search_by_key, then, if item whose first
entry matches is not found it looks for the entry inside directory
item found by search_by_key. Fills the path to the entry, and to the
entry position in the item
*/
/* The function is NOT SCHEDULE-SAFE! */
int search_by_entry_key (struct super_block * sb, const struct cpu_key * key,
struct path * path, struct reiserfs_dir_entry * de)
{
int retval;
retval = search_item (sb, key, path);
switch (retval) {
case ITEM_NOT_FOUND:
if (!PATH_LAST_POSITION (path)) {
reiserfs_warning ("vs-7000: search_by_entry_key: search_by_key returned item position == 0");
pathrelse(path) ;
return IO_ERROR ;
}
PATH_LAST_POSITION (path) --;
case ITEM_FOUND:
break;
case IO_ERROR:
return retval;
default:
pathrelse (path);
reiserfs_warning ("vs-7002: search_by_entry_key: no path to here");
return IO_ERROR;
}
set_de_item_location (de, path);
#ifdef CONFIG_REISERFS_CHECK
if (!is_direntry_le_ih (de->de_ih) ||
COMP_SHORT_KEYS (&(de->de_ih->ih_key), key)) {
print_block (de->de_bh, 0, -1, -1);
reiserfs_panic (sb, "vs-7005: search_by_entry_key: found item %h is not directory item or "
"does not belong to the same directory as key %K", de->de_ih, key);
}
#endif /* CONFIG_REISERFS_CHECK */
/* binary search in directory item by third componen t of the
key. sets de->de_entry_num of de */
retval = bin_search_in_dir_item (de, cpu_key_k_offset (key));
path->pos_in_item = de->de_entry_num;
if (retval != NAME_NOT_FOUND) {
// ugly, but rename needs de_bh, de_deh, de_name, de_namelen, de_objectid set
set_de_name_and_namelen (de);
set_de_object_key (de);
}
return retval;
}
/* Keyed 32-bit hash function using TEA in a Davis-Meyer function */
/* The third component is hashed, and you can choose from more than
one hash function. Per directory hashes are not yet implemented
but are thought about. This function should be moved to hashes.c
Jedi, please do so. -Hans */
static __u32 get_third_component (struct super_block * s,
const char * name, int len)
{
__u32 res;
if (!len || (len == 1 && name[0] == '.'))
return DOT_OFFSET;
if (len == 2 && name[0] == '.' && name[1] == '.')
return DOT_DOT_OFFSET;
res = s->u.reiserfs_sb.s_hash_function (name, len);
// take bits from 7-th to 30-th including both bounds
res = GET_HASH_VALUE(res);
if (res == 0)
// needed to have no names before "." and ".." those have hash
// value == 0 and generation conters 1 and 2 accordingly
res = 128;
return res + MAX_GENERATION_NUMBER;
}
//
// a portion of this function, particularly the VFS interface portion,
// was derived from minix or ext2's analog and evolved as the
// prototype did. You should be able to tell which portion by looking
// at the ext2 code and comparing. It's subfunctions contain no code
// used as a template unless they are so labeled.
//
static int reiserfs_match (struct reiserfs_dir_entry * de,
const char * name, int namelen)
{
int retval = NAME_NOT_FOUND;
if ((namelen == de->de_namelen) &&
!memcmp(de->de_name, name, de->de_namelen))
retval = (de_visible (de->de_deh + de->de_entry_num) ? NAME_FOUND : NAME_FOUND_INVISIBLE);
return retval;
}
/* de's de_bh, de_ih, de_deh, de_item_num, de_entry_num are set already */
/* used when hash collisions exist */
static int linear_search_in_dir_item (struct cpu_key * key, struct reiserfs_dir_entry * de,
const char * name, int namelen)
{
struct reiserfs_de_head * deh = de->de_deh;
int retval;
int i;
i = de->de_entry_num;
if (i == I_ENTRY_COUNT (de->de_ih) ||
GET_HASH_VALUE (deh_offset (deh + i)) != GET_HASH_VALUE (cpu_key_k_offset (key))) {
i --;
}
RFALSE( de->de_deh != B_I_DEH (de->de_bh, de->de_ih),
"vs-7010: array of entry headers not found");
deh += i;
for (; i >= 0; i --, deh --) {
if (GET_HASH_VALUE (deh_offset (deh)) !=
GET_HASH_VALUE (cpu_key_k_offset (key))) {
// hash value does not match, no need to check whole name
return NAME_NOT_FOUND;
}
/* mark, that this generation number is used */
if (de->de_gen_number_bit_string)
set_bit (GET_GENERATION_NUMBER (deh_offset (deh)), de->de_gen_number_bit_string);
// calculate pointer to name and namelen
de->de_entry_num = i;
set_de_name_and_namelen (de);
if ((retval = reiserfs_match (de, name, namelen)) != NAME_NOT_FOUND) {
// de's de_name, de_namelen, de_recordlen are set. Fill the rest:
// key of pointed object
set_de_object_key (de);
store_de_entry_key (de);
// retval can be NAME_FOUND or NAME_FOUND_INVISIBLE
return retval;
}
}
if (GET_GENERATION_NUMBER (le_ih_k_offset (de->de_ih)) == 0)
/* we have reached left most entry in the node. In common we
have to go to the left neighbor, but if generation counter
is 0 already, we know for sure, that there is no name with
the same hash value */
// FIXME: this work correctly only because hash value can not
// be 0. Btw, in case of Yura's hash it is probably possible,
// so, this is a bug
return NAME_NOT_FOUND;
RFALSE( de->de_item_num,
"vs-7015: two diritems of the same directory in one node?");
return GOTO_PREVIOUS_ITEM;
}
//
// a portion of this function, particularly the VFS interface portion,
// was derived from minix or ext2's analog and evolved as the
// prototype did. You should be able to tell which portion by looking
// at the ext2 code and comparing. It's subfunctions contain no code
// used as a template unless they are so labeled.
//
// may return NAME_FOUND, NAME_FOUND_INVISIBLE, NAME_NOT_FOUND
// FIXME: should add something like IOERROR
static int reiserfs_find_entry (struct inode * dir, const char * name, int namelen,
struct path * path_to_entry, struct reiserfs_dir_entry * de)
{
struct cpu_key key_to_search;
int retval;
if (namelen > REISERFS_MAX_NAME_LEN (dir->i_sb->s_blocksize))
return NAME_NOT_FOUND;
/* we will search for this key in the tree */
make_cpu_key (&key_to_search, dir,
get_third_component (dir->i_sb, name, namelen), TYPE_DIRENTRY, 3);
while (1) {
retval = search_by_entry_key (dir->i_sb, &key_to_search, path_to_entry, de);
if (retval == IO_ERROR) {
reiserfs_warning ("zam-7001: io error in " __FUNCTION__ "\n");
return IO_ERROR;
}
/* compare names for all entries having given hash value */
retval = linear_search_in_dir_item (&key_to_search, de, name, namelen);
if (retval != GOTO_PREVIOUS_ITEM) {
/* there is no need to scan directory anymore. Given entry found or does not exist */
path_to_entry->pos_in_item = de->de_entry_num;
return retval;
}
/* there is left neighboring item of this directory and given entry can be there */
set_cpu_key_k_offset (&key_to_search, le_ih_k_offset (de->de_ih) - 1);
pathrelse (path_to_entry);
} /* while (1) */
}
//
// a portion of this function, particularly the VFS interface portion,
// was derived from minix or ext2's analog and evolved as the
// prototype did. You should be able to tell which portion by looking
// at the ext2 code and comparing. It's subfunctions contain no code
// used as a template unless they are so labeled.
//
static struct dentry * reiserfs_lookup (struct inode * dir, struct dentry * dentry)
{
int retval;
struct inode * inode = NULL;
struct reiserfs_dir_entry de;
INITIALIZE_PATH (path_to_entry);
reiserfs_check_lock_depth("lookup") ;
if (dentry->d_name.len > REISERFS_MAX_NAME_LEN (dir->i_sb->s_blocksize))
return ERR_PTR(-ENAMETOOLONG);
de.de_gen_number_bit_string = 0;
retval = reiserfs_find_entry (dir, dentry->d_name.name, dentry->d_name.len, &path_to_entry, &de);
pathrelse (&path_to_entry);
if (retval == NAME_FOUND) {
inode = reiserfs_iget (dir->i_sb, (struct cpu_key *)&(de.de_dir_id));
if (!inode || IS_ERR(inode)) {
return ERR_PTR(-EACCES);
}
}
if ( retval == IO_ERROR ) {
return ERR_PTR(-EIO);
}
d_add(dentry, inode);
return NULL;
}
//
// a portion of this function, particularly the VFS interface portion,
// was derived from minix or ext2's analog and evolved as the
// prototype did. You should be able to tell which portion by looking
// at the ext2 code and comparing. It's subfunctions contain no code
// used as a template unless they are so labeled.
//
/* add entry to the directory (entry can be hidden).
insert definition of when hidden directories are used here -Hans
Does not mark dir inode dirty, do it after successesfull call to it */
static int reiserfs_add_entry (struct reiserfs_transaction_handle *th, struct inode * dir,
const char * name, int namelen, struct inode * inode,
int visible)
{
struct cpu_key entry_key;
struct reiserfs_de_head * deh;
INITIALIZE_PATH (path);
struct reiserfs_dir_entry de;
int bit_string [MAX_GENERATION_NUMBER / (sizeof(int) * 8) + 1];
int gen_number;
char small_buf[32+DEH_SIZE] ; /* 48 bytes now and we avoid kmalloc
if we create file with short name */
char * buffer;
int buflen, paste_size;
int retval;
/* cannot allow items to be added into a busy deleted directory */
if (!namelen)
return -EINVAL;
if (namelen > REISERFS_MAX_NAME_LEN (dir->i_sb->s_blocksize))
return -ENAMETOOLONG;
/* each entry has unique key. compose it */
make_cpu_key (&entry_key, dir,
get_third_component (dir->i_sb, name, namelen), TYPE_DIRENTRY, 3);
/* get memory for composing the entry */
buflen = DEH_SIZE + ROUND_UP (namelen);
if (buflen > sizeof (small_buf)) {
buffer = reiserfs_kmalloc (buflen, GFP_NOFS, dir->i_sb);
if (buffer == 0)
return -ENOMEM;
} else
buffer = small_buf;
paste_size = (old_format_only (dir->i_sb)) ? (DEH_SIZE + namelen) : buflen;
/* fill buffer : directory entry head, name[, dir objectid | , stat data | ,stat data, dir objectid ] */
deh = (struct reiserfs_de_head *)buffer;
deh->deh_location = 0; /* JDM Endian safe if 0 */
put_deh_offset( deh, cpu_key_k_offset( &entry_key ) );
deh->deh_state = 0; /* JDM Endian safe if 0 */
/* put key (ino analog) to de */
deh->deh_dir_id = INODE_PKEY (inode)->k_dir_id; /* safe: k_dir_id is le */
deh->deh_objectid = INODE_PKEY (inode)->k_objectid; /* safe: k_objectid is le */
/* copy name */
memcpy ((char *)(deh + 1), name, namelen);
/* padd by 0s to the 4 byte boundary */
padd_item ((char *)(deh + 1), ROUND_UP (namelen), namelen);
/* entry is ready to be pasted into tree, set 'visibility' and 'stat data in entry' attributes */
mark_de_without_sd (deh);
visible ? mark_de_visible (deh) : mark_de_hidden (deh);
/* find the proper place for the new entry */
memset (bit_string, 0, sizeof (bit_string));
de.de_gen_number_bit_string = (char *)bit_string;
retval = reiserfs_find_entry (dir, name, namelen, &path, &de);
if( retval != NAME_NOT_FOUND ) {
if (buffer != small_buf)
reiserfs_kfree (buffer, buflen, dir->i_sb);
pathrelse (&path);
if ( retval == IO_ERROR ) {
return -EIO;
}
if (retval != NAME_FOUND) {
reiserfs_warning ("zam-7002:" __FUNCTION__ ": \"reiserfs_find_entry\" has returned"
" unexpected value (%d)\n", retval);
}
return -EEXIST;
}
gen_number = find_first_zero_bit (bit_string, MAX_GENERATION_NUMBER + 1);
if (gen_number > MAX_GENERATION_NUMBER) {
/* there is no free generation number */
reiserfs_warning ("reiserfs_add_entry: Congratulations! we have got hash function screwed up\n");
if (buffer != small_buf)
reiserfs_kfree (buffer, buflen, dir->i_sb);
pathrelse (&path);
return -EBUSY;
}
/* adjust offset of directory enrty */
put_deh_offset(deh, SET_GENERATION_NUMBER(deh_offset(deh), gen_number));
set_cpu_key_k_offset (&entry_key, deh_offset(deh));
/* update max-hash-collisions counter in reiserfs_sb_info */
PROC_INFO_MAX( th -> t_super, max_hash_collisions, gen_number );
if (gen_number != 0) { /* we need to re-search for the insertion point */
if (search_by_entry_key (dir->i_sb, &entry_key, &path, &de) != NAME_NOT_FOUND) {
reiserfs_warning ("vs-7032: reiserfs_add_entry: "
"entry with this key (%K) already exists\n", &entry_key);
if (buffer != small_buf)
reiserfs_kfree (buffer, buflen, dir->i_sb);
pathrelse (&path);
return -EBUSY;
}
}
/* perform the insertion of the entry that we have prepared */
retval = reiserfs_paste_into_item (th, &path, &entry_key, buffer, paste_size);
if (buffer != small_buf)
reiserfs_kfree (buffer, buflen, dir->i_sb);
if (retval) {
reiserfs_check_path(&path) ;
return retval;
}
dir->i_size += paste_size;
dir->i_blocks = ((dir->i_size + 511) >> 9);
dir->i_mtime = dir->i_ctime = CURRENT_TIME;
if (!S_ISDIR (inode->i_mode) && visible)
// reiserfs_mkdir or reiserfs_rename will do that by itself
reiserfs_update_sd (th, dir);
reiserfs_check_path(&path) ;
return 0;
}
//
// a portion of this function, particularly the VFS interface portion,
// was derived from minix or ext2's analog and evolved as the
// prototype did. You should be able to tell which portion by looking
// at the ext2 code and comparing. It's subfunctions contain no code
// used as a template unless they are so labeled.
//
static int reiserfs_create (struct inode * dir, struct dentry *dentry, int mode)
{
int retval;
struct inode * inode;
int windex ;
int jbegin_count = JOURNAL_PER_BALANCE_CNT * 2 ;
struct reiserfs_transaction_handle th ;
inode = new_inode(dir->i_sb) ;
if (!inode) {
return -ENOMEM ;
}
journal_begin(&th, dir->i_sb, jbegin_count) ;
th.t_caller = "create" ;
windex = push_journal_writer("reiserfs_create") ;
inode = reiserfs_new_inode (&th, dir, mode, 0, 0/*i_size*/, dentry, inode, &retval);
if (!inode) {
pop_journal_writer(windex) ;
journal_end(&th, dir->i_sb, jbegin_count) ;
return retval;
}
inode->i_op = &reiserfs_file_inode_operations;
inode->i_fop = &reiserfs_file_operations;
inode->i_mapping->a_ops = &reiserfs_address_space_operations ;
retval = reiserfs_add_entry (&th, dir, dentry->d_name.name, dentry->d_name.len,
inode, 1/*visible*/);
if (retval) {
inode->i_nlink--;
reiserfs_update_sd (&th, inode);
pop_journal_writer(windex) ;
// FIXME: should we put iput here and have stat data deleted
// in the same transactioin
journal_end(&th, dir->i_sb, jbegin_count) ;
iput (inode);
return retval;
}
reiserfs_update_inode_transaction(inode) ;
reiserfs_update_inode_transaction(dir) ;
d_instantiate(dentry, inode);
pop_journal_writer(windex) ;
journal_end(&th, dir->i_sb, jbegin_count) ;
return 0;
}
//
// a portion of this function, particularly the VFS interface portion,
// was derived from minix or ext2's analog and evolved as the
// prototype did. You should be able to tell which portion by looking
// at the ext2 code and comparing. It's subfunctions contain no code
// used as a template unless they are so labeled.
//
static int reiserfs_mknod (struct inode * dir, struct dentry *dentry, int mode, int rdev)
{
int retval;
struct inode * inode;
int windex ;
struct reiserfs_transaction_handle th ;
int jbegin_count = JOURNAL_PER_BALANCE_CNT * 3;
inode = new_inode(dir->i_sb) ;
if (!inode) {
return -ENOMEM ;
}
journal_begin(&th, dir->i_sb, jbegin_count) ;
windex = push_journal_writer("reiserfs_mknod") ;
inode = reiserfs_new_inode (&th, dir, mode, 0, 0/*i_size*/, dentry, inode, &retval);
if (!inode) {
pop_journal_writer(windex) ;
journal_end(&th, dir->i_sb, jbegin_count) ;
return retval;
}
init_special_inode(inode, mode, rdev) ;
//FIXME: needed for block and char devices only
reiserfs_update_sd (&th, inode);
reiserfs_update_inode_transaction(inode) ;
reiserfs_update_inode_transaction(dir) ;
retval = reiserfs_add_entry (&th, dir, dentry->d_name.name, dentry->d_name.len,
inode, 1/*visible*/);
if (retval) {
inode->i_nlink--;
reiserfs_update_sd (&th, inode);
pop_journal_writer(windex) ;
journal_end(&th, dir->i_sb, jbegin_count) ;
iput (inode);
return retval;
}
d_instantiate(dentry, inode);
pop_journal_writer(windex) ;
journal_end(&th, dir->i_sb, jbegin_count) ;
return 0;
}
//
// a portion of this function, particularly the VFS interface portion,
// was derived from minix or ext2's analog and evolved as the
// prototype did. You should be able to tell which portion by looking
// at the ext2 code and comparing. It's subfunctions contain no code
// used as a template unless they are so labeled.
//
static int reiserfs_mkdir (struct inode * dir, struct dentry *dentry, int mode)
{
int retval;
struct inode * inode;
int windex ;
struct reiserfs_transaction_handle th ;
int jbegin_count = JOURNAL_PER_BALANCE_CNT * 3;
inode = new_inode(dir->i_sb) ;
if (!inode) {
return -ENOMEM ;
}
journal_begin(&th, dir->i_sb, jbegin_count) ;
windex = push_journal_writer("reiserfs_mkdir") ;
/* inc the link count now, so another writer doesn't overflow it while
** we sleep later on.
*/
INC_DIR_INODE_NLINK(dir)
mode = S_IFDIR | mode;
inode = reiserfs_new_inode (&th, dir, mode, 0/*symlink*/,
old_format_only (dir->i_sb) ? EMPTY_DIR_SIZE_V1 : EMPTY_DIR_SIZE,
dentry, inode, &retval);
if (!inode) {
pop_journal_writer(windex) ;
dir->i_nlink-- ;
journal_end(&th, dir->i_sb, jbegin_count) ;
return retval;
}
reiserfs_update_inode_transaction(inode) ;
reiserfs_update_inode_transaction(dir) ;
inode->i_op = &reiserfs_dir_inode_operations;
inode->i_fop = &reiserfs_dir_operations;
// note, _this_ add_entry will not update dir's stat data
retval = reiserfs_add_entry (&th, dir, dentry->d_name.name, dentry->d_name.len,
inode, 1/*visible*/);
if (retval) {
inode->i_nlink = 0;
DEC_DIR_INODE_NLINK(dir);
reiserfs_update_sd (&th, inode);
pop_journal_writer(windex) ;
journal_end(&th, dir->i_sb, jbegin_count) ;
iput (inode);
return retval;
}
// the above add_entry did not update dir's stat data
reiserfs_update_sd (&th, dir);
d_instantiate(dentry, inode);
pop_journal_writer(windex) ;
journal_end(&th, dir->i_sb, jbegin_count) ;
return 0;
}
static inline int reiserfs_empty_dir(struct inode *inode) {
/* we can cheat because an old format dir cannot have
** EMPTY_DIR_SIZE, and a new format dir cannot have
** EMPTY_DIR_SIZE_V1. So, if the inode is either size,
** regardless of disk format version, the directory is empty.
*/
if (inode->i_size != EMPTY_DIR_SIZE &&
inode->i_size != EMPTY_DIR_SIZE_V1) {
return 0 ;
}
return 1 ;
}
//
// a portion of this function, particularly the VFS interface portion,
// was derived from minix or ext2's analog and evolved as the
// prototype did. You should be able to tell which portion by looking
// at the ext2 code and comparing. It's subfunctions contain no code
// used as a template unless they are so labeled.
//
static int reiserfs_rmdir (struct inode * dir, struct dentry *dentry)
{
int retval;
struct inode * inode;
int windex ;
struct reiserfs_transaction_handle th ;
int jbegin_count;
INITIALIZE_PATH (path);
struct reiserfs_dir_entry de;
/* we will be doing 2 balancings and update 2 stat data */
jbegin_count = JOURNAL_PER_BALANCE_CNT * 2 + 2;
journal_begin(&th, dir->i_sb, jbegin_count) ;
windex = push_journal_writer("reiserfs_rmdir") ;
de.de_gen_number_bit_string = 0;
if ( (retval = reiserfs_find_entry (dir, dentry->d_name.name, dentry->d_name.len, &path, &de)) == NAME_NOT_FOUND) {
retval = -ENOENT;
goto end_rmdir;
} else if ( retval == IO_ERROR) {
retval = -EIO;
goto end_rmdir;
}
inode = dentry->d_inode;
reiserfs_update_inode_transaction(inode) ;
reiserfs_update_inode_transaction(dir) ;
if (de.de_objectid != inode->i_ino) {
// FIXME: compare key of an object and a key found in the
// entry
retval = -EIO;
goto end_rmdir;
}
if (!reiserfs_empty_dir(inode)) {
retval = -ENOTEMPTY;
goto end_rmdir;
}
/* cut entry from dir directory */
retval = reiserfs_cut_from_item (&th, &path, &(de.de_entry_key), dir,
NULL, /* page */
0/*new file size - not used here*/);
if (retval < 0)
goto end_rmdir;
if ( inode->i_nlink != 2 && inode->i_nlink != 1 )
printk ("reiserfs_rmdir: empty directory has nlink != 2 (%d)\n", inode->i_nlink);
inode->i_nlink = 0;
inode->i_ctime = dir->i_ctime = dir->i_mtime = CURRENT_TIME;
reiserfs_update_sd (&th, inode);
DEC_DIR_INODE_NLINK(dir)
dir->i_size -= (DEH_SIZE + de.de_entrylen);
dir->i_blocks = ((dir->i_size + 511) >> 9);
reiserfs_update_sd (&th, dir);
/* prevent empty directory from getting lost */
add_save_link (&th, inode, 0/* not truncate */);
pop_journal_writer(windex) ;
journal_end(&th, dir->i_sb, jbegin_count) ;
reiserfs_check_path(&path) ;
return 0;
end_rmdir:
/* we must release path, because we did not call
reiserfs_cut_from_item, or reiserfs_cut_from_item does not
release path if operation was not complete */
pathrelse (&path);
pop_journal_writer(windex) ;
journal_end(&th, dir->i_sb, jbegin_count) ;
return retval;
}
//
// a portion of this function, particularly the VFS interface portion,
// was derived from minix or ext2's analog and evolved as the
// prototype did. You should be able to tell which portion by looking
// at the ext2 code and comparing. It's subfunctions contain no code
// used as a template unless they are so labeled.
//
static int reiserfs_unlink (struct inode * dir, struct dentry *dentry)
{
int retval;
struct inode * inode;
struct reiserfs_dir_entry de;
INITIALIZE_PATH (path);
int windex ;
struct reiserfs_transaction_handle th ;
int jbegin_count;
inode = dentry->d_inode;
/* in this transaction we can be doing at max two balancings and update
two stat datas */
jbegin_count = JOURNAL_PER_BALANCE_CNT * 2 + 2;
journal_begin(&th, dir->i_sb, jbegin_count) ;
windex = push_journal_writer("reiserfs_unlink") ;
de.de_gen_number_bit_string = 0;
if ( (retval = reiserfs_find_entry (dir, dentry->d_name.name, dentry->d_name.len, &path, &de)) == NAME_NOT_FOUND) {
retval = -ENOENT;
goto end_unlink;
} else if (retval == IO_ERROR) {
retval = -EIO;
goto end_unlink;
}
reiserfs_update_inode_transaction(inode) ;
reiserfs_update_inode_transaction(dir) ;
if (de.de_objectid != inode->i_ino) {
// FIXME: compare key of an object and a key found in the
// entry
retval = -EIO;
goto end_unlink;
}
if (!inode->i_nlink) {
printk("reiserfs_unlink: deleting nonexistent file (%s:%lu), %d\n",
kdevname(inode->i_dev), inode->i_ino, inode->i_nlink);
inode->i_nlink = 1;
}
retval = reiserfs_cut_from_item (&th, &path, &(de.de_entry_key), dir, NULL, 0);
if (retval < 0)
goto end_unlink;
inode->i_nlink--;
inode->i_ctime = CURRENT_TIME;
reiserfs_update_sd (&th, inode);
dir->i_size -= (de.de_entrylen + DEH_SIZE);
dir->i_blocks = ((dir->i_size + 511) >> 9);
dir->i_ctime = dir->i_mtime = CURRENT_TIME;
reiserfs_update_sd (&th, dir);
if (!inode->i_nlink)
/* prevent file from getting lost */
add_save_link (&th, inode, 0/* not truncate */);
pop_journal_writer(windex) ;
journal_end(&th, dir->i_sb, jbegin_count) ;
reiserfs_check_path(&path) ;
return 0;
end_unlink:
pathrelse (&path);
pop_journal_writer(windex) ;
journal_end(&th, dir->i_sb, jbegin_count) ;
reiserfs_check_path(&path) ;
return retval;
}
//
// a portion of this function, particularly the VFS interface portion,
// was derived from minix or ext2's analog and evolved as the
// prototype did. You should be able to tell which portion by looking
// at the ext2 code and comparing. It's subfunctions contain no code
// used as a template unless they are so labeled.
//
static int reiserfs_symlink (struct inode * dir, struct dentry * dentry, const char * symname)
{
int retval;
struct inode * inode;
char * name;
int item_len;
int windex ;
struct reiserfs_transaction_handle th ;
int jbegin_count = JOURNAL_PER_BALANCE_CNT * 3;
inode = new_inode(dir->i_sb) ;
if (!inode) {
return -ENOMEM ;
}
item_len = ROUND_UP (strlen (symname));
if (item_len > MAX_DIRECT_ITEM_LEN (dir->i_sb->s_blocksize)) {
iput(inode) ;
return -ENAMETOOLONG;
}
name = reiserfs_kmalloc (item_len, GFP_NOFS, dir->i_sb);
if (!name) {
iput(inode) ;
return -ENOMEM;
}
memcpy (name, symname, strlen (symname));
padd_item (name, item_len, strlen (symname));
journal_begin(&th, dir->i_sb, jbegin_count) ;
windex = push_journal_writer("reiserfs_symlink") ;
inode = reiserfs_new_inode (&th, dir, S_IFLNK | S_IRWXUGO, name, strlen (symname), dentry,
inode, &retval);
reiserfs_kfree (name, item_len, dir->i_sb);
if (inode == 0) { /* reiserfs_new_inode iputs for us */
pop_journal_writer(windex) ;
journal_end(&th, dir->i_sb, jbegin_count) ;
return retval;
}
reiserfs_update_inode_transaction(inode) ;
reiserfs_update_inode_transaction(dir) ;
inode->i_op = &page_symlink_inode_operations;
inode->i_mapping->a_ops = &reiserfs_address_space_operations;
// must be sure this inode is written with this transaction
//
//reiserfs_update_sd (&th, inode, READ_BLOCKS);
retval = reiserfs_add_entry (&th, dir, dentry->d_name.name, dentry->d_name.len,
inode, 1/*visible*/);
if (retval) {
inode->i_nlink--;
reiserfs_update_sd (&th, inode);
pop_journal_writer(windex) ;
journal_end(&th, dir->i_sb, jbegin_count) ;
iput (inode);
return retval;
}
d_instantiate(dentry, inode);
pop_journal_writer(windex) ;
journal_end(&th, dir->i_sb, jbegin_count) ;
return 0;
}
//
// a portion of this function, particularly the VFS interface portion,
// was derived from minix or ext2's analog and evolved as the
// prototype did. You should be able to tell which portion by looking
// at the ext2 code and comparing. It's subfunctions contain no code
// used as a template unless they are so labeled.
//
static int reiserfs_link (struct dentry * old_dentry, struct inode * dir, struct dentry * dentry)
{
int retval;
struct inode *inode = old_dentry->d_inode;
int windex ;
struct reiserfs_transaction_handle th ;
int jbegin_count = JOURNAL_PER_BALANCE_CNT * 3;
if (S_ISDIR(inode->i_mode))
return -EPERM;
if (inode->i_nlink >= REISERFS_LINK_MAX) {
//FIXME: sd_nlink is 32 bit for new files
return -EMLINK;
}
journal_begin(&th, dir->i_sb, jbegin_count) ;
windex = push_journal_writer("reiserfs_link") ;
/* create new entry */
retval = reiserfs_add_entry (&th, dir, dentry->d_name.name, dentry->d_name.len,
inode, 1/*visible*/);
reiserfs_update_inode_transaction(inode) ;
reiserfs_update_inode_transaction(dir) ;
if (retval) {
pop_journal_writer(windex) ;
journal_end(&th, dir->i_sb, jbegin_count) ;
return retval;
}
inode->i_nlink++;
inode->i_ctime = CURRENT_TIME;
reiserfs_update_sd (&th, inode);
atomic_inc(&inode->i_count) ;
d_instantiate(dentry, inode);
pop_journal_writer(windex) ;
journal_end(&th, dir->i_sb, jbegin_count) ;
return 0;
}
// de contains information pointing to an entry which
static int de_still_valid (const char * name, int len, struct reiserfs_dir_entry * de)
{
struct reiserfs_dir_entry tmp = *de;
// recalculate pointer to name and name length
set_de_name_and_namelen (&tmp);
// FIXME: could check more
if (tmp.de_namelen != len || memcmp (name, de->de_name, len))
return 0;
return 1;
}
static int entry_points_to_object (const char * name, int len, struct reiserfs_dir_entry * de, struct inode * inode)
{
if (!de_still_valid (name, len, de))
return 0;
if (inode) {
if (!de_visible (de->de_deh + de->de_entry_num))
reiserfs_panic (0, "vs-7042: entry_points_to_object: entry must be visible");
return (de->de_objectid == inode->i_ino) ? 1 : 0;
}
/* this must be added hidden entry */
if (de_visible (de->de_deh + de->de_entry_num))
reiserfs_panic (0, "vs-7043: entry_points_to_object: entry must be visible");
return 1;
}
/* sets key of objectid the entry has to point to */
static void set_ino_in_dir_entry (struct reiserfs_dir_entry * de, struct key * key)
{
/* JDM These operations are endian safe - both are le */
de->de_deh[de->de_entry_num].deh_dir_id = key->k_dir_id;
de->de_deh[de->de_entry_num].deh_objectid = key->k_objectid;
}
//
// a portion of this function, particularly the VFS interface portion,
// was derived from minix or ext2's analog and evolved as the
// prototype did. You should be able to tell which portion by looking
// at the ext2 code and comparing. It's subfunctions contain no code
// used as a template unless they are so labeled.
//
/*
* process, that is going to call fix_nodes/do_balance must hold only
* one path. If it holds 2 or more, it can get into endless waiting in
* get_empty_nodes or its clones
*/
static int reiserfs_rename (struct inode * old_dir, struct dentry *old_dentry,
struct inode * new_dir, struct dentry *new_dentry)
{
int retval;
INITIALIZE_PATH (old_entry_path);
INITIALIZE_PATH (new_entry_path);
INITIALIZE_PATH (dot_dot_entry_path);
struct item_head new_entry_ih, old_entry_ih, dot_dot_ih ;
struct reiserfs_dir_entry old_de, new_de, dot_dot_de;
struct inode * old_inode, * new_inode;
int windex ;
struct reiserfs_transaction_handle th ;
int jbegin_count ;
/* two balancings: old name removal, new name insertion or "save" link,
stat data updates: old directory and new directory and maybe block
containing ".." of renamed directory */
jbegin_count = JOURNAL_PER_BALANCE_CNT * 3 + 3;
old_inode = old_dentry->d_inode;
new_inode = new_dentry->d_inode;
// make sure, that oldname still exists and points to an object we
// are going to rename
old_de.de_gen_number_bit_string = 0;
retval = reiserfs_find_entry (old_dir, old_dentry->d_name.name, old_dentry->d_name.len,
&old_entry_path, &old_de);
pathrelse (&old_entry_path);
if (retval == IO_ERROR)
return -EIO;
if (retval != NAME_FOUND || old_de.de_objectid != old_inode->i_ino) {
return -ENOENT;
}
if (S_ISDIR(old_inode->i_mode)) {
// make sure, that directory being renamed has correct ".."
// and that its new parent directory has not too many links
// already
if (new_inode) {
if (!reiserfs_empty_dir(new_inode)) {
return -ENOTEMPTY;
}
}
/* directory is renamed, its parent directory will be changed,
** so find ".." entry
*/
dot_dot_de.de_gen_number_bit_string = 0;
retval = reiserfs_find_entry (old_inode, "..", 2, &dot_dot_entry_path, &dot_dot_de);
pathrelse (&dot_dot_entry_path);
if (retval != NAME_FOUND)
return -EIO;
/* inode number of .. must equal old_dir->i_ino */
if (dot_dot_de.de_objectid != old_dir->i_ino)
return -EIO;
}
journal_begin(&th, old_dir->i_sb, jbegin_count) ;
windex = push_journal_writer("reiserfs_rename") ;
/* add new entry (or find the existing one) */
retval = reiserfs_add_entry (&th, new_dir, new_dentry->d_name.name, new_dentry->d_name.len,
old_inode, 0);
if (retval == -EEXIST) {
// FIXME: is it possible, that new_inode == 0 here? If yes, it
// is not clear how does ext2 handle that
if (!new_inode) {
reiserfs_panic (old_dir->i_sb,
"vs-7050: new entry is found, new inode == 0\n");
}
} else if (retval) {
pop_journal_writer(windex) ;
journal_end(&th, old_dir->i_sb, jbegin_count) ;
return retval;
}
reiserfs_update_inode_transaction(old_dir) ;
reiserfs_update_inode_transaction(new_dir) ;
/* this makes it so an fsync on an open fd for the old name will
** commit the rename operation
*/
reiserfs_update_inode_transaction(old_inode) ;
if (new_inode)
reiserfs_update_inode_transaction(new_inode) ;
while (1) {
// look for old name using corresponding entry key (found by reiserfs_find_entry)
if (search_by_entry_key (new_dir->i_sb, &old_de.de_entry_key, &old_entry_path, &old_de) != NAME_FOUND)
BUG ();
copy_item_head(&old_entry_ih, get_ih(&old_entry_path)) ;
reiserfs_prepare_for_journal(old_inode->i_sb, old_de.de_bh, 1) ;
// look for new name by reiserfs_find_entry
new_de.de_gen_number_bit_string = 0;
retval = reiserfs_find_entry (new_dir, new_dentry->d_name.name, new_dentry->d_name.len,
&new_entry_path, &new_de);
// reiserfs_add_entry should not return IO_ERROR, because it is called with essentially same parameters from
// reiserfs_add_entry above, and we'll catch any i/o errors before we get here.
if (retval != NAME_FOUND_INVISIBLE && retval != NAME_FOUND)
BUG ();
copy_item_head(&new_entry_ih, get_ih(&new_entry_path)) ;
reiserfs_prepare_for_journal(old_inode->i_sb, new_de.de_bh, 1) ;
if (S_ISDIR(old_inode->i_mode)) {
if (search_by_entry_key (new_dir->i_sb, &dot_dot_de.de_entry_key, &dot_dot_entry_path, &dot_dot_de) != NAME_FOUND)
BUG ();
copy_item_head(&dot_dot_ih, get_ih(&dot_dot_entry_path)) ;
// node containing ".." gets into transaction
reiserfs_prepare_for_journal(old_inode->i_sb, dot_dot_de.de_bh, 1) ;
}
/* we should check seals here, not do
this stuff, yes? Then, having
gathered everything into RAM we
should lock the buffers, yes? -Hans */
/* probably. our rename needs to hold more
** than one path at once. The seals would
** have to be written to deal with multi-path
** issues -chris
*/
/* sanity checking before doing the rename - avoid races many
** of the above checks could have scheduled. We have to be
** sure our items haven't been shifted by another process.
*/
if (item_moved(&new_entry_ih, &new_entry_path) ||
!entry_points_to_object(new_dentry->d_name.name,
new_dentry->d_name.len,
&new_de, new_inode) ||
item_moved(&old_entry_ih, &old_entry_path) ||
!entry_points_to_object (old_dentry->d_name.name,
old_dentry->d_name.len,
&old_de, old_inode)) {
reiserfs_restore_prepared_buffer (old_inode->i_sb, new_de.de_bh);
reiserfs_restore_prepared_buffer (old_inode->i_sb, old_de.de_bh);
if (S_ISDIR(old_inode->i_mode))
reiserfs_restore_prepared_buffer (old_inode->i_sb, dot_dot_de.de_bh);
continue;
}
if (S_ISDIR(old_inode->i_mode)) {
if ( item_moved(&dot_dot_ih, &dot_dot_entry_path) ||
!entry_points_to_object ( "..", 2, &dot_dot_de, old_dir) ) {
reiserfs_restore_prepared_buffer (old_inode->i_sb, old_de.de_bh);
reiserfs_restore_prepared_buffer (old_inode->i_sb, new_de.de_bh);
reiserfs_restore_prepared_buffer (old_inode->i_sb, dot_dot_de.de_bh);
continue;
}
}
RFALSE( S_ISDIR(old_inode->i_mode) &&
!reiserfs_buffer_prepared(dot_dot_de.de_bh), "" );
break;
}
/* ok, all the changes can be done in one fell swoop when we
have claimed all the buffers needed.*/
mark_de_visible (new_de.de_deh + new_de.de_entry_num);
set_ino_in_dir_entry (&new_de, INODE_PKEY (old_inode));
journal_mark_dirty (&th, old_dir->i_sb, new_de.de_bh);
mark_de_hidden (old_de.de_deh + old_de.de_entry_num);
journal_mark_dirty (&th, old_dir->i_sb, old_de.de_bh);
old_dir->i_ctime = old_dir->i_mtime = CURRENT_TIME;
new_dir->i_ctime = new_dir->i_mtime = CURRENT_TIME;
if (new_inode) {
// adjust link number of the victim
if (S_ISDIR(new_inode->i_mode)) {
new_inode->i_nlink = 0;
} else {
new_inode->i_nlink--;
}
new_inode->i_ctime = CURRENT_TIME;
}
if (S_ISDIR(old_inode->i_mode)) {
// adjust ".." of renamed directory
set_ino_in_dir_entry (&dot_dot_de, INODE_PKEY (new_dir));
journal_mark_dirty (&th, new_dir->i_sb, dot_dot_de.de_bh);
if (!new_inode)
/* there (in new_dir) was no directory, so it got new link
(".." of renamed directory) */
INC_DIR_INODE_NLINK(new_dir);
/* old directory lost one link - ".. " of renamed directory */
DEC_DIR_INODE_NLINK(old_dir);
}
// looks like in 2.3.99pre3 brelse is atomic. so we can use pathrelse
pathrelse (&new_entry_path);
pathrelse (&dot_dot_entry_path);
// FIXME: this reiserfs_cut_from_item's return value may screw up
// anybody, but it will panic if will not be able to find the
// entry. This needs one more clean up
if (reiserfs_cut_from_item (&th, &old_entry_path, &(old_de.de_entry_key), old_dir, NULL, 0) < 0)
reiserfs_warning ("vs-7060: reiserfs_rename: couldn't not cut old name. Fsck later?\n");
old_dir->i_size -= DEH_SIZE + old_de.de_entrylen;
old_dir->i_blocks = ((old_dir->i_size + 511) >> 9);
reiserfs_update_sd (&th, old_dir);
reiserfs_update_sd (&th, new_dir);
if (new_inode) {
if (new_inode->i_nlink == 0)
add_save_link (&th, new_inode, 0/* not truncate */);
reiserfs_update_sd (&th, new_inode);
}
pop_journal_writer(windex) ;
journal_end(&th, old_dir->i_sb, jbegin_count) ;
return 0;
}
/*
* directories can handle most operations...
*/
struct inode_operations reiserfs_dir_inode_operations = {
//&reiserfs_dir_operations, /* default_file_ops */
create: reiserfs_create,
lookup: reiserfs_lookup,
link: reiserfs_link,
unlink: reiserfs_unlink,
symlink: reiserfs_symlink,
mkdir: reiserfs_mkdir,
rmdir: reiserfs_rmdir,
mknod: reiserfs_mknod,
rename: reiserfs_rename,
};
|
alexbousso/kernel_2.4.18-14
|
fs/reiserfs/namei.c
|
C
|
gpl-2.0
| 41,942
|
<?php
interface AdminCourseAction
{
public function getAdminActionURL();
/**
* Defines if the Plugin wants to use the multimode to edit multiple courses at once.
* @return boolean|string: false, if multimode is not important, else true. But you can also set it to a string (means true) that is the label of the send-button like _("Veranstaltungen archivieren")
*/
public function useMultimode();
/**
* Returns a template for a small table cell (the <td> wraps the template-content)
* in which you can set inputs and links to display special actions for an admin
* for the given course.
* @param $course_id
* @param null $values
* @return null|Flex_Template
*/
public function getAdminCourseActionTemplate($course_id, $values = null);
}
|
pawohl/studip
|
lib/plugins/core/AdminCourseAction.class.php
|
PHP
|
gpl-2.0
| 808
|
/*
* (C) Copyright 2002
* Sysgo Real-Time Solutions, GmbH <www.elinos.com>
* Marius Groeger <mgroeger@sysgo.de>
*
* (C) Copyright 2002
* Sysgo Real-Time Solutions, GmbH <www.elinos.com>
* Alex Zuepke <azu@sysgo.de>
*
* See file CREDITS for list of people who contributed to this
* project.
*
* 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 <clps7111.h>
#include <asm/proc-armv/ptrace.h>
#include <asm/hardware.h>
#ifndef CONFIG_NETARM
/* we always count down the max. */
#define TIMER_LOAD_VAL 0xffff
/* macro to read the 16 bit timer */
#define READ_TIMER (IO_TC1D & 0xffff)
#ifdef CONFIG_LPC2292
#undef READ_TIMER
#define READ_TIMER (0xFFFFFFFF - GET32(T0TC))
#endif
#else
#define IRQEN (*(volatile unsigned int *)(NETARM_GEN_MODULE_BASE + NETARM_GEN_INTR_ENABLE))
#define TM2CTRL (*(volatile unsigned int *)(NETARM_GEN_MODULE_BASE + NETARM_GEN_TIMER2_CONTROL))
#define TM2STAT (*(volatile unsigned int *)(NETARM_GEN_MODULE_BASE + NETARM_GEN_TIMER2_STATUS))
#define TIMER_LOAD_VAL NETARM_GEN_TSTAT_CTC_MASK
#define READ_TIMER (TM2STAT & NETARM_GEN_TSTAT_CTC_MASK)
#endif
#ifdef CONFIG_S3C4510B
/* require interrupts for the S3C4510B */
# ifndef CONFIG_USE_IRQ
# error CONFIG_USE_IRQ _must_ be defined when using CONFIG_S3C4510B
# else
static struct _irq_handler IRQ_HANDLER[N_IRQS];
# endif
#endif /* CONFIG_S3C4510B */
#ifdef CONFIG_USE_IRQ
void do_irq (struct pt_regs *pt_regs)
{
#if defined(CONFIG_S3C4510B)
unsigned int pending;
while ( (pending = GET_REG( REG_INTOFFSET)) != 0x54) { /* sentinal value for no pending interrutps */
IRQ_HANDLER[pending>>2].m_func( IRQ_HANDLER[pending>>2].m_data);
/* clear pending interrupt */
PUT_REG( REG_INTPEND, (1<<(pending>>2)));
}
#elif defined(CONFIG_INTEGRATOR) && defined(CONFIG_ARCH_INTEGRATOR)
/* No do_irq() for IntegratorAP/CM720T as yet */
#elif defined(CONFIG_LPC2292)
void (*pfnct)(void);
pfnct = (void (*)(void))VICVectAddr;
(*pfnct)();
#else
#error do_irq() not defined for this CPU type
#endif
}
#endif
#ifdef CONFIG_S3C4510B
static void default_isr( void *data) {
printf ("default_isr(): called for IRQ %d\n", (int)data);
}
static void timer_isr( void *data) {
unsigned int *pTime = (unsigned int *)data;
(*pTime)++;
if ( !(*pTime % (CONFIG_SYS_HZ/4))) {
/* toggle LED 0 */
PUT_REG( REG_IOPDATA, GET_REG(REG_IOPDATA) ^ 0x1);
}
}
#endif
#if defined(CONFIG_INTEGRATOR) && defined(CONFIG_ARCH_INTEGRATOR)
/* Use IntegratorAP routines in board/integratorap.c */
#else
static ulong timestamp;
static ulong lastdec;
#if defined(CONFIG_USE_IRQ) && defined(CONFIG_S3C4510B)
int arch_interrupt_init (void)
{
int i;
/* install default interrupt handlers */
for ( i = 0; i < N_IRQS; i++) {
IRQ_HANDLER[i].m_data = (void *)i;
IRQ_HANDLER[i].m_func = default_isr;
}
/* configure interrupts for IRQ mode */
PUT_REG( REG_INTMODE, 0x0);
/* clear any pending interrupts */
PUT_REG( REG_INTPEND, 0x1FFFFF);
lastdec = 0;
/* install interrupt handler for timer */
IRQ_HANDLER[INT_TIMER0].m_data = (void *)×tamp;
IRQ_HANDLER[INT_TIMER0].m_func = timer_isr;
return 0;
}
#endif
int timer_init (void)
{
#if defined(CONFIG_NETARM)
/* disable all interrupts */
IRQEN = 0;
/* operate timer 2 in non-prescale mode */
TM2CTRL = ( NETARM_GEN_TIMER_SET_HZ(CONFIG_SYS_HZ) |
NETARM_GEN_TCTL_ENABLE |
NETARM_GEN_TCTL_INIT_COUNT(TIMER_LOAD_VAL));
/* set timer 2 counter */
lastdec = TIMER_LOAD_VAL;
#elif defined(CONFIG_IMPA7) || defined(CONFIG_EP7312) || defined(CONFIG_ARMADILLO)
/* disable all interrupts */
IO_INTMR1 = 0;
/* operate timer 1 in prescale mode */
IO_SYSCON1 |= SYSCON1_TC1M;
/* select 2kHz clock source for timer 1 */
IO_SYSCON1 &= ~SYSCON1_TC1S;
/* set timer 1 counter */
lastdec = IO_TC1D = TIMER_LOAD_VAL;
#elif defined(CONFIG_S3C4510B)
/* configure free running timer 0 */
PUT_REG( REG_TMOD, 0x0);
/* Stop timer 0 */
CLR_REG( REG_TMOD, TM0_RUN);
/* Configure for interval mode */
CLR_REG( REG_TMOD, TM1_TOGGLE);
/*
* Load Timer data register with count down value.
* count_down_val = CONFIG_SYS_SYS_CLK_FREQ/CONFIG_SYS_HZ
*/
PUT_REG( REG_TDATA0, (CONFIG_SYS_SYS_CLK_FREQ / CONFIG_SYS_HZ));
/*
* Enable global interrupt
* Enable timer0 interrupt
*/
CLR_REG( REG_INTMASK, ((1<<INT_GLOBAL) | (1<<INT_TIMER0)));
/* Start timer */
SET_REG( REG_TMOD, TM0_RUN);
#elif defined(CONFIG_LPC2292)
PUT32(T0IR, 0); /* disable all timer0 interrupts */
PUT32(T0TCR, 0); /* disable timer0 */
PUT32(T0PR, CONFIG_SYS_SYS_CLK_FREQ / CONFIG_SYS_HZ);
PUT32(T0MCR, 0);
PUT32(T0TC, 0);
PUT32(T0TCR, 1); /* enable timer0 */
#else
#error No timer_init() defined for this CPU type
#endif
timestamp = 0;
return (0);
}
#endif /* ! IntegratorAP */
/*
* timer without interrupts
*/
#if defined(CONFIG_IMPA7) || defined(CONFIG_EP7312) || defined(CONFIG_NETARM) || defined(CONFIG_ARMADILLO) || defined(CONFIG_LPC2292)
ulong get_timer (ulong base)
{
return get_timer_masked () - base;
}
void __udelay (unsigned long usec)
{
ulong tmo;
tmo = usec / 1000;
tmo *= CONFIG_SYS_HZ;
tmo /= 1000;
tmo += get_timer (0);
while (get_timer_masked () < tmo)
#ifdef CONFIG_LPC2292
/* GJ - not sure whether this is really needed or a misunderstanding */
__asm__ __volatile__(" nop");
#else
/*NOP*/;
#endif
}
ulong get_timer_masked (void)
{
ulong now = READ_TIMER;
if (lastdec >= now) {
/* normal mode */
timestamp += lastdec - now;
} else {
/* we have an overflow ... */
timestamp += lastdec + TIMER_LOAD_VAL - now;
}
lastdec = now;
return timestamp;
}
void udelay_masked (unsigned long usec)
{
ulong tmo;
ulong endtime;
signed long diff;
if (usec >= 1000) {
tmo = usec / 1000;
tmo *= CONFIG_SYS_HZ;
tmo /= 1000;
} else {
tmo = usec * CONFIG_SYS_HZ;
tmo /= (1000*1000);
}
endtime = get_timer_masked () + tmo;
do {
ulong now = get_timer_masked ();
diff = endtime - now;
} while (diff >= 0);
}
#elif defined(CONFIG_S3C4510B)
ulong get_timer (ulong base)
{
return timestamp - base;
}
void __udelay (unsigned long usec)
{
u32 ticks;
ticks = (usec * CONFIG_SYS_HZ) / 1000000;
ticks += get_timer (0);
while (get_timer (0) < ticks)
/*NOP*/;
}
#elif defined(CONFIG_INTEGRATOR) && defined(CONFIG_ARCH_INTEGRATOR)
/* No timer routines for IntegratorAP/CM720T as yet */
#else
#error Timer routines not defined for this CPU type
#endif
|
hschauhan/xvisor-uboot
|
arch/arm/cpu/arm720t/interrupts.c
|
C
|
gpl-2.0
| 7,066
|
class AdministradorsController < ApplicationController
def index
if session[:usuario] == nil then
render :'app_principal/login'
return
end
@admin_activo = "active open"
@admin_revisar_activo = "active"
@btnBarraAdmin = true
@titulo = "Gestión de administradores"
@admins = Administrador.all
end
def perfil
if session[:usuario] == nil then
render :'app_principal/login'
return
end
@titulo = "Editar perfil"
@admin = Administrador.find(session[:usuario]["id"])
@admin_activo = "active open"
end
def new
if session[:usuario] == nil then
render :'app_principal/login'
return
end
@admin_activo = "active open"
@admin_n_activo = "active"
@titulo = "Nuevo administrador del sitio"
@resume = Administrador.new
end
def create
if session[:usuario] == nil then
render :'app_principal/login'
return
end
@resume = Administrador.new(administrador_params)
@admin_activo = "active open"
@admin_n_activo = "active"
if @resume.save
@titulo = "Nuevo administrador del sitio"
@notif = true
render "new"
else
render "new"
end
end
def destroy
end
def editar
if session[:usuario] == nil then
render :'app_principal/login'
return
end
@titulo = "Editar administrador"
@admin = Administrador.find(params[:id])
@admin_activo = "active open"
end
def editarPOST
if session[:usuario] == nil then
render :'app_principal/login'
return
end
@admin = Administrador.find(params[:administrador]["id"])
@admin.avatar = params[:administrador]["avatar"]
@admin.nombres = params[:administrador]["nombres"]
@admin.usuario = params[:administrador]["usuario"]
@admin.apellidos = params[:administrador]["apellidos"]
if params[:administrador]["es_super_usuario"] then
@admin.es_super_usuario = params[:administrador]["es_super_usuario"]
end
@admin_activo = "active open"
if @admin.save
@titulo = "Editar administrador"
@notif = true
@admin = Administrador.find(params[:administrador]["id"])
if @admin.id == session[:usuario]["id"] then
session[:usuario]["nombres"] = @admin.nombres + " " + @admin.apellidos
session[:usuario]["avatar"] = @admin.avatar_url
session[:usuario]["es_super"] = @admin.es_super_usuario
end
render :editar
else
render "editar"
end
end
def editarperfil
if session[:usuario] == nil then
render :'app_principal/login'
return
end
@admin = Administrador.find(params[:administrador]["id"])
@admin.avatar = params[:administrador]["avatar"]
@admin.nombres = params[:administrador]["nombres"]
@admin.usuario = params[:administrador]["usuario"]
@admin.apellidos = params[:administrador]["apellidos"]
if params[:administrador]["es_super_usuario"] then
@admin.es_super_usuario = params[:administrador]["es_super_usuario"]
end
@admin_activo = "active open"
if @admin.save
@notif = true
if @admin.id == session[:usuario]["id"] then
session[:usuario]["nombres"] = @admin.nombres + " " + @admin.apellidos
session[:usuario]["avatar"] = @admin.avatar_url
session[:usuario]["es_super"] = @admin.es_super_usuario
end
render :perfil
else
redirect_to "administrador/perfil"
end
end
def eliminar
if session[:usuario] == nil then
render :'app_principal/login'
return
end
@titulo = "Gestión de administradores"
@admin = Administrador.find(params[:id])
@admin.delete()
@admins = Administrador.all
@notifeliminar = true
@btnBarraAdmin = true
@admin_activo = "active open"
@admin_n_activo = "active"
render :index
end
def password
if session[:usuario] == nil then
render :'app_principal/login'
return
end
@admin = Administrador.find(params[:idadmin])
if params[:passAnterior] == @admin.password then
@admin.password = params[:passNueva]
@admin.save()
@titulo = "Editar perfil"
@notifok = true
render :editar
else
@titulo = "Editar perfil"
@notiferror = true
render :editar
end
end
private
def administrador_params
params.require(:administrador).permit(:avatar, :usuario, :password, :nombres, :apellidos, :es_super_usuario)
end
end
|
mawich07/dakar
|
app/controllers/administradors_controller.rb
|
Ruby
|
gpl-2.0
| 4,460
|
/*
* Linux INET6 implementation
* FIB front-end.
*
* Authors:
* Pedro Roque <roque@di.fc.ul.pt>
*
* 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.
*/
/* Changes:
*
* YOSHIFUJI Hideaki @USAGI
* reworked default router selection.
* - respect outgoing interface
* - select from (probably) reachable routers (i.e.
* routers in REACHABLE, STALE, DELAY or PROBE states).
* - always select the same router if it is (probably)
* reachable. otherwise, round-robin the list.
* Ville Nuorvala
* Fixed routing subtrees.
*/
#define pr_fmt(fmt) "IPv6: " fmt
#include <linux/capability.h>
#include <linux/errno.h>
#include <linux/export.h>
#include <linux/types.h>
#include <linux/times.h>
#include <linux/socket.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/route.h>
#include <linux/netdevice.h>
#include <linux/in6.h>
#include <linux/mroute6.h>
#include <linux/init.h>
#include <linux/if_arp.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/nsproxy.h>
#include <linux/slab.h>
#include <net/net_namespace.h>
#include <net/snmp.h>
#include <net/ipv6.h>
#include <net/ip6_fib.h>
#include <net/ip6_route.h>
#include <net/ndisc.h>
#include <net/addrconf.h>
#include <net/tcp.h>
#include <linux/rtnetlink.h>
#include <net/dst.h>
#include <net/xfrm.h>
#include <net/netevent.h>
#include <net/netlink.h>
#include <net/nexthop.h>
#include <asm/uaccess.h>
#ifdef CONFIG_SYSCTL
#include <linux/sysctl.h>
#endif
static struct rt6_info *ip6_rt_copy(struct rt6_info *ort,
const struct in6_addr *dest);
static struct dst_entry *ip6_dst_check(struct dst_entry *dst, u32 cookie);
static unsigned int ip6_default_advmss(const struct dst_entry *dst);
static unsigned int ip6_mtu(const struct dst_entry *dst);
static struct dst_entry *ip6_negative_advice(struct dst_entry *);
static void ip6_dst_destroy(struct dst_entry *);
static void ip6_dst_ifdown(struct dst_entry *,
struct net_device *dev, int how);
static int ip6_dst_gc(struct dst_ops *ops);
static int ip6_pkt_discard(struct sk_buff *skb);
static int ip6_pkt_discard_out(struct sk_buff *skb);
static void ip6_link_failure(struct sk_buff *skb);
static void ip6_rt_update_pmtu(struct dst_entry *dst, struct sock *sk,
struct sk_buff *skb, u32 mtu);
static void rt6_do_redirect(struct dst_entry *dst, struct sock *sk,
struct sk_buff *skb);
#ifdef CONFIG_IPV6_ROUTE_INFO
static struct rt6_info *rt6_add_route_info(struct net *net,
const struct in6_addr *prefix, int prefixlen,
const struct in6_addr *gwaddr, int ifindex,
unsigned int pref);
static struct rt6_info *rt6_get_route_info(struct net *net,
const struct in6_addr *prefix, int prefixlen,
const struct in6_addr *gwaddr, int ifindex);
#endif
static u32 *ipv6_cow_metrics(struct dst_entry *dst, unsigned long old)
{
struct rt6_info *rt = (struct rt6_info *) dst;
struct inet_peer *peer;
u32 *p = NULL;
if (!(rt->dst.flags & DST_HOST))
return NULL;
peer = rt6_get_peer_create(rt);
if (peer) {
u32 *old_p = __DST_METRICS_PTR(old);
unsigned long prev, new;
p = peer->metrics;
if (inet_metrics_new(peer))
memcpy(p, old_p, sizeof(u32) * RTAX_MAX);
new = (unsigned long) p;
prev = cmpxchg(&dst->_metrics, old, new);
if (prev != old) {
p = __DST_METRICS_PTR(prev);
if (prev & DST_METRICS_READ_ONLY)
p = NULL;
}
}
return p;
}
static inline const void *choose_neigh_daddr(struct rt6_info *rt,
struct sk_buff *skb,
const void *daddr)
{
struct in6_addr *p = &rt->rt6i_gateway;
if (!ipv6_addr_any(p))
return (const void *) p;
else if (skb)
return &ipv6_hdr(skb)->daddr;
return daddr;
}
static struct neighbour *ip6_neigh_lookup(const struct dst_entry *dst,
struct sk_buff *skb,
const void *daddr)
{
struct rt6_info *rt = (struct rt6_info *) dst;
struct neighbour *n;
daddr = choose_neigh_daddr(rt, skb, daddr);
n = __ipv6_neigh_lookup(&nd_tbl, dst->dev, daddr);
if (n)
return n;
return neigh_create(&nd_tbl, daddr, dst->dev);
}
static int rt6_bind_neighbour(struct rt6_info *rt, struct net_device *dev)
{
struct neighbour *n = __ipv6_neigh_lookup(&nd_tbl, dev, &rt->rt6i_gateway);
if (!n) {
n = neigh_create(&nd_tbl, &rt->rt6i_gateway, dev);
if (IS_ERR(n))
return PTR_ERR(n);
}
rt->n = n;
return 0;
}
static struct dst_ops ip6_dst_ops_template = {
.family = AF_INET6,
.protocol = cpu_to_be16(ETH_P_IPV6),
.gc = ip6_dst_gc,
.gc_thresh = 1024,
.check = ip6_dst_check,
.default_advmss = ip6_default_advmss,
.mtu = ip6_mtu,
.cow_metrics = ipv6_cow_metrics,
.destroy = ip6_dst_destroy,
.ifdown = ip6_dst_ifdown,
.negative_advice = ip6_negative_advice,
.link_failure = ip6_link_failure,
.update_pmtu = ip6_rt_update_pmtu,
.redirect = rt6_do_redirect,
.local_out = __ip6_local_out,
.neigh_lookup = ip6_neigh_lookup,
};
static unsigned int ip6_blackhole_mtu(const struct dst_entry *dst)
{
unsigned int mtu = dst_metric_raw(dst, RTAX_MTU);
return mtu ? : dst->dev->mtu;
}
static void ip6_rt_blackhole_update_pmtu(struct dst_entry *dst, struct sock *sk,
struct sk_buff *skb, u32 mtu)
{
}
static void ip6_rt_blackhole_redirect(struct dst_entry *dst, struct sock *sk,
struct sk_buff *skb)
{
}
static u32 *ip6_rt_blackhole_cow_metrics(struct dst_entry *dst,
unsigned long old)
{
return NULL;
}
static struct dst_ops ip6_dst_blackhole_ops = {
.family = AF_INET6,
.protocol = cpu_to_be16(ETH_P_IPV6),
.destroy = ip6_dst_destroy,
.check = ip6_dst_check,
.mtu = ip6_blackhole_mtu,
.default_advmss = ip6_default_advmss,
.update_pmtu = ip6_rt_blackhole_update_pmtu,
.redirect = ip6_rt_blackhole_redirect,
.cow_metrics = ip6_rt_blackhole_cow_metrics,
.neigh_lookup = ip6_neigh_lookup,
};
static const u32 ip6_template_metrics[RTAX_MAX] = {
[RTAX_HOPLIMIT - 1] = 0,
};
static const struct rt6_info ip6_null_entry_template = {
.dst = {
.__refcnt = ATOMIC_INIT(1),
.__use = 1,
.obsolete = DST_OBSOLETE_FORCE_CHK,
.error = -ENETUNREACH,
.input = ip6_pkt_discard,
.output = ip6_pkt_discard_out,
},
.rt6i_flags = (RTF_REJECT | RTF_NONEXTHOP),
.rt6i_protocol = RTPROT_KERNEL,
.rt6i_metric = ~(u32) 0,
.rt6i_ref = ATOMIC_INIT(1),
};
#ifdef CONFIG_IPV6_MULTIPLE_TABLES
static int ip6_pkt_prohibit(struct sk_buff *skb);
static int ip6_pkt_prohibit_out(struct sk_buff *skb);
static const struct rt6_info ip6_prohibit_entry_template = {
.dst = {
.__refcnt = ATOMIC_INIT(1),
.__use = 1,
.obsolete = DST_OBSOLETE_FORCE_CHK,
.error = -EACCES,
.input = ip6_pkt_prohibit,
.output = ip6_pkt_prohibit_out,
},
.rt6i_flags = (RTF_REJECT | RTF_NONEXTHOP),
.rt6i_protocol = RTPROT_KERNEL,
.rt6i_metric = ~(u32) 0,
.rt6i_ref = ATOMIC_INIT(1),
};
static const struct rt6_info ip6_blk_hole_entry_template = {
.dst = {
.__refcnt = ATOMIC_INIT(1),
.__use = 1,
.obsolete = DST_OBSOLETE_FORCE_CHK,
.error = -EINVAL,
.input = dst_discard,
.output = dst_discard,
},
.rt6i_flags = (RTF_REJECT | RTF_NONEXTHOP),
.rt6i_protocol = RTPROT_KERNEL,
.rt6i_metric = ~(u32) 0,
.rt6i_ref = ATOMIC_INIT(1),
};
#endif
/* allocate dst with ip6_dst_ops */
static inline struct rt6_info *ip6_dst_alloc(struct net *net,
struct net_device *dev,
int flags,
struct fib6_table *table)
{
struct rt6_info *rt = dst_alloc(&net->ipv6.ip6_dst_ops, dev,
0, DST_OBSOLETE_FORCE_CHK, flags);
if (rt) {
struct dst_entry *dst = &rt->dst;
memset(dst + 1, 0, sizeof(*rt) - sizeof(*dst));
rt6_init_peer(rt, table ? &table->tb6_peers : net->ipv6.peers);
rt->rt6i_genid = rt_genid(net);
INIT_LIST_HEAD(&rt->rt6i_siblings);
rt->rt6i_nsiblings = 0;
}
return rt;
}
static void ip6_dst_destroy(struct dst_entry *dst)
{
struct rt6_info *rt = (struct rt6_info *)dst;
struct inet6_dev *idev = rt->rt6i_idev;
struct dst_entry *from = dst->from;
if (rt->n)
neigh_release(rt->n);
if (!(rt->dst.flags & DST_HOST))
dst_destroy_metrics_generic(dst);
if (idev) {
rt->rt6i_idev = NULL;
in6_dev_put(idev);
}
dst->from = NULL;
dst_release(from);
if (rt6_has_peer(rt)) {
struct inet_peer *peer = rt6_peer_ptr(rt);
inet_putpeer(peer);
}
}
void rt6_bind_peer(struct rt6_info *rt, int create)
{
struct inet_peer_base *base;
struct inet_peer *peer;
base = inetpeer_base_ptr(rt->_rt6i_peer);
if (!base)
return;
peer = inet_getpeer_v6(base, &rt->rt6i_dst.addr, create);
if (peer) {
if (!rt6_set_peer(rt, peer))
inet_putpeer(peer);
}
}
static void ip6_dst_ifdown(struct dst_entry *dst, struct net_device *dev,
int how)
{
struct rt6_info *rt = (struct rt6_info *)dst;
struct inet6_dev *idev = rt->rt6i_idev;
struct net_device *loopback_dev =
dev_net(dev)->loopback_dev;
if (dev != loopback_dev) {
if (idev && idev->dev == dev) {
struct inet6_dev *loopback_idev =
in6_dev_get(loopback_dev);
if (loopback_idev) {
rt->rt6i_idev = loopback_idev;
in6_dev_put(idev);
}
}
if (rt->n && rt->n->dev == dev) {
rt->n->dev = loopback_dev;
dev_hold(loopback_dev);
dev_put(dev);
}
}
}
static bool rt6_check_expired(const struct rt6_info *rt)
{
if (rt->rt6i_flags & RTF_EXPIRES) {
if (time_after(jiffies, rt->dst.expires))
return true;
} else if (rt->dst.from) {
return rt6_check_expired((struct rt6_info *) rt->dst.from);
}
return false;
}
static bool rt6_need_strict(const struct in6_addr *daddr)
{
return ipv6_addr_type(daddr) &
(IPV6_ADDR_MULTICAST | IPV6_ADDR_LINKLOCAL | IPV6_ADDR_LOOPBACK);
}
/* Multipath route selection:
* Hash based function using packet header and flowlabel.
* Adapted from fib_info_hashfn()
*/
static int rt6_info_hash_nhsfn(unsigned int candidate_count,
const struct flowi6 *fl6)
{
unsigned int val = fl6->flowi6_proto;
val ^= (__force u32)fl6->daddr.s6_addr32[0];
val ^= (__force u32)fl6->daddr.s6_addr32[1];
val ^= (__force u32)fl6->daddr.s6_addr32[2];
val ^= (__force u32)fl6->daddr.s6_addr32[3];
val ^= (__force u32)fl6->saddr.s6_addr32[0];
val ^= (__force u32)fl6->saddr.s6_addr32[1];
val ^= (__force u32)fl6->saddr.s6_addr32[2];
val ^= (__force u32)fl6->saddr.s6_addr32[3];
/* Work only if this not encapsulated */
switch (fl6->flowi6_proto) {
case IPPROTO_UDP:
case IPPROTO_TCP:
case IPPROTO_SCTP:
val ^= (__force u16)fl6->fl6_sport;
val ^= (__force u16)fl6->fl6_dport;
break;
case IPPROTO_ICMPV6:
val ^= (__force u16)fl6->fl6_icmp_type;
val ^= (__force u16)fl6->fl6_icmp_code;
break;
}
/* RFC6438 recommands to use flowlabel */
val ^= (__force u32)fl6->flowlabel;
/* Perhaps, we need to tune, this function? */
val = val ^ (val >> 7) ^ (val >> 12);
return val % candidate_count;
}
static struct rt6_info *rt6_multipath_select(struct rt6_info *match,
struct flowi6 *fl6)
{
struct rt6_info *sibling, *next_sibling;
int route_choosen;
route_choosen = rt6_info_hash_nhsfn(match->rt6i_nsiblings + 1, fl6);
/* Don't change the route, if route_choosen == 0
* (siblings does not include ourself)
*/
if (route_choosen)
list_for_each_entry_safe(sibling, next_sibling,
&match->rt6i_siblings, rt6i_siblings) {
route_choosen--;
if (route_choosen == 0) {
match = sibling;
break;
}
}
return match;
}
/*
* Route lookup. Any table->tb6_lock is implied.
*/
static inline struct rt6_info *rt6_device_match(struct net *net,
struct rt6_info *rt,
const struct in6_addr *saddr,
int oif,
int flags)
{
struct rt6_info *local = NULL;
struct rt6_info *sprt;
if (!oif && ipv6_addr_any(saddr))
goto out;
for (sprt = rt; sprt; sprt = sprt->dst.rt6_next) {
struct net_device *dev = sprt->dst.dev;
if (oif) {
if (dev->ifindex == oif)
return sprt;
if (dev->flags & IFF_LOOPBACK) {
if (!sprt->rt6i_idev ||
sprt->rt6i_idev->dev->ifindex != oif) {
if (flags & RT6_LOOKUP_F_IFACE && oif)
continue;
if (local && (!oif ||
local->rt6i_idev->dev->ifindex == oif))
continue;
}
local = sprt;
}
} else {
if (ipv6_chk_addr(net, saddr, dev,
flags & RT6_LOOKUP_F_IFACE))
return sprt;
}
}
if (oif) {
if (local)
return local;
if (flags & RT6_LOOKUP_F_IFACE)
return net->ipv6.ip6_null_entry;
}
out:
return rt;
}
#ifdef CONFIG_IPV6_ROUTER_PREF
static void rt6_probe(struct rt6_info *rt)
{
struct neighbour *neigh;
/*
* Okay, this does not seem to be appropriate
* for now, however, we need to check if it
* is really so; aka Router Reachability Probing.
*
* Router Reachability Probe MUST be rate-limited
* to no more than one per minute.
*/
neigh = rt ? rt->n : NULL;
if (!neigh || (neigh->nud_state & NUD_VALID))
return;
read_lock_bh(&neigh->lock);
if (!(neigh->nud_state & NUD_VALID) &&
time_after(jiffies, neigh->updated + rt->rt6i_idev->cnf.rtr_probe_interval)) {
struct in6_addr mcaddr;
struct in6_addr *target;
neigh->updated = jiffies;
read_unlock_bh(&neigh->lock);
target = (struct in6_addr *)&neigh->primary_key;
addrconf_addr_solict_mult(target, &mcaddr);
ndisc_send_ns(rt->dst.dev, NULL, target, &mcaddr, NULL);
} else {
read_unlock_bh(&neigh->lock);
}
}
#else
static inline void rt6_probe(struct rt6_info *rt)
{
}
#endif
/*
* Default Router Selection (RFC 2461 6.3.6)
*/
static inline int rt6_check_dev(struct rt6_info *rt, int oif)
{
struct net_device *dev = rt->dst.dev;
if (!oif || dev->ifindex == oif)
return 2;
if ((dev->flags & IFF_LOOPBACK) &&
rt->rt6i_idev && rt->rt6i_idev->dev->ifindex == oif)
return 1;
return 0;
}
static inline bool rt6_check_neigh(struct rt6_info *rt)
{
struct neighbour *neigh;
bool ret = false;
neigh = rt->n;
if (rt->rt6i_flags & RTF_NONEXTHOP ||
!(rt->rt6i_flags & RTF_GATEWAY))
ret = true;
else if (neigh) {
read_lock_bh(&neigh->lock);
if (neigh->nud_state & NUD_VALID)
ret = true;
#ifdef CONFIG_IPV6_ROUTER_PREF
else if (!(neigh->nud_state & NUD_FAILED))
ret = true;
#endif
read_unlock_bh(&neigh->lock);
}
return ret;
}
static int rt6_score_route(struct rt6_info *rt, int oif,
int strict)
{
int m;
m = rt6_check_dev(rt, oif);
if (!m && (strict & RT6_LOOKUP_F_IFACE))
return -1;
#ifdef CONFIG_IPV6_ROUTER_PREF
m |= IPV6_DECODE_PREF(IPV6_EXTRACT_PREF(rt->rt6i_flags)) << 2;
#endif
if (!rt6_check_neigh(rt) && (strict & RT6_LOOKUP_F_REACHABLE))
return -1;
return m;
}
static struct rt6_info *find_match(struct rt6_info *rt, int oif, int strict,
int *mpri, struct rt6_info *match)
{
int m;
if (rt6_check_expired(rt))
goto out;
m = rt6_score_route(rt, oif, strict);
if (m < 0)
goto out;
if (m > *mpri) {
if (strict & RT6_LOOKUP_F_REACHABLE)
rt6_probe(match);
*mpri = m;
match = rt;
} else if (strict & RT6_LOOKUP_F_REACHABLE) {
rt6_probe(rt);
}
out:
return match;
}
static struct rt6_info *find_rr_leaf(struct fib6_node *fn,
struct rt6_info *rr_head,
u32 metric, int oif, int strict)
{
struct rt6_info *rt, *match;
int mpri = -1;
match = NULL;
for (rt = rr_head; rt && rt->rt6i_metric == metric;
rt = rt->dst.rt6_next)
match = find_match(rt, oif, strict, &mpri, match);
for (rt = fn->leaf; rt && rt != rr_head && rt->rt6i_metric == metric;
rt = rt->dst.rt6_next)
match = find_match(rt, oif, strict, &mpri, match);
return match;
}
static struct rt6_info *rt6_select(struct fib6_node *fn, int oif, int strict)
{
struct rt6_info *match, *rt0;
struct net *net;
rt0 = fn->rr_ptr;
if (!rt0)
fn->rr_ptr = rt0 = fn->leaf;
match = find_rr_leaf(fn, rt0, rt0->rt6i_metric, oif, strict);
if (!match &&
(strict & RT6_LOOKUP_F_REACHABLE)) {
struct rt6_info *next = rt0->dst.rt6_next;
/* no entries matched; do round-robin */
if (!next || next->rt6i_metric != rt0->rt6i_metric)
next = fn->leaf;
if (next != rt0)
fn->rr_ptr = next;
}
net = dev_net(rt0->dst.dev);
return match ? match : net->ipv6.ip6_null_entry;
}
#ifdef CONFIG_IPV6_ROUTE_INFO
int rt6_route_rcv(struct net_device *dev, u8 *opt, int len,
const struct in6_addr *gwaddr)
{
struct net *net = dev_net(dev);
struct route_info *rinfo = (struct route_info *) opt;
struct in6_addr prefix_buf, *prefix;
unsigned int pref;
unsigned long lifetime;
struct rt6_info *rt;
if (len < sizeof(struct route_info)) {
return -EINVAL;
}
/* Sanity check for prefix_len and length */
if (rinfo->length > 3) {
return -EINVAL;
} else if (rinfo->prefix_len > 128) {
return -EINVAL;
} else if (rinfo->prefix_len > 64) {
if (rinfo->length < 2) {
return -EINVAL;
}
} else if (rinfo->prefix_len > 0) {
if (rinfo->length < 1) {
return -EINVAL;
}
}
pref = rinfo->route_pref;
if (pref == ICMPV6_ROUTER_PREF_INVALID)
return -EINVAL;
lifetime = addrconf_timeout_fixup(ntohl(rinfo->lifetime), HZ);
if (rinfo->length == 3)
prefix = (struct in6_addr *)rinfo->prefix;
else {
/* this function is safe */
ipv6_addr_prefix(&prefix_buf,
(struct in6_addr *)rinfo->prefix,
rinfo->prefix_len);
prefix = &prefix_buf;
}
rt = rt6_get_route_info(net, prefix, rinfo->prefix_len, gwaddr,
dev->ifindex);
if (rt && !lifetime) {
ip6_del_rt(rt);
rt = NULL;
}
if (!rt && lifetime)
rt = rt6_add_route_info(net, prefix, rinfo->prefix_len, gwaddr, dev->ifindex,
pref);
else if (rt)
rt->rt6i_flags = RTF_ROUTEINFO |
(rt->rt6i_flags & ~RTF_PREF_MASK) | RTF_PREF(pref);
if (rt) {
if (!addrconf_finite_timeout(lifetime))
rt6_clean_expires(rt);
else
rt6_set_expires(rt, jiffies + HZ * lifetime);
ip6_rt_put(rt);
}
return 0;
}
#endif
#define BACKTRACK(__net, saddr) \
do { \
if (rt == __net->ipv6.ip6_null_entry) { \
struct fib6_node *pn; \
while (1) { \
if (fn->fn_flags & RTN_TL_ROOT) \
goto out; \
pn = fn->parent; \
if (FIB6_SUBTREE(pn) && FIB6_SUBTREE(pn) != fn) \
fn = fib6_lookup(FIB6_SUBTREE(pn), NULL, saddr); \
else \
fn = pn; \
if (fn->fn_flags & RTN_RTINFO) \
goto restart; \
} \
} \
} while (0)
static struct rt6_info *ip6_pol_route_lookup(struct net *net,
struct fib6_table *table,
struct flowi6 *fl6, int flags)
{
struct fib6_node *fn;
struct rt6_info *rt;
read_lock_bh(&table->tb6_lock);
fn = fib6_lookup(&table->tb6_root, &fl6->daddr, &fl6->saddr);
restart:
rt = fn->leaf;
rt = rt6_device_match(net, rt, &fl6->saddr, fl6->flowi6_oif, flags);
if (rt->rt6i_nsiblings && fl6->flowi6_oif == 0)
rt = rt6_multipath_select(rt, fl6);
BACKTRACK(net, &fl6->saddr);
out:
dst_use(&rt->dst, jiffies);
read_unlock_bh(&table->tb6_lock);
return rt;
}
struct dst_entry * ip6_route_lookup(struct net *net, struct flowi6 *fl6,
int flags)
{
return fib6_rule_lookup(net, fl6, flags, ip6_pol_route_lookup);
}
EXPORT_SYMBOL_GPL(ip6_route_lookup);
struct rt6_info *rt6_lookup(struct net *net, const struct in6_addr *daddr,
const struct in6_addr *saddr, int oif, int strict)
{
struct flowi6 fl6 = {
.flowi6_oif = oif,
.daddr = *daddr,
};
struct dst_entry *dst;
int flags = strict ? RT6_LOOKUP_F_IFACE : 0;
if (saddr) {
memcpy(&fl6.saddr, saddr, sizeof(*saddr));
flags |= RT6_LOOKUP_F_HAS_SADDR;
}
dst = fib6_rule_lookup(net, &fl6, flags, ip6_pol_route_lookup);
if (dst->error == 0)
return (struct rt6_info *) dst;
dst_release(dst);
return NULL;
}
EXPORT_SYMBOL(rt6_lookup);
/* ip6_ins_rt is called with FREE table->tb6_lock.
It takes new route entry, the addition fails by any reason the
route is freed. In any case, if caller does not hold it, it may
be destroyed.
*/
static int __ip6_ins_rt(struct rt6_info *rt, struct nl_info *info)
{
int err;
struct fib6_table *table;
table = rt->rt6i_table;
write_lock_bh(&table->tb6_lock);
err = fib6_add(&table->tb6_root, rt, info);
write_unlock_bh(&table->tb6_lock);
return err;
}
int ip6_ins_rt(struct rt6_info *rt)
{
struct nl_info info = {
.nl_net = dev_net(rt->dst.dev),
};
return __ip6_ins_rt(rt, &info);
}
static struct rt6_info *rt6_alloc_cow(struct rt6_info *ort,
const struct in6_addr *daddr,
const struct in6_addr *saddr)
{
struct rt6_info *rt;
/*
* Clone the route.
*/
rt = ip6_rt_copy(ort, daddr);
if (rt) {
int attempts = !in_softirq();
if (!(rt->rt6i_flags & RTF_GATEWAY)) {
if (ort->rt6i_dst.plen != 128 &&
ipv6_addr_equal(&ort->rt6i_dst.addr, daddr))
rt->rt6i_flags |= RTF_ANYCAST;
rt->rt6i_gateway = *daddr;
}
rt->rt6i_flags |= RTF_CACHE;
#ifdef CONFIG_IPV6_SUBTREES
if (rt->rt6i_src.plen && saddr) {
rt->rt6i_src.addr = *saddr;
rt->rt6i_src.plen = 128;
}
#endif
retry:
if (rt6_bind_neighbour(rt, rt->dst.dev)) {
struct net *net = dev_net(rt->dst.dev);
int saved_rt_min_interval =
net->ipv6.sysctl.ip6_rt_gc_min_interval;
int saved_rt_elasticity =
net->ipv6.sysctl.ip6_rt_gc_elasticity;
if (attempts-- > 0) {
net->ipv6.sysctl.ip6_rt_gc_elasticity = 1;
net->ipv6.sysctl.ip6_rt_gc_min_interval = 0;
ip6_dst_gc(&net->ipv6.ip6_dst_ops);
net->ipv6.sysctl.ip6_rt_gc_elasticity =
saved_rt_elasticity;
net->ipv6.sysctl.ip6_rt_gc_min_interval =
saved_rt_min_interval;
goto retry;
}
net_warn_ratelimited("Neighbour table overflow\n");
dst_free(&rt->dst);
return NULL;
}
}
return rt;
}
static struct rt6_info *rt6_alloc_clone(struct rt6_info *ort,
const struct in6_addr *daddr)
{
struct rt6_info *rt = ip6_rt_copy(ort, daddr);
if (rt) {
rt->rt6i_flags |= RTF_CACHE;
rt->n = neigh_clone(ort->n);
}
return rt;
}
static struct rt6_info *ip6_pol_route(struct net *net, struct fib6_table *table, int oif,
struct flowi6 *fl6, int flags)
{
struct fib6_node *fn;
struct rt6_info *rt, *nrt;
int strict = 0;
int attempts = 3;
int err;
int reachable = net->ipv6.devconf_all->forwarding ? 0 : RT6_LOOKUP_F_REACHABLE;
strict |= flags & RT6_LOOKUP_F_IFACE;
relookup:
read_lock_bh(&table->tb6_lock);
restart_2:
fn = fib6_lookup(&table->tb6_root, &fl6->daddr, &fl6->saddr);
restart:
rt = rt6_select(fn, oif, strict | reachable);
if (rt->rt6i_nsiblings && oif == 0)
rt = rt6_multipath_select(rt, fl6);
BACKTRACK(net, &fl6->saddr);
if (rt == net->ipv6.ip6_null_entry ||
rt->rt6i_flags & RTF_CACHE)
goto out;
dst_hold(&rt->dst);
read_unlock_bh(&table->tb6_lock);
if (!rt->n && !(rt->rt6i_flags & (RTF_NONEXTHOP | RTF_LOCAL)))
nrt = rt6_alloc_cow(rt, &fl6->daddr, &fl6->saddr);
else if (!(rt->dst.flags & DST_HOST))
nrt = rt6_alloc_clone(rt, &fl6->daddr);
else
goto out2;
ip6_rt_put(rt);
rt = nrt ? : net->ipv6.ip6_null_entry;
dst_hold(&rt->dst);
if (nrt) {
err = ip6_ins_rt(nrt);
if (!err)
goto out2;
}
if (--attempts <= 0)
goto out2;
/*
* Race condition! In the gap, when table->tb6_lock was
* released someone could insert this route. Relookup.
*/
ip6_rt_put(rt);
goto relookup;
out:
if (reachable) {
reachable = 0;
goto restart_2;
}
dst_hold(&rt->dst);
read_unlock_bh(&table->tb6_lock);
out2:
rt->dst.lastuse = jiffies;
rt->dst.__use++;
return rt;
}
static struct rt6_info *ip6_pol_route_input(struct net *net, struct fib6_table *table,
struct flowi6 *fl6, int flags)
{
return ip6_pol_route(net, table, fl6->flowi6_iif, fl6, flags);
}
static struct dst_entry *ip6_route_input_lookup(struct net *net,
struct net_device *dev,
struct flowi6 *fl6, int flags)
{
if (rt6_need_strict(&fl6->daddr) && dev->type != ARPHRD_PIMREG)
flags |= RT6_LOOKUP_F_IFACE;
return fib6_rule_lookup(net, fl6, flags, ip6_pol_route_input);
}
void ip6_route_input(struct sk_buff *skb)
{
const struct ipv6hdr *iph = ipv6_hdr(skb);
struct net *net = dev_net(skb->dev);
int flags = RT6_LOOKUP_F_HAS_SADDR;
struct flowi6 fl6 = {
.flowi6_iif = skb->dev->ifindex,
.daddr = iph->daddr,
.saddr = iph->saddr,
.flowlabel = (* (__be32 *) iph) & IPV6_FLOWINFO_MASK,
.flowi6_mark = skb->mark,
.flowi6_proto = iph->nexthdr,
};
skb_dst_set(skb, ip6_route_input_lookup(net, skb->dev, &fl6, flags));
}
static struct rt6_info *ip6_pol_route_output(struct net *net, struct fib6_table *table,
struct flowi6 *fl6, int flags)
{
return ip6_pol_route(net, table, fl6->flowi6_oif, fl6, flags);
}
struct dst_entry * ip6_route_output(struct net *net, const struct sock *sk,
struct flowi6 *fl6)
{
int flags = 0;
fl6->flowi6_iif = LOOPBACK_IFINDEX;
if ((sk && sk->sk_bound_dev_if) || rt6_need_strict(&fl6->daddr))
flags |= RT6_LOOKUP_F_IFACE;
if (!ipv6_addr_any(&fl6->saddr))
flags |= RT6_LOOKUP_F_HAS_SADDR;
else if (sk)
flags |= rt6_srcprefs2flags(inet6_sk(sk)->srcprefs);
return fib6_rule_lookup(net, fl6, flags, ip6_pol_route_output);
}
EXPORT_SYMBOL(ip6_route_output);
struct dst_entry *ip6_blackhole_route(struct net *net, struct dst_entry *dst_orig)
{
struct rt6_info *rt, *ort = (struct rt6_info *) dst_orig;
struct dst_entry *new = NULL;
rt = dst_alloc(&ip6_dst_blackhole_ops, ort->dst.dev, 1, DST_OBSOLETE_NONE, 0);
if (rt) {
new = &rt->dst;
memset(new + 1, 0, sizeof(*rt) - sizeof(*new));
rt6_init_peer(rt, net->ipv6.peers);
new->__use = 1;
new->input = dst_discard;
new->output = dst_discard;
if (dst_metrics_read_only(&ort->dst))
new->_metrics = ort->dst._metrics;
else
dst_copy_metrics(new, &ort->dst);
rt->rt6i_idev = ort->rt6i_idev;
if (rt->rt6i_idev)
in6_dev_hold(rt->rt6i_idev);
rt->rt6i_gateway = ort->rt6i_gateway;
rt->rt6i_flags = ort->rt6i_flags;
rt->rt6i_metric = 0;
memcpy(&rt->rt6i_dst, &ort->rt6i_dst, sizeof(struct rt6key));
#ifdef CONFIG_IPV6_SUBTREES
memcpy(&rt->rt6i_src, &ort->rt6i_src, sizeof(struct rt6key));
#endif
dst_free(new);
}
dst_release(dst_orig);
return new ? new : ERR_PTR(-ENOMEM);
}
/*
* Destination cache support functions
*/
static struct dst_entry *ip6_dst_check(struct dst_entry *dst, u32 cookie)
{
struct rt6_info *rt;
rt = (struct rt6_info *) dst;
/* All IPV6 dsts are created with ->obsolete set to the value
* DST_OBSOLETE_FORCE_CHK which forces validation calls down
* into this function always.
*/
if (rt->rt6i_genid != rt_genid(dev_net(rt->dst.dev)))
return NULL;
if (rt->rt6i_node && (rt->rt6i_node->fn_sernum == cookie))
return dst;
return NULL;
}
static struct dst_entry *ip6_negative_advice(struct dst_entry *dst)
{
struct rt6_info *rt = (struct rt6_info *) dst;
if (rt) {
if (rt->rt6i_flags & RTF_CACHE) {
if (rt6_check_expired(rt)) {
ip6_del_rt(rt);
dst = NULL;
}
} else {
dst_release(dst);
dst = NULL;
}
}
return dst;
}
static void ip6_link_failure(struct sk_buff *skb)
{
struct rt6_info *rt;
icmpv6_send(skb, ICMPV6_DEST_UNREACH, ICMPV6_ADDR_UNREACH, 0);
rt = (struct rt6_info *) skb_dst(skb);
if (rt) {
if (rt->rt6i_flags & RTF_CACHE)
rt6_update_expires(rt, 0);
else if (rt->rt6i_node && (rt->rt6i_flags & RTF_DEFAULT))
rt->rt6i_node->fn_sernum = -1;
}
}
static void ip6_rt_update_pmtu(struct dst_entry *dst, struct sock *sk,
struct sk_buff *skb, u32 mtu)
{
struct rt6_info *rt6 = (struct rt6_info*)dst;
dst_confirm(dst);
if (mtu < dst_mtu(dst) && rt6->rt6i_dst.plen == 128) {
struct net *net = dev_net(dst->dev);
rt6->rt6i_flags |= RTF_MODIFIED;
if (mtu < IPV6_MIN_MTU) {
u32 features = dst_metric(dst, RTAX_FEATURES);
mtu = IPV6_MIN_MTU;
features |= RTAX_FEATURE_ALLFRAG;
dst_metric_set(dst, RTAX_FEATURES, features);
}
dst_metric_set(dst, RTAX_MTU, mtu);
rt6_update_expires(rt6, net->ipv6.sysctl.ip6_rt_mtu_expires);
}
}
void ip6_update_pmtu(struct sk_buff *skb, struct net *net, __be32 mtu,
int oif, u32 mark)
{
const struct ipv6hdr *iph = (struct ipv6hdr *) skb->data;
struct dst_entry *dst;
struct flowi6 fl6;
memset(&fl6, 0, sizeof(fl6));
fl6.flowi6_oif = oif;
fl6.flowi6_mark = mark;
fl6.flowi6_flags = 0;
fl6.daddr = iph->daddr;
fl6.saddr = iph->saddr;
fl6.flowlabel = (*(__be32 *) iph) & IPV6_FLOWINFO_MASK;
dst = ip6_route_output(net, NULL, &fl6);
if (!dst->error)
ip6_rt_update_pmtu(dst, NULL, skb, ntohl(mtu));
dst_release(dst);
}
EXPORT_SYMBOL_GPL(ip6_update_pmtu);
void ip6_sk_update_pmtu(struct sk_buff *skb, struct sock *sk, __be32 mtu)
{
ip6_update_pmtu(skb, sock_net(sk), mtu,
sk->sk_bound_dev_if, sk->sk_mark);
}
EXPORT_SYMBOL_GPL(ip6_sk_update_pmtu);
void ip6_redirect(struct sk_buff *skb, struct net *net, int oif, u32 mark)
{
const struct ipv6hdr *iph = (struct ipv6hdr *) skb->data;
struct dst_entry *dst;
struct flowi6 fl6;
memset(&fl6, 0, sizeof(fl6));
fl6.flowi6_oif = oif;
fl6.flowi6_mark = mark;
fl6.flowi6_flags = 0;
fl6.daddr = iph->daddr;
fl6.saddr = iph->saddr;
fl6.flowlabel = (*(__be32 *) iph) & IPV6_FLOWINFO_MASK;
dst = ip6_route_output(net, NULL, &fl6);
if (!dst->error)
rt6_do_redirect(dst, NULL, skb);
dst_release(dst);
}
EXPORT_SYMBOL_GPL(ip6_redirect);
void ip6_sk_redirect(struct sk_buff *skb, struct sock *sk)
{
ip6_redirect(skb, sock_net(sk), sk->sk_bound_dev_if, sk->sk_mark);
}
EXPORT_SYMBOL_GPL(ip6_sk_redirect);
static unsigned int ip6_default_advmss(const struct dst_entry *dst)
{
struct net_device *dev = dst->dev;
unsigned int mtu = dst_mtu(dst);
struct net *net = dev_net(dev);
mtu -= sizeof(struct ipv6hdr) + sizeof(struct tcphdr);
if (mtu < net->ipv6.sysctl.ip6_rt_min_advmss)
mtu = net->ipv6.sysctl.ip6_rt_min_advmss;
/*
* Maximal non-jumbo IPv6 payload is IPV6_MAXPLEN and
* corresponding MSS is IPV6_MAXPLEN - tcp_header_size.
* IPV6_MAXPLEN is also valid and means: "any MSS,
* rely only on pmtu discovery"
*/
if (mtu > IPV6_MAXPLEN - sizeof(struct tcphdr))
mtu = IPV6_MAXPLEN;
return mtu;
}
static unsigned int ip6_mtu(const struct dst_entry *dst)
{
struct inet6_dev *idev;
unsigned int mtu = dst_metric_raw(dst, RTAX_MTU);
if (mtu)
return mtu;
mtu = IPV6_MIN_MTU;
rcu_read_lock();
idev = __in6_dev_get(dst->dev);
if (idev)
mtu = idev->cnf.mtu6;
rcu_read_unlock();
return mtu;
}
static struct dst_entry *icmp6_dst_gc_list;
static DEFINE_SPINLOCK(icmp6_dst_lock);
struct dst_entry *icmp6_dst_alloc(struct net_device *dev,
struct neighbour *neigh,
struct flowi6 *fl6)
{
struct dst_entry *dst;
struct rt6_info *rt;
struct inet6_dev *idev = in6_dev_get(dev);
struct net *net = dev_net(dev);
if (unlikely(!idev))
return ERR_PTR(-ENODEV);
rt = ip6_dst_alloc(net, dev, 0, NULL);
if (unlikely(!rt)) {
in6_dev_put(idev);
dst = ERR_PTR(-ENOMEM);
goto out;
}
if (neigh)
neigh_hold(neigh);
else {
neigh = ip6_neigh_lookup(&rt->dst, NULL, &fl6->daddr);
if (IS_ERR(neigh)) {
in6_dev_put(idev);
dst_free(&rt->dst);
return ERR_CAST(neigh);
}
}
rt->dst.flags |= DST_HOST;
rt->dst.output = ip6_output;
rt->n = neigh;
atomic_set(&rt->dst.__refcnt, 1);
rt->rt6i_dst.addr = fl6->daddr;
rt->rt6i_dst.plen = 128;
rt->rt6i_idev = idev;
dst_metric_set(&rt->dst, RTAX_HOPLIMIT, 0);
spin_lock_bh(&icmp6_dst_lock);
rt->dst.next = icmp6_dst_gc_list;
icmp6_dst_gc_list = &rt->dst;
spin_unlock_bh(&icmp6_dst_lock);
fib6_force_start_gc(net);
dst = xfrm_lookup(net, &rt->dst, flowi6_to_flowi(fl6), NULL, 0);
out:
return dst;
}
int icmp6_dst_gc(void)
{
struct dst_entry *dst, **pprev;
int more = 0;
spin_lock_bh(&icmp6_dst_lock);
pprev = &icmp6_dst_gc_list;
while ((dst = *pprev) != NULL) {
if (!atomic_read(&dst->__refcnt)) {
*pprev = dst->next;
dst_free(dst);
} else {
pprev = &dst->next;
++more;
}
}
spin_unlock_bh(&icmp6_dst_lock);
return more;
}
static void icmp6_clean_all(int (*func)(struct rt6_info *rt, void *arg),
void *arg)
{
struct dst_entry *dst, **pprev;
spin_lock_bh(&icmp6_dst_lock);
pprev = &icmp6_dst_gc_list;
while ((dst = *pprev) != NULL) {
struct rt6_info *rt = (struct rt6_info *) dst;
if (func(rt, arg)) {
*pprev = dst->next;
dst_free(dst);
} else {
pprev = &dst->next;
}
}
spin_unlock_bh(&icmp6_dst_lock);
}
static int ip6_dst_gc(struct dst_ops *ops)
{
unsigned long now = jiffies;
struct net *net = container_of(ops, struct net, ipv6.ip6_dst_ops);
int rt_min_interval = net->ipv6.sysctl.ip6_rt_gc_min_interval;
int rt_max_size = net->ipv6.sysctl.ip6_rt_max_size;
int rt_elasticity = net->ipv6.sysctl.ip6_rt_gc_elasticity;
int rt_gc_timeout = net->ipv6.sysctl.ip6_rt_gc_timeout;
unsigned long rt_last_gc = net->ipv6.ip6_rt_last_gc;
int entries;
entries = dst_entries_get_fast(ops);
if (time_after(rt_last_gc + rt_min_interval, now) &&
entries <= rt_max_size)
goto out;
net->ipv6.ip6_rt_gc_expire++;
fib6_run_gc(net->ipv6.ip6_rt_gc_expire, net);
net->ipv6.ip6_rt_last_gc = now;
entries = dst_entries_get_slow(ops);
if (entries < ops->gc_thresh)
net->ipv6.ip6_rt_gc_expire = rt_gc_timeout>>1;
out:
net->ipv6.ip6_rt_gc_expire -= net->ipv6.ip6_rt_gc_expire>>rt_elasticity;
return entries > rt_max_size;
}
int ip6_dst_hoplimit(struct dst_entry *dst)
{
int hoplimit = dst_metric_raw(dst, RTAX_HOPLIMIT);
if (hoplimit == 0) {
struct net_device *dev = dst->dev;
struct inet6_dev *idev;
rcu_read_lock();
idev = __in6_dev_get(dev);
if (idev)
hoplimit = idev->cnf.hop_limit;
else
hoplimit = dev_net(dev)->ipv6.devconf_all->hop_limit;
rcu_read_unlock();
}
return hoplimit;
}
EXPORT_SYMBOL(ip6_dst_hoplimit);
/*
*
*/
int ip6_route_add(struct fib6_config *cfg)
{
int err;
struct net *net = cfg->fc_nlinfo.nl_net;
struct rt6_info *rt = NULL;
struct net_device *dev = NULL;
struct inet6_dev *idev = NULL;
struct fib6_table *table;
int addr_type;
if (cfg->fc_dst_len > 128 || cfg->fc_src_len > 128)
return -EINVAL;
#ifndef CONFIG_IPV6_SUBTREES
if (cfg->fc_src_len)
return -EINVAL;
#endif
if (cfg->fc_ifindex) {
err = -ENODEV;
dev = dev_get_by_index(net, cfg->fc_ifindex);
if (!dev)
goto out;
idev = in6_dev_get(dev);
if (!idev)
goto out;
}
if (cfg->fc_metric == 0)
cfg->fc_metric = IP6_RT_PRIO_USER;
err = -ENOBUFS;
if (cfg->fc_nlinfo.nlh &&
!(cfg->fc_nlinfo.nlh->nlmsg_flags & NLM_F_CREATE)) {
table = fib6_get_table(net, cfg->fc_table);
if (!table) {
pr_warn("NLM_F_CREATE should be specified when creating new route\n");
table = fib6_new_table(net, cfg->fc_table);
}
} else {
table = fib6_new_table(net, cfg->fc_table);
}
if (!table)
goto out;
rt = ip6_dst_alloc(net, NULL, (cfg->fc_flags & RTF_ADDRCONF) ? 0 : DST_NOCOUNT, table);
if (!rt) {
err = -ENOMEM;
goto out;
}
if (cfg->fc_flags & RTF_EXPIRES)
rt6_set_expires(rt, jiffies +
clock_t_to_jiffies(cfg->fc_expires));
else
rt6_clean_expires(rt);
if (cfg->fc_protocol == RTPROT_UNSPEC)
cfg->fc_protocol = RTPROT_BOOT;
rt->rt6i_protocol = cfg->fc_protocol;
addr_type = ipv6_addr_type(&cfg->fc_dst);
if (addr_type & IPV6_ADDR_MULTICAST)
rt->dst.input = ip6_mc_input;
else if (cfg->fc_flags & RTF_LOCAL)
rt->dst.input = ip6_input;
else
rt->dst.input = ip6_forward;
rt->dst.output = ip6_output;
ipv6_addr_prefix(&rt->rt6i_dst.addr, &cfg->fc_dst, cfg->fc_dst_len);
rt->rt6i_dst.plen = cfg->fc_dst_len;
if (rt->rt6i_dst.plen == 128)
rt->dst.flags |= DST_HOST;
if (!(rt->dst.flags & DST_HOST) && cfg->fc_mx) {
u32 *metrics = kzalloc(sizeof(u32) * RTAX_MAX, GFP_KERNEL);
if (!metrics) {
err = -ENOMEM;
goto out;
}
dst_init_metrics(&rt->dst, metrics, 0);
}
#ifdef CONFIG_IPV6_SUBTREES
ipv6_addr_prefix(&rt->rt6i_src.addr, &cfg->fc_src, cfg->fc_src_len);
rt->rt6i_src.plen = cfg->fc_src_len;
#endif
rt->rt6i_metric = cfg->fc_metric;
/* We cannot add true routes via loopback here,
they would result in kernel looping; promote them to reject routes
*/
if ((cfg->fc_flags & RTF_REJECT) ||
(dev && (dev->flags & IFF_LOOPBACK) &&
!(addr_type & IPV6_ADDR_LOOPBACK) &&
!(cfg->fc_flags & RTF_LOCAL))) {
/* hold loopback dev/idev if we haven't done so. */
if (dev != net->loopback_dev) {
if (dev) {
dev_put(dev);
in6_dev_put(idev);
}
dev = net->loopback_dev;
dev_hold(dev);
idev = in6_dev_get(dev);
if (!idev) {
err = -ENODEV;
goto out;
}
}
rt->dst.output = ip6_pkt_discard_out;
rt->dst.input = ip6_pkt_discard;
rt->rt6i_flags = RTF_REJECT|RTF_NONEXTHOP;
switch (cfg->fc_type) {
case RTN_BLACKHOLE:
rt->dst.error = -EINVAL;
break;
case RTN_PROHIBIT:
rt->dst.error = -EACCES;
break;
case RTN_THROW:
rt->dst.error = -EAGAIN;
break;
default:
rt->dst.error = -ENETUNREACH;
break;
}
goto install_route;
}
if (cfg->fc_flags & RTF_GATEWAY) {
const struct in6_addr *gw_addr;
int gwa_type;
gw_addr = &cfg->fc_gateway;
rt->rt6i_gateway = *gw_addr;
gwa_type = ipv6_addr_type(gw_addr);
if (gwa_type != (IPV6_ADDR_LINKLOCAL|IPV6_ADDR_UNICAST)) {
struct rt6_info *grt;
/* IPv6 strictly inhibits using not link-local
addresses as nexthop address.
Otherwise, router will not able to send redirects.
It is very good, but in some (rare!) circumstances
(SIT, PtP, NBMA NOARP links) it is handy to allow
some exceptions. --ANK
*/
err = -EINVAL;
if (!(gwa_type & IPV6_ADDR_UNICAST))
goto out;
grt = rt6_lookup(net, gw_addr, NULL, cfg->fc_ifindex, 1);
err = -EHOSTUNREACH;
if (!grt)
goto out;
if (dev) {
if (dev != grt->dst.dev) {
ip6_rt_put(grt);
goto out;
}
} else {
dev = grt->dst.dev;
idev = grt->rt6i_idev;
dev_hold(dev);
in6_dev_hold(grt->rt6i_idev);
}
if (!(grt->rt6i_flags & RTF_GATEWAY))
err = 0;
ip6_rt_put(grt);
if (err)
goto out;
}
err = -EINVAL;
if (!dev || (dev->flags & IFF_LOOPBACK))
goto out;
}
err = -ENODEV;
if (!dev)
goto out;
if (!ipv6_addr_any(&cfg->fc_prefsrc)) {
if (!ipv6_chk_addr(net, &cfg->fc_prefsrc, dev, 0)) {
err = -EINVAL;
goto out;
}
rt->rt6i_prefsrc.addr = cfg->fc_prefsrc;
rt->rt6i_prefsrc.plen = 128;
} else
rt->rt6i_prefsrc.plen = 0;
if (cfg->fc_flags & (RTF_GATEWAY | RTF_NONEXTHOP)) {
err = rt6_bind_neighbour(rt, dev);
if (err)
goto out;
}
rt->rt6i_flags = cfg->fc_flags;
install_route:
if (cfg->fc_mx) {
struct nlattr *nla;
int remaining;
nla_for_each_attr(nla, cfg->fc_mx, cfg->fc_mx_len, remaining) {
int type = nla_type(nla);
if (type) {
if (type > RTAX_MAX) {
err = -EINVAL;
goto out;
}
dst_metric_set(&rt->dst, type, nla_get_u32(nla));
}
}
}
rt->dst.dev = dev;
rt->rt6i_idev = idev;
rt->rt6i_table = table;
cfg->fc_nlinfo.nl_net = dev_net(dev);
return __ip6_ins_rt(rt, &cfg->fc_nlinfo);
out:
if (dev)
dev_put(dev);
if (idev)
in6_dev_put(idev);
if (rt)
dst_free(&rt->dst);
return err;
}
static int __ip6_del_rt(struct rt6_info *rt, struct nl_info *info)
{
int err;
struct fib6_table *table;
struct net *net = dev_net(rt->dst.dev);
if (rt == net->ipv6.ip6_null_entry) {
err = -ENOENT;
goto out;
}
table = rt->rt6i_table;
write_lock_bh(&table->tb6_lock);
err = fib6_del(rt, info);
write_unlock_bh(&table->tb6_lock);
out:
ip6_rt_put(rt);
return err;
}
int ip6_del_rt(struct rt6_info *rt)
{
struct nl_info info = {
.nl_net = dev_net(rt->dst.dev),
};
return __ip6_del_rt(rt, &info);
}
static int ip6_route_del(struct fib6_config *cfg)
{
struct fib6_table *table;
struct fib6_node *fn;
struct rt6_info *rt;
int err = -ESRCH;
table = fib6_get_table(cfg->fc_nlinfo.nl_net, cfg->fc_table);
if (!table)
return err;
read_lock_bh(&table->tb6_lock);
fn = fib6_locate(&table->tb6_root,
&cfg->fc_dst, cfg->fc_dst_len,
&cfg->fc_src, cfg->fc_src_len);
if (fn) {
for (rt = fn->leaf; rt; rt = rt->dst.rt6_next) {
if (cfg->fc_ifindex &&
(!rt->dst.dev ||
rt->dst.dev->ifindex != cfg->fc_ifindex))
continue;
if (cfg->fc_flags & RTF_GATEWAY &&
!ipv6_addr_equal(&cfg->fc_gateway, &rt->rt6i_gateway))
continue;
if (cfg->fc_metric && cfg->fc_metric != rt->rt6i_metric)
continue;
dst_hold(&rt->dst);
read_unlock_bh(&table->tb6_lock);
return __ip6_del_rt(rt, &cfg->fc_nlinfo);
}
}
read_unlock_bh(&table->tb6_lock);
return err;
}
static void rt6_do_redirect(struct dst_entry *dst, struct sock *sk, struct sk_buff *skb)
{
struct net *net = dev_net(skb->dev);
struct netevent_redirect netevent;
struct rt6_info *rt, *nrt = NULL;
const struct in6_addr *target;
struct ndisc_options ndopts;
const struct in6_addr *dest;
struct neighbour *old_neigh;
struct inet6_dev *in6_dev;
struct neighbour *neigh;
struct icmp6hdr *icmph;
int optlen, on_link;
u8 *lladdr;
optlen = skb->tail - skb->transport_header;
optlen -= sizeof(struct icmp6hdr) + 2 * sizeof(struct in6_addr);
if (optlen < 0) {
net_dbg_ratelimited("rt6_do_redirect: packet too short\n");
return;
}
icmph = icmp6_hdr(skb);
target = (const struct in6_addr *) (icmph + 1);
dest = target + 1;
if (ipv6_addr_is_multicast(dest)) {
net_dbg_ratelimited("rt6_do_redirect: destination address is multicast\n");
return;
}
on_link = 0;
if (ipv6_addr_equal(dest, target)) {
on_link = 1;
} else if (ipv6_addr_type(target) !=
(IPV6_ADDR_UNICAST|IPV6_ADDR_LINKLOCAL)) {
net_dbg_ratelimited("rt6_do_redirect: target address is not link-local unicast\n");
return;
}
in6_dev = __in6_dev_get(skb->dev);
if (!in6_dev)
return;
if (in6_dev->cnf.forwarding || !in6_dev->cnf.accept_redirects)
return;
/* RFC2461 8.1:
* The IP source address of the Redirect MUST be the same as the current
* first-hop router for the specified ICMP Destination Address.
*/
if (!ndisc_parse_options((u8*)(dest + 1), optlen, &ndopts)) {
net_dbg_ratelimited("rt6_redirect: invalid ND options\n");
return;
}
lladdr = NULL;
if (ndopts.nd_opts_tgt_lladdr) {
lladdr = ndisc_opt_addr_data(ndopts.nd_opts_tgt_lladdr,
skb->dev);
if (!lladdr) {
net_dbg_ratelimited("rt6_redirect: invalid link-layer address length\n");
return;
}
}
rt = (struct rt6_info *) dst;
if (rt == net->ipv6.ip6_null_entry) {
net_dbg_ratelimited("rt6_redirect: source isn't a valid nexthop for redirect target\n");
return;
}
/* Redirect received -> path was valid.
* Look, redirects are sent only in response to data packets,
* so that this nexthop apparently is reachable. --ANK
*/
dst_confirm(&rt->dst);
neigh = __neigh_lookup(&nd_tbl, target, skb->dev, 1);
if (!neigh)
return;
/* Duplicate redirect: silently ignore. */
old_neigh = rt->n;
if (neigh == old_neigh)
goto out;
/*
* We have finally decided to accept it.
*/
neigh_update(neigh, lladdr, NUD_STALE,
NEIGH_UPDATE_F_WEAK_OVERRIDE|
NEIGH_UPDATE_F_OVERRIDE|
(on_link ? 0 : (NEIGH_UPDATE_F_OVERRIDE_ISROUTER|
NEIGH_UPDATE_F_ISROUTER))
);
nrt = ip6_rt_copy(rt, dest);
if (!nrt)
goto out;
nrt->rt6i_flags = RTF_GATEWAY|RTF_UP|RTF_DYNAMIC|RTF_CACHE;
if (on_link)
nrt->rt6i_flags &= ~RTF_GATEWAY;
nrt->rt6i_gateway = *(struct in6_addr *)neigh->primary_key;
nrt->n = neigh_clone(neigh);
if (ip6_ins_rt(nrt))
goto out;
netevent.old = &rt->dst;
netevent.old_neigh = old_neigh;
netevent.new = &nrt->dst;
netevent.new_neigh = neigh;
netevent.daddr = dest;
call_netevent_notifiers(NETEVENT_REDIRECT, &netevent);
if (rt->rt6i_flags & RTF_CACHE) {
rt = (struct rt6_info *) dst_clone(&rt->dst);
ip6_del_rt(rt);
}
out:
neigh_release(neigh);
}
/*
* Misc support functions
*/
static struct rt6_info *ip6_rt_copy(struct rt6_info *ort,
const struct in6_addr *dest)
{
struct net *net = dev_net(ort->dst.dev);
struct rt6_info *rt = ip6_dst_alloc(net, ort->dst.dev, 0,
ort->rt6i_table);
if (rt) {
rt->dst.input = ort->dst.input;
rt->dst.output = ort->dst.output;
rt->dst.flags |= DST_HOST;
rt->rt6i_dst.addr = *dest;
rt->rt6i_dst.plen = 128;
dst_copy_metrics(&rt->dst, &ort->dst);
rt->dst.error = ort->dst.error;
rt->rt6i_idev = ort->rt6i_idev;
if (rt->rt6i_idev)
in6_dev_hold(rt->rt6i_idev);
rt->dst.lastuse = jiffies;
rt->rt6i_gateway = ort->rt6i_gateway;
rt->rt6i_flags = ort->rt6i_flags;
if ((ort->rt6i_flags & (RTF_DEFAULT | RTF_ADDRCONF)) ==
(RTF_DEFAULT | RTF_ADDRCONF))
rt6_set_from(rt, ort);
rt->rt6i_metric = 0;
#ifdef CONFIG_IPV6_SUBTREES
memcpy(&rt->rt6i_src, &ort->rt6i_src, sizeof(struct rt6key));
#endif
memcpy(&rt->rt6i_prefsrc, &ort->rt6i_prefsrc, sizeof(struct rt6key));
rt->rt6i_table = ort->rt6i_table;
}
return rt;
}
#ifdef CONFIG_IPV6_ROUTE_INFO
static struct rt6_info *rt6_get_route_info(struct net *net,
const struct in6_addr *prefix, int prefixlen,
const struct in6_addr *gwaddr, int ifindex)
{
struct fib6_node *fn;
struct rt6_info *rt = NULL;
struct fib6_table *table;
table = fib6_get_table(net, RT6_TABLE_INFO);
if (!table)
return NULL;
read_lock_bh(&table->tb6_lock);
fn = fib6_locate(&table->tb6_root, prefix ,prefixlen, NULL, 0);
if (!fn)
goto out;
for (rt = fn->leaf; rt; rt = rt->dst.rt6_next) {
if (rt->dst.dev->ifindex != ifindex)
continue;
if ((rt->rt6i_flags & (RTF_ROUTEINFO|RTF_GATEWAY)) != (RTF_ROUTEINFO|RTF_GATEWAY))
continue;
if (!ipv6_addr_equal(&rt->rt6i_gateway, gwaddr))
continue;
dst_hold(&rt->dst);
break;
}
out:
read_unlock_bh(&table->tb6_lock);
return rt;
}
static struct rt6_info *rt6_add_route_info(struct net *net,
const struct in6_addr *prefix, int prefixlen,
const struct in6_addr *gwaddr, int ifindex,
unsigned int pref)
{
struct fib6_config cfg = {
.fc_table = RT6_TABLE_INFO,
.fc_metric = IP6_RT_PRIO_USER,
.fc_ifindex = ifindex,
.fc_dst_len = prefixlen,
.fc_flags = RTF_GATEWAY | RTF_ADDRCONF | RTF_ROUTEINFO |
RTF_UP | RTF_PREF(pref),
.fc_nlinfo.portid = 0,
.fc_nlinfo.nlh = NULL,
.fc_nlinfo.nl_net = net,
};
cfg.fc_dst = *prefix;
cfg.fc_gateway = *gwaddr;
/* We should treat it as a default route if prefix length is 0. */
if (!prefixlen)
cfg.fc_flags |= RTF_DEFAULT;
ip6_route_add(&cfg);
return rt6_get_route_info(net, prefix, prefixlen, gwaddr, ifindex);
}
#endif
struct rt6_info *rt6_get_dflt_router(const struct in6_addr *addr, struct net_device *dev)
{
struct rt6_info *rt;
struct fib6_table *table;
table = fib6_get_table(dev_net(dev), RT6_TABLE_DFLT);
if (!table)
return NULL;
read_lock_bh(&table->tb6_lock);
for (rt = table->tb6_root.leaf; rt; rt=rt->dst.rt6_next) {
if (dev == rt->dst.dev &&
((rt->rt6i_flags & (RTF_ADDRCONF | RTF_DEFAULT)) == (RTF_ADDRCONF | RTF_DEFAULT)) &&
ipv6_addr_equal(&rt->rt6i_gateway, addr))
break;
}
if (rt)
dst_hold(&rt->dst);
read_unlock_bh(&table->tb6_lock);
return rt;
}
struct rt6_info *rt6_add_dflt_router(const struct in6_addr *gwaddr,
struct net_device *dev,
unsigned int pref)
{
struct fib6_config cfg = {
.fc_table = RT6_TABLE_DFLT,
.fc_metric = IP6_RT_PRIO_USER,
.fc_ifindex = dev->ifindex,
.fc_flags = RTF_GATEWAY | RTF_ADDRCONF | RTF_DEFAULT |
RTF_UP | RTF_EXPIRES | RTF_PREF(pref),
.fc_nlinfo.portid = 0,
.fc_nlinfo.nlh = NULL,
.fc_nlinfo.nl_net = dev_net(dev),
};
cfg.fc_gateway = *gwaddr;
ip6_route_add(&cfg);
return rt6_get_dflt_router(gwaddr, dev);
}
void rt6_purge_dflt_routers(struct net *net)
{
struct rt6_info *rt;
struct fib6_table *table;
/* NOTE: Keep consistent with rt6_get_dflt_router */
table = fib6_get_table(net, RT6_TABLE_DFLT);
if (!table)
return;
restart:
read_lock_bh(&table->tb6_lock);
for (rt = table->tb6_root.leaf; rt; rt = rt->dst.rt6_next) {
if (rt->rt6i_flags & (RTF_DEFAULT | RTF_ADDRCONF) &&
(!rt->rt6i_idev || rt->rt6i_idev->cnf.accept_ra != 2)) {
dst_hold(&rt->dst);
read_unlock_bh(&table->tb6_lock);
ip6_del_rt(rt);
goto restart;
}
}
read_unlock_bh(&table->tb6_lock);
}
static void rtmsg_to_fib6_config(struct net *net,
struct in6_rtmsg *rtmsg,
struct fib6_config *cfg)
{
memset(cfg, 0, sizeof(*cfg));
cfg->fc_table = RT6_TABLE_MAIN;
cfg->fc_ifindex = rtmsg->rtmsg_ifindex;
cfg->fc_metric = rtmsg->rtmsg_metric;
cfg->fc_expires = rtmsg->rtmsg_info;
cfg->fc_dst_len = rtmsg->rtmsg_dst_len;
cfg->fc_src_len = rtmsg->rtmsg_src_len;
cfg->fc_flags = rtmsg->rtmsg_flags;
cfg->fc_nlinfo.nl_net = net;
cfg->fc_dst = rtmsg->rtmsg_dst;
cfg->fc_src = rtmsg->rtmsg_src;
cfg->fc_gateway = rtmsg->rtmsg_gateway;
}
int ipv6_route_ioctl(struct net *net, unsigned int cmd, void __user *arg)
{
struct fib6_config cfg;
struct in6_rtmsg rtmsg;
int err;
switch(cmd) {
case SIOCADDRT: /* Add a route */
case SIOCDELRT: /* Delete a route */
if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
return -EPERM;
err = copy_from_user(&rtmsg, arg,
sizeof(struct in6_rtmsg));
if (err)
return -EFAULT;
rtmsg_to_fib6_config(net, &rtmsg, &cfg);
rtnl_lock();
switch (cmd) {
case SIOCADDRT:
err = ip6_route_add(&cfg);
break;
case SIOCDELRT:
err = ip6_route_del(&cfg);
break;
default:
err = -EINVAL;
}
rtnl_unlock();
return err;
}
return -EINVAL;
}
/*
* Drop the packet on the floor
*/
static int ip6_pkt_drop(struct sk_buff *skb, u8 code, int ipstats_mib_noroutes)
{
int type;
struct dst_entry *dst = skb_dst(skb);
switch (ipstats_mib_noroutes) {
case IPSTATS_MIB_INNOROUTES:
type = ipv6_addr_type(&ipv6_hdr(skb)->daddr);
if (type == IPV6_ADDR_ANY) {
IP6_INC_STATS(dev_net(dst->dev), ip6_dst_idev(dst),
IPSTATS_MIB_INADDRERRORS);
break;
}
/* FALLTHROUGH */
case IPSTATS_MIB_OUTNOROUTES:
IP6_INC_STATS(dev_net(dst->dev), ip6_dst_idev(dst),
ipstats_mib_noroutes);
break;
}
icmpv6_send(skb, ICMPV6_DEST_UNREACH, code, 0);
kfree_skb(skb);
return 0;
}
static int ip6_pkt_discard(struct sk_buff *skb)
{
return ip6_pkt_drop(skb, ICMPV6_NOROUTE, IPSTATS_MIB_INNOROUTES);
}
static int ip6_pkt_discard_out(struct sk_buff *skb)
{
skb->dev = skb_dst(skb)->dev;
return ip6_pkt_drop(skb, ICMPV6_NOROUTE, IPSTATS_MIB_OUTNOROUTES);
}
#ifdef CONFIG_IPV6_MULTIPLE_TABLES
static int ip6_pkt_prohibit(struct sk_buff *skb)
{
return ip6_pkt_drop(skb, ICMPV6_ADM_PROHIBITED, IPSTATS_MIB_INNOROUTES);
}
static int ip6_pkt_prohibit_out(struct sk_buff *skb)
{
skb->dev = skb_dst(skb)->dev;
return ip6_pkt_drop(skb, ICMPV6_ADM_PROHIBITED, IPSTATS_MIB_OUTNOROUTES);
}
#endif
/*
* Allocate a dst for local (unicast / anycast) address.
*/
struct rt6_info *addrconf_dst_alloc(struct inet6_dev *idev,
const struct in6_addr *addr,
bool anycast)
{
struct net *net = dev_net(idev->dev);
struct rt6_info *rt = ip6_dst_alloc(net, net->loopback_dev, 0, NULL);
int err;
if (!rt) {
net_warn_ratelimited("Maximum number of routes reached, consider increasing route/max_size\n");
return ERR_PTR(-ENOMEM);
}
in6_dev_hold(idev);
rt->dst.flags |= DST_HOST;
rt->dst.input = ip6_input;
rt->dst.output = ip6_output;
rt->rt6i_idev = idev;
rt->rt6i_flags = RTF_UP | RTF_NONEXTHOP;
if (anycast)
rt->rt6i_flags |= RTF_ANYCAST;
else
rt->rt6i_flags |= RTF_LOCAL;
err = rt6_bind_neighbour(rt, rt->dst.dev);
if (err) {
dst_free(&rt->dst);
return ERR_PTR(err);
}
rt->rt6i_dst.addr = *addr;
rt->rt6i_dst.plen = 128;
rt->rt6i_table = fib6_get_table(net, RT6_TABLE_LOCAL);
atomic_set(&rt->dst.__refcnt, 1);
return rt;
}
int ip6_route_get_saddr(struct net *net,
struct rt6_info *rt,
const struct in6_addr *daddr,
unsigned int prefs,
struct in6_addr *saddr)
{
struct inet6_dev *idev = ip6_dst_idev((struct dst_entry*)rt);
int err = 0;
if (rt->rt6i_prefsrc.plen)
*saddr = rt->rt6i_prefsrc.addr;
else
err = ipv6_dev_get_saddr(net, idev ? idev->dev : NULL,
daddr, prefs, saddr);
return err;
}
/* remove deleted ip from prefsrc entries */
struct arg_dev_net_ip {
struct net_device *dev;
struct net *net;
struct in6_addr *addr;
};
static int fib6_remove_prefsrc(struct rt6_info *rt, void *arg)
{
struct net_device *dev = ((struct arg_dev_net_ip *)arg)->dev;
struct net *net = ((struct arg_dev_net_ip *)arg)->net;
struct in6_addr *addr = ((struct arg_dev_net_ip *)arg)->addr;
if (((void *)rt->dst.dev == dev || !dev) &&
rt != net->ipv6.ip6_null_entry &&
ipv6_addr_equal(addr, &rt->rt6i_prefsrc.addr)) {
/* remove prefsrc entry */
rt->rt6i_prefsrc.plen = 0;
}
return 0;
}
void rt6_remove_prefsrc(struct inet6_ifaddr *ifp)
{
struct net *net = dev_net(ifp->idev->dev);
struct arg_dev_net_ip adni = {
.dev = ifp->idev->dev,
.net = net,
.addr = &ifp->addr,
};
fib6_clean_all(net, fib6_remove_prefsrc, 0, &adni);
}
struct arg_dev_net {
struct net_device *dev;
struct net *net;
};
static int fib6_ifdown(struct rt6_info *rt, void *arg)
{
const struct arg_dev_net *adn = arg;
const struct net_device *dev = adn->dev;
if ((rt->dst.dev == dev || !dev) &&
rt != adn->net->ipv6.ip6_null_entry)
return -1;
return 0;
}
void rt6_ifdown(struct net *net, struct net_device *dev)
{
struct arg_dev_net adn = {
.dev = dev,
.net = net,
};
fib6_clean_all(net, fib6_ifdown, 0, &adn);
icmp6_clean_all(fib6_ifdown, &adn);
}
struct rt6_mtu_change_arg {
struct net_device *dev;
unsigned int mtu;
};
static int rt6_mtu_change_route(struct rt6_info *rt, void *p_arg)
{
struct rt6_mtu_change_arg *arg = (struct rt6_mtu_change_arg *) p_arg;
struct inet6_dev *idev;
/* In IPv6 pmtu discovery is not optional,
so that RTAX_MTU lock cannot disable it.
We still use this lock to block changes
caused by addrconf/ndisc.
*/
idev = __in6_dev_get(arg->dev);
if (!idev)
return 0;
/* For administrative MTU increase, there is no way to discover
IPv6 PMTU increase, so PMTU increase should be updated here.
Since RFC 1981 doesn't include administrative MTU increase
update PMTU increase is a MUST. (i.e. jumbo frame)
*/
/*
If new MTU is less than route PMTU, this new MTU will be the
lowest MTU in the path, update the route PMTU to reflect PMTU
decreases; if new MTU is greater than route PMTU, and the
old MTU is the lowest MTU in the path, update the route PMTU
to reflect the increase. In this case if the other nodes' MTU
also have the lowest MTU, TOO BIG MESSAGE will be lead to
PMTU discouvery.
*/
if (rt->dst.dev == arg->dev &&
!dst_metric_locked(&rt->dst, RTAX_MTU) &&
(dst_mtu(&rt->dst) >= arg->mtu ||
(dst_mtu(&rt->dst) < arg->mtu &&
dst_mtu(&rt->dst) == idev->cnf.mtu6))) {
dst_metric_set(&rt->dst, RTAX_MTU, arg->mtu);
}
return 0;
}
void rt6_mtu_change(struct net_device *dev, unsigned int mtu)
{
struct rt6_mtu_change_arg arg = {
.dev = dev,
.mtu = mtu,
};
fib6_clean_all(dev_net(dev), rt6_mtu_change_route, 0, &arg);
}
static const struct nla_policy rtm_ipv6_policy[RTA_MAX+1] = {
[RTA_GATEWAY] = { .len = sizeof(struct in6_addr) },
[RTA_OIF] = { .type = NLA_U32 },
[RTA_IIF] = { .type = NLA_U32 },
[RTA_PRIORITY] = { .type = NLA_U32 },
[RTA_METRICS] = { .type = NLA_NESTED },
[RTA_MULTIPATH] = { .len = sizeof(struct rtnexthop) },
};
static int rtm_to_fib6_config(struct sk_buff *skb, struct nlmsghdr *nlh,
struct fib6_config *cfg)
{
struct rtmsg *rtm;
struct nlattr *tb[RTA_MAX+1];
int err;
err = nlmsg_parse(nlh, sizeof(*rtm), tb, RTA_MAX, rtm_ipv6_policy);
if (err < 0)
goto errout;
err = -EINVAL;
rtm = nlmsg_data(nlh);
memset(cfg, 0, sizeof(*cfg));
cfg->fc_table = rtm->rtm_table;
cfg->fc_dst_len = rtm->rtm_dst_len;
cfg->fc_src_len = rtm->rtm_src_len;
cfg->fc_flags = RTF_UP;
cfg->fc_protocol = rtm->rtm_protocol;
cfg->fc_type = rtm->rtm_type;
if (rtm->rtm_type == RTN_UNREACHABLE ||
rtm->rtm_type == RTN_BLACKHOLE ||
rtm->rtm_type == RTN_PROHIBIT ||
rtm->rtm_type == RTN_THROW)
cfg->fc_flags |= RTF_REJECT;
if (rtm->rtm_type == RTN_LOCAL)
cfg->fc_flags |= RTF_LOCAL;
cfg->fc_nlinfo.portid = NETLINK_CB(skb).portid;
cfg->fc_nlinfo.nlh = nlh;
cfg->fc_nlinfo.nl_net = sock_net(skb->sk);
if (tb[RTA_GATEWAY]) {
nla_memcpy(&cfg->fc_gateway, tb[RTA_GATEWAY], 16);
cfg->fc_flags |= RTF_GATEWAY;
}
if (tb[RTA_DST]) {
int plen = (rtm->rtm_dst_len + 7) >> 3;
if (nla_len(tb[RTA_DST]) < plen)
goto errout;
nla_memcpy(&cfg->fc_dst, tb[RTA_DST], plen);
}
if (tb[RTA_SRC]) {
int plen = (rtm->rtm_src_len + 7) >> 3;
if (nla_len(tb[RTA_SRC]) < plen)
goto errout;
nla_memcpy(&cfg->fc_src, tb[RTA_SRC], plen);
}
if (tb[RTA_PREFSRC])
nla_memcpy(&cfg->fc_prefsrc, tb[RTA_PREFSRC], 16);
if (tb[RTA_OIF])
cfg->fc_ifindex = nla_get_u32(tb[RTA_OIF]);
if (tb[RTA_PRIORITY])
cfg->fc_metric = nla_get_u32(tb[RTA_PRIORITY]);
if (tb[RTA_METRICS]) {
cfg->fc_mx = nla_data(tb[RTA_METRICS]);
cfg->fc_mx_len = nla_len(tb[RTA_METRICS]);
}
if (tb[RTA_TABLE])
cfg->fc_table = nla_get_u32(tb[RTA_TABLE]);
if (tb[RTA_MULTIPATH]) {
cfg->fc_mp = nla_data(tb[RTA_MULTIPATH]);
cfg->fc_mp_len = nla_len(tb[RTA_MULTIPATH]);
}
err = 0;
errout:
return err;
}
static int ip6_route_multipath(struct fib6_config *cfg, int add)
{
struct fib6_config r_cfg;
struct rtnexthop *rtnh;
int remaining;
int attrlen;
int err = 0, last_err = 0;
beginning:
rtnh = (struct rtnexthop *)cfg->fc_mp;
remaining = cfg->fc_mp_len;
/* Parse a Multipath Entry */
while (rtnh_ok(rtnh, remaining)) {
memcpy(&r_cfg, cfg, sizeof(*cfg));
if (rtnh->rtnh_ifindex)
r_cfg.fc_ifindex = rtnh->rtnh_ifindex;
attrlen = rtnh_attrlen(rtnh);
if (attrlen > 0) {
struct nlattr *nla, *attrs = rtnh_attrs(rtnh);
nla = nla_find(attrs, attrlen, RTA_GATEWAY);
if (nla) {
nla_memcpy(&r_cfg.fc_gateway, nla, 16);
r_cfg.fc_flags |= RTF_GATEWAY;
}
}
err = add ? ip6_route_add(&r_cfg) : ip6_route_del(&r_cfg);
if (err) {
last_err = err;
/* If we are trying to remove a route, do not stop the
* loop when ip6_route_del() fails (because next hop is
* already gone), we should try to remove all next hops.
*/
if (add) {
/* If add fails, we should try to delete all
* next hops that have been already added.
*/
add = 0;
goto beginning;
}
}
/* Because each route is added like a single route we remove
* this flag after the first nexthop (if there is a collision,
* we have already fail to add the first nexthop:
* fib6_add_rt2node() has reject it).
*/
cfg->fc_nlinfo.nlh->nlmsg_flags &= ~NLM_F_EXCL;
rtnh = rtnh_next(rtnh, &remaining);
}
return last_err;
}
static int inet6_rtm_delroute(struct sk_buff *skb, struct nlmsghdr* nlh, void *arg)
{
struct fib6_config cfg;
int err;
err = rtm_to_fib6_config(skb, nlh, &cfg);
if (err < 0)
return err;
if (cfg.fc_mp)
return ip6_route_multipath(&cfg, 0);
else
return ip6_route_del(&cfg);
}
static int inet6_rtm_newroute(struct sk_buff *skb, struct nlmsghdr* nlh, void *arg)
{
struct fib6_config cfg;
int err;
err = rtm_to_fib6_config(skb, nlh, &cfg);
if (err < 0)
return err;
if (cfg.fc_mp)
return ip6_route_multipath(&cfg, 1);
else
return ip6_route_add(&cfg);
}
static inline size_t rt6_nlmsg_size(void)
{
return NLMSG_ALIGN(sizeof(struct rtmsg))
+ nla_total_size(16) /* RTA_SRC */
+ nla_total_size(16) /* RTA_DST */
+ nla_total_size(16) /* RTA_GATEWAY */
+ nla_total_size(16) /* RTA_PREFSRC */
+ nla_total_size(4) /* RTA_TABLE */
+ nla_total_size(4) /* RTA_IIF */
+ nla_total_size(4) /* RTA_OIF */
+ nla_total_size(4) /* RTA_PRIORITY */
+ RTAX_MAX * nla_total_size(4) /* RTA_METRICS */
+ nla_total_size(sizeof(struct rta_cacheinfo));
}
static int rt6_fill_node(struct net *net,
struct sk_buff *skb, struct rt6_info *rt,
struct in6_addr *dst, struct in6_addr *src,
int iif, int type, u32 portid, u32 seq,
int prefix, int nowait, unsigned int flags)
{
struct rtmsg *rtm;
struct nlmsghdr *nlh;
long expires;
u32 table;
struct neighbour *n;
if (prefix) { /* user wants prefix routes only */
if (!(rt->rt6i_flags & RTF_PREFIX_RT)) {
/* success since this is not a prefix route */
return 1;
}
}
nlh = nlmsg_put(skb, portid, seq, type, sizeof(*rtm), flags);
if (!nlh)
return -EMSGSIZE;
rtm = nlmsg_data(nlh);
rtm->rtm_family = AF_INET6;
rtm->rtm_dst_len = rt->rt6i_dst.plen;
rtm->rtm_src_len = rt->rt6i_src.plen;
rtm->rtm_tos = 0;
if (rt->rt6i_table)
table = rt->rt6i_table->tb6_id;
else
table = RT6_TABLE_UNSPEC;
rtm->rtm_table = table;
if (nla_put_u32(skb, RTA_TABLE, table))
goto nla_put_failure;
if (rt->rt6i_flags & RTF_REJECT) {
switch (rt->dst.error) {
case -EINVAL:
rtm->rtm_type = RTN_BLACKHOLE;
break;
case -EACCES:
rtm->rtm_type = RTN_PROHIBIT;
break;
case -EAGAIN:
rtm->rtm_type = RTN_THROW;
break;
default:
rtm->rtm_type = RTN_UNREACHABLE;
break;
}
}
else if (rt->rt6i_flags & RTF_LOCAL)
rtm->rtm_type = RTN_LOCAL;
else if (rt->dst.dev && (rt->dst.dev->flags & IFF_LOOPBACK))
rtm->rtm_type = RTN_LOCAL;
else
rtm->rtm_type = RTN_UNICAST;
rtm->rtm_flags = 0;
rtm->rtm_scope = RT_SCOPE_UNIVERSE;
rtm->rtm_protocol = rt->rt6i_protocol;
if (rt->rt6i_flags & RTF_DYNAMIC)
rtm->rtm_protocol = RTPROT_REDIRECT;
else if (rt->rt6i_flags & RTF_ADDRCONF) {
if (rt->rt6i_flags & (RTF_DEFAULT | RTF_ROUTEINFO))
rtm->rtm_protocol = RTPROT_RA;
else
rtm->rtm_protocol = RTPROT_KERNEL;
}
if (rt->rt6i_flags & RTF_CACHE)
rtm->rtm_flags |= RTM_F_CLONED;
if (dst) {
if (nla_put(skb, RTA_DST, 16, dst))
goto nla_put_failure;
rtm->rtm_dst_len = 128;
} else if (rtm->rtm_dst_len)
if (nla_put(skb, RTA_DST, 16, &rt->rt6i_dst.addr))
goto nla_put_failure;
#ifdef CONFIG_IPV6_SUBTREES
if (src) {
if (nla_put(skb, RTA_SRC, 16, src))
goto nla_put_failure;
rtm->rtm_src_len = 128;
} else if (rtm->rtm_src_len &&
nla_put(skb, RTA_SRC, 16, &rt->rt6i_src.addr))
goto nla_put_failure;
#endif
if (iif) {
#ifdef CONFIG_IPV6_MROUTE
if (ipv6_addr_is_multicast(&rt->rt6i_dst.addr)) {
int err = ip6mr_get_route(net, skb, rtm, nowait);
if (err <= 0) {
if (!nowait) {
if (err == 0)
return 0;
goto nla_put_failure;
} else {
if (err == -EMSGSIZE)
goto nla_put_failure;
}
}
} else
#endif
if (nla_put_u32(skb, RTA_IIF, iif))
goto nla_put_failure;
} else if (dst) {
struct in6_addr saddr_buf;
if (ip6_route_get_saddr(net, rt, dst, 0, &saddr_buf) == 0 &&
nla_put(skb, RTA_PREFSRC, 16, &saddr_buf))
goto nla_put_failure;
}
if (rt->rt6i_prefsrc.plen) {
struct in6_addr saddr_buf;
saddr_buf = rt->rt6i_prefsrc.addr;
if (nla_put(skb, RTA_PREFSRC, 16, &saddr_buf))
goto nla_put_failure;
}
if (rtnetlink_put_metrics(skb, dst_metrics_ptr(&rt->dst)) < 0)
goto nla_put_failure;
n = rt->n;
if (n) {
if (nla_put(skb, RTA_GATEWAY, 16, &n->primary_key) < 0)
goto nla_put_failure;
}
if (rt->dst.dev &&
nla_put_u32(skb, RTA_OIF, rt->dst.dev->ifindex))
goto nla_put_failure;
if (nla_put_u32(skb, RTA_PRIORITY, rt->rt6i_metric))
goto nla_put_failure;
expires = (rt->rt6i_flags & RTF_EXPIRES) ? rt->dst.expires - jiffies : 0;
if (rtnl_put_cacheinfo(skb, &rt->dst, 0, expires, rt->dst.error) < 0)
goto nla_put_failure;
return nlmsg_end(skb, nlh);
nla_put_failure:
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
int rt6_dump_route(struct rt6_info *rt, void *p_arg)
{
struct rt6_rtnl_dump_arg *arg = (struct rt6_rtnl_dump_arg *) p_arg;
int prefix;
if (nlmsg_len(arg->cb->nlh) >= sizeof(struct rtmsg)) {
struct rtmsg *rtm = nlmsg_data(arg->cb->nlh);
prefix = (rtm->rtm_flags & RTM_F_PREFIX) != 0;
} else
prefix = 0;
return rt6_fill_node(arg->net,
arg->skb, rt, NULL, NULL, 0, RTM_NEWROUTE,
NETLINK_CB(arg->cb->skb).portid, arg->cb->nlh->nlmsg_seq,
prefix, 0, NLM_F_MULTI);
}
static int inet6_rtm_getroute(struct sk_buff *in_skb, struct nlmsghdr* nlh, void *arg)
{
struct net *net = sock_net(in_skb->sk);
struct nlattr *tb[RTA_MAX+1];
struct rt6_info *rt;
struct sk_buff *skb;
struct rtmsg *rtm;
struct flowi6 fl6;
int err, iif = 0, oif = 0;
err = nlmsg_parse(nlh, sizeof(*rtm), tb, RTA_MAX, rtm_ipv6_policy);
if (err < 0)
goto errout;
err = -EINVAL;
memset(&fl6, 0, sizeof(fl6));
if (tb[RTA_SRC]) {
if (nla_len(tb[RTA_SRC]) < sizeof(struct in6_addr))
goto errout;
fl6.saddr = *(struct in6_addr *)nla_data(tb[RTA_SRC]);
}
if (tb[RTA_DST]) {
if (nla_len(tb[RTA_DST]) < sizeof(struct in6_addr))
goto errout;
fl6.daddr = *(struct in6_addr *)nla_data(tb[RTA_DST]);
}
if (tb[RTA_IIF])
iif = nla_get_u32(tb[RTA_IIF]);
if (tb[RTA_OIF])
oif = nla_get_u32(tb[RTA_OIF]);
if (iif) {
struct net_device *dev;
int flags = 0;
dev = __dev_get_by_index(net, iif);
if (!dev) {
err = -ENODEV;
goto errout;
}
fl6.flowi6_iif = iif;
if (!ipv6_addr_any(&fl6.saddr))
flags |= RT6_LOOKUP_F_HAS_SADDR;
rt = (struct rt6_info *)ip6_route_input_lookup(net, dev, &fl6,
flags);
} else {
fl6.flowi6_oif = oif;
rt = (struct rt6_info *)ip6_route_output(net, NULL, &fl6);
}
skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL);
if (!skb) {
ip6_rt_put(rt);
err = -ENOBUFS;
goto errout;
}
/* Reserve room for dummy headers, this skb can pass
through good chunk of routing engine.
*/
skb_reset_mac_header(skb);
skb_reserve(skb, MAX_HEADER + sizeof(struct ipv6hdr));
skb_dst_set(skb, &rt->dst);
err = rt6_fill_node(net, skb, rt, &fl6.daddr, &fl6.saddr, iif,
RTM_NEWROUTE, NETLINK_CB(in_skb).portid,
nlh->nlmsg_seq, 0, 0, 0);
if (err < 0) {
kfree_skb(skb);
goto errout;
}
err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid);
errout:
return err;
}
void inet6_rt_notify(int event, struct rt6_info *rt, struct nl_info *info)
{
struct sk_buff *skb;
struct net *net = info->nl_net;
u32 seq;
int err;
err = -ENOBUFS;
seq = info->nlh ? info->nlh->nlmsg_seq : 0;
skb = nlmsg_new(rt6_nlmsg_size(), gfp_any());
if (!skb)
goto errout;
err = rt6_fill_node(net, skb, rt, NULL, NULL, 0,
event, info->portid, seq, 0, 0, 0);
if (err < 0) {
/* -EMSGSIZE implies BUG in rt6_nlmsg_size() */
WARN_ON(err == -EMSGSIZE);
kfree_skb(skb);
goto errout;
}
rtnl_notify(skb, net, info->portid, RTNLGRP_IPV6_ROUTE,
info->nlh, gfp_any());
return;
errout:
if (err < 0)
rtnl_set_sk_err(net, RTNLGRP_IPV6_ROUTE, err);
}
static int ip6_route_dev_notify(struct notifier_block *this,
unsigned long event, void *data)
{
struct net_device *dev = (struct net_device *)data;
struct net *net = dev_net(dev);
if (event == NETDEV_REGISTER && (dev->flags & IFF_LOOPBACK)) {
net->ipv6.ip6_null_entry->dst.dev = dev;
net->ipv6.ip6_null_entry->rt6i_idev = in6_dev_get(dev);
#ifdef CONFIG_IPV6_MULTIPLE_TABLES
net->ipv6.ip6_prohibit_entry->dst.dev = dev;
net->ipv6.ip6_prohibit_entry->rt6i_idev = in6_dev_get(dev);
net->ipv6.ip6_blk_hole_entry->dst.dev = dev;
net->ipv6.ip6_blk_hole_entry->rt6i_idev = in6_dev_get(dev);
#endif
}
return NOTIFY_OK;
}
/*
* /proc
*/
#ifdef CONFIG_PROC_FS
struct rt6_proc_arg
{
char *buffer;
int offset;
int length;
int skip;
int len;
};
static int rt6_info_route(struct rt6_info *rt, void *p_arg)
{
struct seq_file *m = p_arg;
struct neighbour *n;
seq_printf(m, "%pi6 %02x ", &rt->rt6i_dst.addr, rt->rt6i_dst.plen);
#ifdef CONFIG_IPV6_SUBTREES
seq_printf(m, "%pi6 %02x ", &rt->rt6i_src.addr, rt->rt6i_src.plen);
#else
seq_puts(m, "00000000000000000000000000000000 00 ");
#endif
n = rt->n;
if (n) {
seq_printf(m, "%pi6", n->primary_key);
} else {
seq_puts(m, "00000000000000000000000000000000");
}
seq_printf(m, " %08x %08x %08x %08x %8s\n",
rt->rt6i_metric, atomic_read(&rt->dst.__refcnt),
rt->dst.__use, rt->rt6i_flags,
rt->dst.dev ? rt->dst.dev->name : "");
return 0;
}
static int ipv6_route_show(struct seq_file *m, void *v)
{
struct net *net = (struct net *)m->private;
fib6_clean_all_ro(net, rt6_info_route, 0, m);
return 0;
}
static int ipv6_route_open(struct inode *inode, struct file *file)
{
return single_open_net(inode, file, ipv6_route_show);
}
static const struct file_operations ipv6_route_proc_fops = {
.owner = THIS_MODULE,
.open = ipv6_route_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release_net,
};
static int rt6_stats_seq_show(struct seq_file *seq, void *v)
{
struct net *net = (struct net *)seq->private;
seq_printf(seq, "%04x %04x %04x %04x %04x %04x %04x\n",
net->ipv6.rt6_stats->fib_nodes,
net->ipv6.rt6_stats->fib_route_nodes,
net->ipv6.rt6_stats->fib_rt_alloc,
net->ipv6.rt6_stats->fib_rt_entries,
net->ipv6.rt6_stats->fib_rt_cache,
dst_entries_get_slow(&net->ipv6.ip6_dst_ops),
net->ipv6.rt6_stats->fib_discarded_routes);
return 0;
}
static int rt6_stats_seq_open(struct inode *inode, struct file *file)
{
return single_open_net(inode, file, rt6_stats_seq_show);
}
static const struct file_operations rt6_stats_seq_fops = {
.owner = THIS_MODULE,
.open = rt6_stats_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release_net,
};
#endif /* CONFIG_PROC_FS */
#ifdef CONFIG_SYSCTL
static
int ipv6_sysctl_rtcache_flush(ctl_table *ctl, int write,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
struct net *net;
int delay;
if (!write)
return -EINVAL;
net = (struct net *)ctl->extra1;
delay = net->ipv6.sysctl.flush_delay;
proc_dointvec(ctl, write, buffer, lenp, ppos);
fib6_run_gc(delay <= 0 ? ~0UL : (unsigned long)delay, net);
return 0;
}
ctl_table ipv6_route_table_template[] = {
{
.procname = "flush",
.data = &init_net.ipv6.sysctl.flush_delay,
.maxlen = sizeof(int),
.mode = 0200,
.proc_handler = ipv6_sysctl_rtcache_flush
},
{
.procname = "gc_thresh",
.data = &ip6_dst_ops_template.gc_thresh,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "max_size",
.data = &init_net.ipv6.sysctl.ip6_rt_max_size,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "gc_min_interval",
.data = &init_net.ipv6.sysctl.ip6_rt_gc_min_interval,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "gc_timeout",
.data = &init_net.ipv6.sysctl.ip6_rt_gc_timeout,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "gc_interval",
.data = &init_net.ipv6.sysctl.ip6_rt_gc_interval,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "gc_elasticity",
.data = &init_net.ipv6.sysctl.ip6_rt_gc_elasticity,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "mtu_expires",
.data = &init_net.ipv6.sysctl.ip6_rt_mtu_expires,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{
.procname = "min_adv_mss",
.data = &init_net.ipv6.sysctl.ip6_rt_min_advmss,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{
.procname = "gc_min_interval_ms",
.data = &init_net.ipv6.sysctl.ip6_rt_gc_min_interval,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec_ms_jiffies,
},
{ }
};
struct ctl_table * __net_init ipv6_route_sysctl_init(struct net *net)
{
struct ctl_table *table;
table = kmemdup(ipv6_route_table_template,
sizeof(ipv6_route_table_template),
GFP_KERNEL);
if (table) {
table[0].data = &net->ipv6.sysctl.flush_delay;
table[0].extra1 = net;
table[1].data = &net->ipv6.ip6_dst_ops.gc_thresh;
table[2].data = &net->ipv6.sysctl.ip6_rt_max_size;
table[3].data = &net->ipv6.sysctl.ip6_rt_gc_min_interval;
table[4].data = &net->ipv6.sysctl.ip6_rt_gc_timeout;
table[5].data = &net->ipv6.sysctl.ip6_rt_gc_interval;
table[6].data = &net->ipv6.sysctl.ip6_rt_gc_elasticity;
table[7].data = &net->ipv6.sysctl.ip6_rt_mtu_expires;
table[8].data = &net->ipv6.sysctl.ip6_rt_min_advmss;
table[9].data = &net->ipv6.sysctl.ip6_rt_gc_min_interval;
/* Don't export sysctls to unprivileged users */
if (net->user_ns != &init_user_ns)
table[0].procname = NULL;
}
return table;
}
#endif
static int __net_init ip6_route_net_init(struct net *net)
{
int ret = -ENOMEM;
memcpy(&net->ipv6.ip6_dst_ops, &ip6_dst_ops_template,
sizeof(net->ipv6.ip6_dst_ops));
if (dst_entries_init(&net->ipv6.ip6_dst_ops) < 0)
goto out_ip6_dst_ops;
net->ipv6.ip6_null_entry = kmemdup(&ip6_null_entry_template,
sizeof(*net->ipv6.ip6_null_entry),
GFP_KERNEL);
if (!net->ipv6.ip6_null_entry)
goto out_ip6_dst_entries;
net->ipv6.ip6_null_entry->dst.path =
(struct dst_entry *)net->ipv6.ip6_null_entry;
net->ipv6.ip6_null_entry->dst.ops = &net->ipv6.ip6_dst_ops;
dst_init_metrics(&net->ipv6.ip6_null_entry->dst,
ip6_template_metrics, true);
#ifdef CONFIG_IPV6_MULTIPLE_TABLES
net->ipv6.ip6_prohibit_entry = kmemdup(&ip6_prohibit_entry_template,
sizeof(*net->ipv6.ip6_prohibit_entry),
GFP_KERNEL);
if (!net->ipv6.ip6_prohibit_entry)
goto out_ip6_null_entry;
net->ipv6.ip6_prohibit_entry->dst.path =
(struct dst_entry *)net->ipv6.ip6_prohibit_entry;
net->ipv6.ip6_prohibit_entry->dst.ops = &net->ipv6.ip6_dst_ops;
dst_init_metrics(&net->ipv6.ip6_prohibit_entry->dst,
ip6_template_metrics, true);
net->ipv6.ip6_blk_hole_entry = kmemdup(&ip6_blk_hole_entry_template,
sizeof(*net->ipv6.ip6_blk_hole_entry),
GFP_KERNEL);
if (!net->ipv6.ip6_blk_hole_entry)
goto out_ip6_prohibit_entry;
net->ipv6.ip6_blk_hole_entry->dst.path =
(struct dst_entry *)net->ipv6.ip6_blk_hole_entry;
net->ipv6.ip6_blk_hole_entry->dst.ops = &net->ipv6.ip6_dst_ops;
dst_init_metrics(&net->ipv6.ip6_blk_hole_entry->dst,
ip6_template_metrics, true);
#endif
net->ipv6.sysctl.flush_delay = 0;
net->ipv6.sysctl.ip6_rt_max_size = 4096;
net->ipv6.sysctl.ip6_rt_gc_min_interval = HZ / 2;
net->ipv6.sysctl.ip6_rt_gc_timeout = 60*HZ;
net->ipv6.sysctl.ip6_rt_gc_interval = 30*HZ;
net->ipv6.sysctl.ip6_rt_gc_elasticity = 9;
net->ipv6.sysctl.ip6_rt_mtu_expires = 10*60*HZ;
net->ipv6.sysctl.ip6_rt_min_advmss = IPV6_MIN_MTU - 20 - 40;
net->ipv6.ip6_rt_gc_expire = 30*HZ;
ret = 0;
out:
return ret;
#ifdef CONFIG_IPV6_MULTIPLE_TABLES
out_ip6_prohibit_entry:
kfree(net->ipv6.ip6_prohibit_entry);
out_ip6_null_entry:
kfree(net->ipv6.ip6_null_entry);
#endif
out_ip6_dst_entries:
dst_entries_destroy(&net->ipv6.ip6_dst_ops);
out_ip6_dst_ops:
goto out;
}
static void __net_exit ip6_route_net_exit(struct net *net)
{
kfree(net->ipv6.ip6_null_entry);
#ifdef CONFIG_IPV6_MULTIPLE_TABLES
kfree(net->ipv6.ip6_prohibit_entry);
kfree(net->ipv6.ip6_blk_hole_entry);
#endif
dst_entries_destroy(&net->ipv6.ip6_dst_ops);
}
static int __net_init ip6_route_net_init_late(struct net *net)
{
#ifdef CONFIG_PROC_FS
proc_net_fops_create(net, "ipv6_route", 0, &ipv6_route_proc_fops);
proc_net_fops_create(net, "rt6_stats", S_IRUGO, &rt6_stats_seq_fops);
#endif
return 0;
}
static void __net_exit ip6_route_net_exit_late(struct net *net)
{
#ifdef CONFIG_PROC_FS
proc_net_remove(net, "ipv6_route");
proc_net_remove(net, "rt6_stats");
#endif
}
static struct pernet_operations ip6_route_net_ops = {
.init = ip6_route_net_init,
.exit = ip6_route_net_exit,
};
static int __net_init ipv6_inetpeer_init(struct net *net)
{
struct inet_peer_base *bp = kmalloc(sizeof(*bp), GFP_KERNEL);
if (!bp)
return -ENOMEM;
inet_peer_base_init(bp);
net->ipv6.peers = bp;
return 0;
}
static void __net_exit ipv6_inetpeer_exit(struct net *net)
{
struct inet_peer_base *bp = net->ipv6.peers;
net->ipv6.peers = NULL;
inetpeer_invalidate_tree(bp);
kfree(bp);
}
static struct pernet_operations ipv6_inetpeer_ops = {
.init = ipv6_inetpeer_init,
.exit = ipv6_inetpeer_exit,
};
static struct pernet_operations ip6_route_net_late_ops = {
.init = ip6_route_net_init_late,
.exit = ip6_route_net_exit_late,
};
static struct notifier_block ip6_route_dev_notifier = {
.notifier_call = ip6_route_dev_notify,
.priority = 0,
};
int __init ip6_route_init(void)
{
int ret;
ret = -ENOMEM;
ip6_dst_ops_template.kmem_cachep =
kmem_cache_create("ip6_dst_cache", sizeof(struct rt6_info), 0,
SLAB_HWCACHE_ALIGN, NULL);
if (!ip6_dst_ops_template.kmem_cachep)
goto out;
ret = dst_entries_init(&ip6_dst_blackhole_ops);
if (ret)
goto out_kmem_cache;
ret = register_pernet_subsys(&ipv6_inetpeer_ops);
if (ret)
goto out_dst_entries;
ret = register_pernet_subsys(&ip6_route_net_ops);
if (ret)
goto out_register_inetpeer;
ip6_dst_blackhole_ops.kmem_cachep = ip6_dst_ops_template.kmem_cachep;
/* Registering of the loopback is done before this portion of code,
* the loopback reference in rt6_info will not be taken, do it
* manually for init_net */
init_net.ipv6.ip6_null_entry->dst.dev = init_net.loopback_dev;
init_net.ipv6.ip6_null_entry->rt6i_idev = in6_dev_get(init_net.loopback_dev);
#ifdef CONFIG_IPV6_MULTIPLE_TABLES
init_net.ipv6.ip6_prohibit_entry->dst.dev = init_net.loopback_dev;
init_net.ipv6.ip6_prohibit_entry->rt6i_idev = in6_dev_get(init_net.loopback_dev);
init_net.ipv6.ip6_blk_hole_entry->dst.dev = init_net.loopback_dev;
init_net.ipv6.ip6_blk_hole_entry->rt6i_idev = in6_dev_get(init_net.loopback_dev);
#endif
ret = fib6_init();
if (ret)
goto out_register_subsys;
ret = xfrm6_init();
if (ret)
goto out_fib6_init;
ret = fib6_rules_init();
if (ret)
goto xfrm6_init;
ret = register_pernet_subsys(&ip6_route_net_late_ops);
if (ret)
goto fib6_rules_init;
ret = -ENOBUFS;
if (__rtnl_register(PF_INET6, RTM_NEWROUTE, inet6_rtm_newroute, NULL, NULL) ||
__rtnl_register(PF_INET6, RTM_DELROUTE, inet6_rtm_delroute, NULL, NULL) ||
__rtnl_register(PF_INET6, RTM_GETROUTE, inet6_rtm_getroute, NULL, NULL))
goto out_register_late_subsys;
ret = register_netdevice_notifier(&ip6_route_dev_notifier);
if (ret)
goto out_register_late_subsys;
out:
return ret;
out_register_late_subsys:
unregister_pernet_subsys(&ip6_route_net_late_ops);
fib6_rules_init:
fib6_rules_cleanup();
xfrm6_init:
xfrm6_fini();
out_fib6_init:
fib6_gc_cleanup();
out_register_subsys:
unregister_pernet_subsys(&ip6_route_net_ops);
out_register_inetpeer:
unregister_pernet_subsys(&ipv6_inetpeer_ops);
out_dst_entries:
dst_entries_destroy(&ip6_dst_blackhole_ops);
out_kmem_cache:
kmem_cache_destroy(ip6_dst_ops_template.kmem_cachep);
goto out;
}
void ip6_route_cleanup(void)
{
unregister_netdevice_notifier(&ip6_route_dev_notifier);
unregister_pernet_subsys(&ip6_route_net_late_ops);
fib6_rules_cleanup();
xfrm6_fini();
fib6_gc_cleanup();
unregister_pernet_subsys(&ipv6_inetpeer_ops);
unregister_pernet_subsys(&ip6_route_net_ops);
dst_entries_destroy(&ip6_dst_blackhole_ops);
kmem_cache_destroy(ip6_dst_ops_template.kmem_cachep);
}
|
u9621071/kernel-uek-UEK3
|
net/ipv6/route.c
|
C
|
gpl-2.0
| 78,720
|
/*
Copyright (C) 2008-2016 Vana Development 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; version 2
of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#pragma once
#include "common/packet_handler.hpp"
namespace vana {
class packet_reader;
namespace channel_server {
class login_server_session final : public packet_handler, public enable_shared<login_server_session> {
NONCOPYABLE(login_server_session);
public:
login_server_session() = default;
protected:
auto handle(packet_reader &reader) -> result override;
auto on_connect() -> void override;
auto on_disconnect() -> void override;
};
}
}
|
retep998/Vana
|
src/channel_server/login_server_session.hpp
|
C++
|
gpl-2.0
| 1,160
|
/*************************************************************************/ /*!
@File
@Title RGX Transfer queue Functionality
@Copyright Copyright (c) Imagination Technologies Ltd. All Rights Reserved
@Description Header for the RGX Transfer queue Functionality
@License Dual MIT/GPLv2
The contents of this file are subject to the MIT license as set out below.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 ("GPL") in which case the provisions
of GPL are applicable instead of those above.
If you wish to allow use of your version of this file only under the terms of
GPL, and not to allow others to use your version of this file under the terms
of the MIT license, indicate your decision by deleting the provisions above
and replace them with the notice and other provisions required by GPL as set
out in the file called "GPL-COPYING" included in this distribution. If you do
not delete the provisions above, a recipient may use your version of this file
under the terms of either the MIT license or GPL.
This License is also included in this distribution in the file called
"MIT-COPYING".
EXCEPT AS OTHERWISE STATED IN A NEGOTIATED AGREEMENT: (A) THE SOFTWARE IS
PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT; AND (B) IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/ /**************************************************************************/
#if !defined(__RGXTRANSFER_H__)
#define __RGXTRANSFER_H__
#include "devicemem.h"
#include "device.h"
#include "rgxdevice.h"
#include "rgxfwutils.h"
#include "rgx_fwif_resetframework.h"
#include "sync_server.h"
#include "connection_server.h"
#if defined (__cplusplus)
extern "C" {
#endif
typedef struct _RGX_SERVER_TQ_CONTEXT_ RGX_SERVER_TQ_CONTEXT;
/*!
*******************************************************************************
@Function PVRSRVRGXCreateTransferContextKM
@Description
Server-side implementation of RGXCreateTransferContext
@Input pvDeviceNode - device node
FIXME fill this in
@Return PVRSRV_ERROR
******************************************************************************/
IMG_EXPORT
PVRSRV_ERROR PVRSRVRGXCreateTransferContextKM(CONNECTION_DATA *psConnection,
PVRSRV_DEVICE_NODE *psDeviceNode,
IMG_UINT32 ui32Priority,
IMG_DEV_VIRTADDR sMCUFenceAddr,
IMG_UINT32 ui32FrameworkCommandSize,
IMG_PBYTE pabyFrameworkCommand,
IMG_HANDLE hMemCtxPrivData,
RGX_SERVER_TQ_CONTEXT **ppsTransferContext);
/*!
*******************************************************************************
@Function PVRSRVRGXDestroyTransferContextKM
@Description
Server-side implementation of RGXDestroyTransferContext
@Input psTransferContext - Transfer context
@Return PVRSRV_ERROR
******************************************************************************/
IMG_EXPORT
PVRSRV_ERROR PVRSRVRGXDestroyTransferContextKM(RGX_SERVER_TQ_CONTEXT *psTransferContext);
/*!
*******************************************************************************
@Function PVRSRVSubmitTransferKM
@Description
Schedules one or more 2D or 3D HW commands on the firmware
@Return PVRSRV_ERROR
******************************************************************************/
IMG_EXPORT
PVRSRV_ERROR PVRSRVRGXSubmitTransferKM(RGX_SERVER_TQ_CONTEXT *psTransferContext,
IMG_UINT32 ui32PrepareCount,
IMG_UINT32 *paui32ClientFenceCount,
PRGXFWIF_UFO_ADDR **papauiClientFenceUFOAddress,
IMG_UINT32 **papaui32ClientFenceValue,
IMG_UINT32 *paui32ClientUpdateCount,
PRGXFWIF_UFO_ADDR **papauiClientUpdateUFOAddress,
IMG_UINT32 **papaui32ClientUpdateValue,
IMG_UINT32 *paui32ServerSyncCount,
IMG_UINT32 **papaui32ServerSyncFlags,
SERVER_SYNC_PRIMITIVE ***papapsServerSyncs,
IMG_UINT32 ui32NumFenceFDs,
IMG_INT32 *paui32FenceFDs,
IMG_UINT32 *paui32FWCommandSize,
IMG_UINT8 **papaui8FWCommand,
IMG_UINT32 *pui32TQPrepareFlags);
IMG_EXPORT
PVRSRV_ERROR PVRSRVRGXSetTransferContextPriorityKM(CONNECTION_DATA *psConnection,
RGX_SERVER_TQ_CONTEXT *psTransferContext,
IMG_UINT32 ui32Priority);
/* Debug - check if transfer context is waiting on a fence */
IMG_VOID CheckForStalledTransferCtxt(PVRSRV_RGXDEV_INFO *psDevInfo);
#endif /* __RGXTRANSFER_H__ */
|
jmztaylor/android_kernel_amazon_ariel
|
drivers/gpu/mt8135/rgx_1.3_2876724/services/server/devices/rgx/rgxtransfer.h
|
C
|
gpl-2.0
| 5,431
|
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
body
{
/* Font */
font-family: sans-serif, Arial, Verdana, "Trebuchet MS";
font-size: 12px;
/* Text color */
color: #333;
/* Remove the background color to make it transparent */
background-color: #fff;
margin: 20px;
}
.cke_editable
{
font-size: 13px;
line-height: 1.6;
}
blockquote
{
font-style: italic;
font-family: Georgia, Times, "Times New Roman", serif;
padding: 2px 0;
border-style: solid;
border-color: #ccc;
border-width: 0;
}
.cke_contents_ltr blockquote
{
padding-left: 20px;
padding-right: 8px;
border-left-width: 5px;
}
.cke_contents_rtl blockquote
{
padding-left: 8px;
padding-right: 20px;
border-right-width: 5px;
}
a
{
color: #0782C1;
}
ol,ul,dl
{
/* IE7: reset rtl list margin. (#7334) */
*margin-right: 0px;
/* preserved spaces for list items with text direction other than the list. (#6249,#8049)*/
padding: 0 40px;
}
h1,h2,h3,h4,h5,h6
{
font-weight: normal;
line-height: 1.2;
}
hr
{
border: 0px;
border-top: 1px solid #ccc;
}
img.right
{
border: 1px solid #ccc;
float: right;
margin-left: 15px;
padding: 5px;
}
img.left
{
border: 1px solid #ccc;
float: left;
margin-right: 15px;
padding: 5px;
}
pre
{
white-space: pre-wrap; /* CSS 2.1 */
word-wrap: break-word; /* IE7 */
-moz-tab-size: 4;
tab-size: 4;
}
.marker
{
background-color: Yellow;
}
span[lang]
{
font-style: italic;
}
figure
{
text-align: center;
border: solid 1px #ccc;
border-radius: 2px;
background: rgba(0,0,0,0.05);
padding: 10px;
margin: 10px 20px;
display: inline-block;
}
figure > figcaption
{
text-align: center;
display: block; /* For IE8 */
}
a > img {
padding: 1px;
margin: 1px;
border: none;
outline: 1px solid #0782C1;
}
|
TamasSzekeres/immense-meadow-9798
|
public/assets/ckeditor/contents.css
|
CSS
|
gpl-2.0
| 1,968
|
# Makefile for client-syslog
# Daniel B. Cid <dcid@ossec.net>
PT=../
NAME=ossec-csyslogd
include ../Config.Make
LOCAL = *.c
OBJS = ${OS_CONFIG} ${OS_SHARED} ${OS_NET} ${OS_REGEX} ${OS_XML}
default:
${CC} ${CFLAGS} ${OS_LINK} ${LOCAL} ${OBJS} -o ${NAME}
clean:
${CLEAN}
build:
${BUILD}
|
dcid/ossec-hids
|
src/os_csyslogd/Makefile
|
Makefile
|
gpl-2.0
| 297
|
/**
* @file
* Display Suite PW Two Rows Content and Sidebar stacked stylesheet.
*/
.ds-header {
/* Styles for the "header" region go here */
}
.ds-left-1 {
/* Styles for the "left-1" region go here */
}
.ds-right-1 {
/* Styles for the "right-1" region go here */
}
.ds-inbetween {
/* Styles for the "inbetween" region go here */
}
.ds-left-2 {
/* Styles for the "left-2" region go here */
}
.ds-right-2 {
/* Styles for the "right-2" region go here */
}
.ds-footer {
/* Styles for the "footer" region go here */
}
|
ver-di/svwatch
|
sites/all/themes/custom/parliamentwatch/ds_layouts/pw_with_sidebar_2rows_stacked/pw_with_sidebar_2rows_stacked.css
|
CSS
|
gpl-2.0
| 537
|
//========================== Open Steamworks ================================
//
// This file is part of the Open Steamworks project. All individuals associated
// with this project do not claim ownership of the contents
//
// The code, comments, and all related files, projects, resources,
// redistributables included with this project are Copyright Valve Corporation.
// Additionally, Valve, the Valve logo, Half-Life, the Half-Life logo, the
// Lambda logo, Steam, the Steam logo, Team Fortress, the Team Fortress logo,
// Opposing Force, Day of Defeat, the Day of Defeat logo, Counter-Strike, the
// Counter-Strike logo, Source, the Source logo, and Counter-Strike Condition
// Zero are trademarks and or registered trademarks of Valve Corporation.
// All other trademarks are property of their respective owners.
//
//=============================================================================
#ifndef ISTEAMGAMECOORDINATOR001_H
#define ISTEAMGAMECOORDINATOR001_H
#ifdef _WIN32
#pragma once
#endif
#include "SteamTypes.h"
#include "GameCoordinatorCommon.h"
//-----------------------------------------------------------------------------
// Purpose: Functions for sending and receiving messages from the Game Coordinator
// for this application
//-----------------------------------------------------------------------------
class ISteamGameCoordinator001
{
public:
// sends a message to the Game Coordinator
virtual EGCResults SendMessage( uint32 unMsgType, const void *pubData, uint32 cubData ) = 0;
// returns true if there is a message waiting from the game coordinator
virtual bool IsMessageAvailable( uint32 *pcubMsgSize ) = 0;
// fills the provided buffer with the first message in the queue and returns k_EGCResultOK or
// returns k_EGCResultNoMessage if there is no message waiting. pcubMsgSize is filled with the message size.
// If the provided buffer is not large enough to fit the entire message, k_EGCResultBufferTooSmall is returned
// and the message remains at the head of the queue.
virtual EGCResults RetrieveMessage( uint32 *punMsgType, void *pubDest, uint32 cubDest, uint32 *pcubMsgSize ) = 0;
};
#endif // ISTEAMGAMECOORDINATOR001_H
|
twominutesalad/aIW-Pi
|
Development/osw/ISteamGameCoordinator001.h
|
C
|
gpl-2.0
| 2,187
|
__doc__ = """Random number array generators for numarray.
This package was ported to numarray from Numeric's RandomArray and
provides functions to generate numarray of random numbers.
"""
from RandomArray2 import *
|
fxia22/ASM_xf
|
PythonD/site_python/numarray/random_array/__init__.py
|
Python
|
gpl-2.0
| 218
|
/*
* cmodlistview_moc.cpp, part of VCMI engine
*
* Authors: listed in file AUTHORS in main folder
*
* License: GNU General Public License v2.0 or later
* Full text of license available in license.txt file, in main folder
*
*/
#include "StdInc.h"
#include "cmodlistview_moc.h"
#include "ui_cmodlistview_moc.h"
#include "imageviewer_moc.h"
#include <QJsonArray>
#include <QCryptographicHash>
#include "cmodlistmodel_moc.h"
#include "cmodmanager.h"
#include "cdownloadmanager_moc.h"
#include "../launcherdirs.h"
#include "../../lib/CConfigHandler.h"
void CModListView::setupModModel()
{
modModel = new CModListModel();
manager = new CModManager(modModel);
}
void CModListView::setupFilterModel()
{
filterModel = new CModFilterModel(modModel);
filterModel->setFilterKeyColumn(-1); // filter across all columns
filterModel->setSortCaseSensitivity(Qt::CaseInsensitive); // to make it more user-friendly
filterModel->setDynamicSortFilter(true);
}
void CModListView::setupModsView()
{
ui->allModsView->setModel(filterModel);
// input data is not sorted - sort it before display
ui->allModsView->sortByColumn(ModFields::TYPE, Qt::AscendingOrder);
ui->allModsView->setColumnWidth(ModFields::NAME, 185);
ui->allModsView->setColumnWidth(ModFields::STATUS_ENABLED, 30);
ui->allModsView->setColumnWidth(ModFields::STATUS_UPDATE, 30);
ui->allModsView->setColumnWidth(ModFields::TYPE, 75);
ui->allModsView->setColumnWidth(ModFields::SIZE, 80);
ui->allModsView->setColumnWidth(ModFields::VERSION, 60);
ui->allModsView->header()->setSectionResizeMode(ModFields::STATUS_ENABLED, QHeaderView::Fixed);
ui->allModsView->header()->setSectionResizeMode(ModFields::STATUS_UPDATE, QHeaderView::Fixed);
ui->allModsView->setUniformRowHeights(true);
connect( ui->allModsView->selectionModel(), SIGNAL( currentRowChanged( const QModelIndex &, const QModelIndex & )),
this, SLOT( modSelected( const QModelIndex &, const QModelIndex & )));
connect( filterModel, SIGNAL( modelReset()),
this, SLOT( modelReset()));
connect( modModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
this, SLOT(dataChanged(QModelIndex,QModelIndex)));
}
CModListView::CModListView(QWidget *parent) :
QWidget(parent),
settingsListener(settings.listen["launcher"]["repositoryURL"]),
ui(new Ui::CModListView)
{
settingsListener([&](const JsonNode &){ repositoriesChanged = true; });
ui->setupUi(this);
setupModModel();
setupFilterModel();
setupModsView();
ui->progressWidget->setVisible(false);
dlManager = nullptr;
disableModInfo();
if (settings["launcher"]["autoCheckRepositories"].Bool())
{
loadRepositories();
}
else
{
manager->resetRepositories();
}
}
void CModListView::loadRepositories()
{
manager->resetRepositories();
for (auto entry : settings["launcher"]["repositoryURL"].Vector())
{
QString str = QString::fromUtf8(entry.String().c_str());
// URL must be encoded to something else to get rid of symbols illegal in file names
auto hashed = QCryptographicHash::hash(str.toUtf8(), QCryptographicHash::Md5);
auto hashedStr = QString::fromUtf8(hashed.toHex());
downloadFile(hashedStr + ".json", str, "repository index");
}
}
CModListView::~CModListView()
{
delete ui;
}
void CModListView::showEvent(QShowEvent * event)
{
QWidget::showEvent(event);
if (repositoriesChanged)
{
repositoriesChanged = false;
if (settings["launcher"]["autoCheckRepositories"].Bool())
{
loadRepositories();
}
}
}
void CModListView::showModInfo()
{
enableModInfo();
ui->modInfoWidget->show();
ui->hideModInfoButton->setArrowType(Qt::RightArrow);
ui->showInfoButton->setVisible(false);
loadScreenshots();
}
void CModListView::hideModInfo()
{
ui->modInfoWidget->hide();
ui->hideModInfoButton->setArrowType(Qt::LeftArrow);
ui->hideModInfoButton->setEnabled(true);
ui->showInfoButton->setVisible(true);
}
static QString replaceIfNotEmpty(QVariant value, QString pattern)
{
if (value.canConvert<QStringList>())
return pattern.arg(value.toStringList().join(", "));
if (value.canConvert<QString>())
return pattern.arg(value.toString());
// all valid types of data should have been filtered by code above
assert(!value.isValid());
return "";
}
static QString replaceIfNotEmpty(QStringList value, QString pattern)
{
if (!value.empty())
return pattern.arg(value.join(", "));
return "";
}
QString CModListView::genChangelogText(CModEntry &mod)
{
QString headerTemplate = "<p><span style=\" font-weight:600;\">%1: </span></p>";
QString entryBegin = "<p align=\"justify\"><ul>";
QString entryEnd = "</ul></p>";
QString entryLine = "<li>%1</li>";
//QString versionSeparator = "<hr/>";
QString result;
QVariantMap changelog = mod.getValue("changelog").toMap();
QList<QString> versions = changelog.keys();
std::sort(versions.begin(), versions.end(), [](QString lesser, QString greater)
{
return !CModEntry::compareVersions(lesser, greater);
});
for (auto & version : versions)
{
result += headerTemplate.arg(version);
result += entryBegin;
for (auto & line : changelog.value(version).toStringList())
result += entryLine.arg(line);
result += entryEnd;
}
return result;
}
QString CModListView::genModInfoText(CModEntry &mod)
{
QString prefix = "<p><span style=\" font-weight:600;\">%1: </span>"; // shared prefix
QString lineTemplate = prefix + "%2</p>";
QString urlTemplate = prefix + "<a href=\"%2\">%3</a></p>";
QString textTemplate = prefix + "</p><p align=\"justify\">%2</p>";
QString listTemplate = "<p align=\"justify\">%1: %2</p>";
QString noteTemplate = "<p align=\"justify\">%1</p>";
QString result;
result += replaceIfNotEmpty(mod.getValue("name"), lineTemplate.arg(tr("Mod name")));
result += replaceIfNotEmpty(mod.getValue("installedVersion"), lineTemplate.arg(tr("Installed version")));
result += replaceIfNotEmpty(mod.getValue("latestVersion"), lineTemplate.arg(tr("Latest version")));
if (mod.getValue("size").isValid())
result += replaceIfNotEmpty(CModEntry::sizeToString(mod.getValue("size").toDouble()), lineTemplate.arg(tr("Download size")));
result += replaceIfNotEmpty(mod.getValue("author"), lineTemplate.arg(tr("Authors")));
if (mod.getValue("licenseURL").isValid())
result += urlTemplate.arg(tr("License")).arg(mod.getValue("licenseURL").toString()).arg(mod.getValue("licenseName").toString());
if (mod.getValue("contact").isValid())
result += urlTemplate.arg(tr("Home")).arg(mod.getValue("contact").toString()).arg(mod.getValue("contact").toString());
result += replaceIfNotEmpty(mod.getValue("depends"), lineTemplate.arg(tr("Required mods")));
result += replaceIfNotEmpty(mod.getValue("conflicts"), lineTemplate.arg(tr("Conflicting mods")));
result += replaceIfNotEmpty(mod.getValue("description"), textTemplate.arg(tr("Description")));
result += "<p></p>"; // to get some empty space
QString unknownDeps = tr("This mod can not be installed or enabled because following dependencies are not present");
QString blockingMods = tr("This mod can not be enabled because following mods are incompatible with this mod");
QString hasActiveDependentMods = tr("This mod can not be disabled because it is required to run following mods");
QString hasDependentMods = tr("This mod can not be uninstalled or updated because it is required to run following mods");
QString thisIsSubmod = tr("This is submod and it can not be installed or uninstalled separately from parent mod");
QString notes;
notes += replaceIfNotEmpty(findInvalidDependencies(mod.getName()), listTemplate.arg(unknownDeps));
notes += replaceIfNotEmpty(findBlockingMods(mod.getName()), listTemplate.arg(blockingMods));
if (mod.isEnabled())
notes += replaceIfNotEmpty(findDependentMods(mod.getName(), true), listTemplate.arg(hasActiveDependentMods));
if (mod.isInstalled())
notes += replaceIfNotEmpty(findDependentMods(mod.getName(), false), listTemplate.arg(hasDependentMods));
if (mod.getName().contains('.'))
notes += noteTemplate.arg(thisIsSubmod);
if (notes.size())
result += textTemplate.arg(tr("Notes")).arg(notes);
return result;
}
void CModListView::enableModInfo()
{
ui->hideModInfoButton->setEnabled(true);
ui->showInfoButton->setVisible(true);
}
void CModListView::disableModInfo()
{
hideModInfo();
ui->hideModInfoButton->setEnabled(false);
ui->showInfoButton->setVisible(false);
ui->disableButton->setVisible(false);
ui->enableButton->setVisible(false);
ui->installButton->setVisible(false);
ui->uninstallButton->setVisible(false);
ui->updateButton->setVisible(false);
}
void CModListView::dataChanged(const QModelIndex & topleft, const QModelIndex & bottomRight)
{
selectMod(ui->allModsView->currentIndex());
}
void CModListView::selectMod(const QModelIndex & index)
{
if (!index.isValid())
{
disableModInfo();
}
else
{
auto mod = modModel->getMod(index.data(ModRoles::ModNameRole).toString());
ui->modInfoBrowser->setHtml(genModInfoText(mod));
ui->changelogBrowser->setHtml(genChangelogText(mod));
bool hasInvalidDeps = !findInvalidDependencies(index.data(ModRoles::ModNameRole).toString()).empty();
bool hasBlockingMods = !findBlockingMods(index.data(ModRoles::ModNameRole).toString()).empty();
bool hasDependentMods = !findDependentMods(index.data(ModRoles::ModNameRole).toString(), true).empty();
ui->hideModInfoButton->setEnabled(true);
ui->showInfoButton->setVisible(!ui->modInfoWidget->isVisible());
ui->disableButton->setVisible(mod.isEnabled());
ui->enableButton->setVisible(mod.isDisabled());
ui->installButton->setVisible(mod.isAvailable() && !mod.getName().contains('.'));
ui->uninstallButton->setVisible(mod.isInstalled() && !mod.getName().contains('.'));
ui->updateButton->setVisible(mod.isUpdateable());
// Block buttons if action is not allowed at this time
// TODO: automate handling of some of these cases instead of forcing player
// to resolve all conflicts manually.
ui->disableButton->setEnabled(!hasDependentMods);
ui->enableButton->setEnabled(!hasBlockingMods && !hasInvalidDeps);
ui->installButton->setEnabled(!hasInvalidDeps);
ui->uninstallButton->setEnabled(!hasDependentMods);
ui->updateButton->setEnabled(!hasInvalidDeps && !hasDependentMods);
loadScreenshots();
}
}
void CModListView::keyPressEvent(QKeyEvent * event)
{
if (event->key() == Qt::Key_Escape && ui->modInfoWidget->isVisible() )
{
hideModInfo();
}
else
{
return QWidget::keyPressEvent(event);
}
}
void CModListView::modSelected(const QModelIndex & current, const QModelIndex & )
{
selectMod(current);
}
void CModListView::on_hideModInfoButton_clicked()
{
if (ui->modInfoWidget->isVisible())
hideModInfo();
else
showModInfo();
}
void CModListView::on_allModsView_activated(const QModelIndex &index)
{
showModInfo();
selectMod(index);
}
void CModListView::on_lineEdit_textChanged(const QString &arg1)
{
QRegExp regExp(arg1, Qt::CaseInsensitive, QRegExp::Wildcard);
filterModel->setFilterRegExp(regExp);
}
void CModListView::on_comboBox_currentIndexChanged(int index)
{
switch (index)
{
break; case 0: filterModel->setTypeFilter(ModStatus::MASK_NONE, ModStatus::MASK_NONE);
break; case 1: filterModel->setTypeFilter(ModStatus::MASK_NONE, ModStatus::INSTALLED);
break; case 2: filterModel->setTypeFilter(ModStatus::INSTALLED, ModStatus::INSTALLED);
break; case 3: filterModel->setTypeFilter(ModStatus::UPDATEABLE, ModStatus::UPDATEABLE);
break; case 4: filterModel->setTypeFilter(ModStatus::ENABLED | ModStatus::INSTALLED, ModStatus::ENABLED | ModStatus::INSTALLED);
break; case 5: filterModel->setTypeFilter(ModStatus::INSTALLED, ModStatus::ENABLED | ModStatus::INSTALLED);
}
}
QStringList CModListView::findInvalidDependencies(QString mod)
{
QStringList ret;
for (QString requrement : modModel->getRequirements(mod))
{
if (!modModel->hasMod(requrement))
ret += requrement;
}
return ret;
}
QStringList CModListView::findBlockingMods(QString mod)
{
QStringList ret;
auto required = modModel->getRequirements(mod);
for (QString name : modModel->getModList())
{
auto mod = modModel->getMod(name);
if (mod.isEnabled())
{
// one of enabled mods have requirement (or this mod) marked as conflict
for (auto conflict : mod.getValue("conflicts").toStringList())
if (required.contains(conflict))
ret.push_back(name);
}
}
return ret;
}
QStringList CModListView::findDependentMods(QString mod, bool excludeDisabled)
{
QStringList ret;
for (QString modName : modModel->getModList())
{
auto current = modModel->getMod(modName);
if (!current.isInstalled())
continue;
if (current.getValue("depends").toStringList().contains(mod) &&
!(current.isDisabled() && excludeDisabled))
ret += modName;
}
return ret;
}
void CModListView::on_enableButton_clicked()
{
QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
assert(findBlockingMods(modName).empty());
assert(findInvalidDependencies(modName).empty());
for (auto & name : modModel->getRequirements(modName))
if (modModel->getMod(name).isDisabled())
manager->enableMod(name);
checkManagerErrors();
}
void CModListView::on_disableButton_clicked()
{
QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
if (modModel->hasMod(modName) &&
modModel->getMod(modName).isEnabled())
manager->disableMod(modName);
checkManagerErrors();
}
void CModListView::on_updateButton_clicked()
{
QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
assert(findInvalidDependencies(modName).empty());
for (auto & name : modModel->getRequirements(modName))
{
auto mod = modModel->getMod(name);
// update required mod, install missing (can be new dependency)
if (mod.isUpdateable() || !mod.isInstalled())
downloadFile(name + ".zip", mod.getValue("download").toString(), "mods");
}
}
void CModListView::on_uninstallButton_clicked()
{
QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
// NOTE: perhaps add "manually installed" flag and uninstall those dependencies that don't have it?
if (modModel->hasMod(modName) &&
modModel->getMod(modName).isInstalled())
{
if (modModel->getMod(modName).isEnabled())
manager->disableMod(modName);
manager->uninstallMod(modName);
}
checkManagerErrors();
}
void CModListView::on_installButton_clicked()
{
QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
assert(findInvalidDependencies(modName).empty());
for (auto & name : modModel->getRequirements(modName))
{
auto mod = modModel->getMod(name);
if (!mod.isInstalled())
downloadFile(name + ".zip", mod.getValue("download").toString(), "mods");
}
}
void CModListView::downloadFile(QString file, QString url, QString description)
{
if (!dlManager)
{
dlManager = new CDownloadManager();
ui->progressWidget->setVisible(true);
connect(dlManager, SIGNAL(downloadProgress(qint64,qint64)),
this, SLOT(downloadProgress(qint64,qint64)));
connect(dlManager, SIGNAL(finished(QStringList,QStringList,QStringList)),
this, SLOT(downloadFinished(QStringList,QStringList,QStringList)));
QString progressBarFormat = "Downloading %s%. %p% (%v KB out of %m KB) finished";
progressBarFormat.replace("%s%", description);
ui->progressBar->setFormat(progressBarFormat);
}
dlManager->downloadFile(QUrl(url), file);
}
void CModListView::downloadProgress(qint64 current, qint64 max)
{
// display progress, in kilobytes
ui->progressBar->setValue(current/1024);
ui->progressBar->setMaximum(max/1024);
}
void CModListView::downloadFinished(QStringList savedFiles, QStringList failedFiles, QStringList errors)
{
QString title = "Download failed";
QString firstLine = "Unable to download all files.\n\nEncountered errors:\n\n";
QString lastLine = "\n\nInstall successfully downloaded?";
// if all files were d/loaded there should be no errors. And on failure there must be an error
assert(failedFiles.empty() == errors.empty());
if (savedFiles.empty())
{
// no successfully downloaded mods
QMessageBox::warning(this, title, firstLine + errors.join("\n"), QMessageBox::Ok, QMessageBox::Ok );
}
else if (!failedFiles.empty())
{
// some mods were not downloaded
int result = QMessageBox::warning (this, title, firstLine + errors.join("\n") + lastLine,
QMessageBox::Yes | QMessageBox::No, QMessageBox::No );
if (result == QMessageBox::Yes)
installFiles(savedFiles);
}
else
{
// everything OK
installFiles(savedFiles);
}
// remove progress bar after some delay so user can see that download was complete and not interrupted.
QTimer::singleShot(1000, this, SLOT(hideProgressBar()));
dlManager->deleteLater();
dlManager = nullptr;
}
void CModListView::hideProgressBar()
{
if (dlManager == nullptr) // it was not recreated meanwhile
{
ui->progressWidget->setVisible(false);
ui->progressBar->setMaximum(0);
ui->progressBar->setValue(0);
}
}
void CModListView::installFiles(QStringList files)
{
QStringList mods;
QStringList images;
// TODO: some better way to separate zip's with mods and downloaded repository files
for (QString filename : files)
{
if (filename.endsWith(".zip"))
mods.push_back(filename);
if (filename.endsWith(".json"))
manager->loadRepository(filename);
if (filename.endsWith(".png"))
images.push_back(filename);
}
if (!mods.empty())
installMods(mods);
if (!images.empty())
loadScreenshots();
}
void CModListView::installMods(QStringList archives)
{
QStringList modNames;
for (QString archive : archives)
{
// get basename out of full file name
// remove path remove extension
QString modName = archive.section('/', -1, -1).section('.', 0, 0);
modNames.push_back(modName);
}
QStringList modsToEnable;
// disable mod(s), to properly recalculate dependencies, if changed
for (QString mod : boost::adaptors::reverse(modNames))
{
CModEntry entry = modModel->getMod(mod);
if (entry.isInstalled())
{
// enable mod if installed and enabled
if (entry.isEnabled())
modsToEnable.push_back(mod);
}
else
{
// enable mod if m
if (settings["launcher"]["enableInstalledMods"].Bool())
modsToEnable.push_back(mod);
}
}
// uninstall old version of mod, if installed
for (QString mod : boost::adaptors::reverse(modNames))
{
if (modModel->getMod(mod).isInstalled())
manager->uninstallMod(mod);
}
for (int i=0; i<modNames.size(); i++)
manager->installMod(modNames[i], archives[i]);
std::function<void(QString)> enableMod;
enableMod = [&](QString modName)
{
auto mod = modModel->getMod(modName);
if (mod.isInstalled() && !mod.getValue("keepDisabled").toBool())
{
if (manager->enableMod(modName))
{
for (QString child : modModel->getChildren(modName))
enableMod(child);
}
}
};
for (QString mod : modsToEnable)
{
enableMod(mod);
}
for (QString archive : archives)
QFile::remove(archive);
checkManagerErrors();
}
void CModListView::on_refreshButton_clicked()
{
loadRepositories();
}
void CModListView::on_pushButton_clicked()
{
delete dlManager;
dlManager = nullptr;
hideProgressBar();
}
void CModListView::modelReset()
{
if (ui->modInfoWidget->isVisible())
selectMod(filterModel->rowCount() > 0 ? filterModel->index(0,0) : QModelIndex());
}
void CModListView::checkManagerErrors()
{
QString errors = manager->getErrors().join('\n');
if (errors.size() != 0)
{
QString title = "Operation failed";
QString description = "Encountered errors:\n" + errors;
QMessageBox::warning(this, title, description, QMessageBox::Ok, QMessageBox::Ok );
}
}
void CModListView::on_tabWidget_currentChanged(int index)
{
loadScreenshots();
}
void CModListView::loadScreenshots()
{
if (ui->tabWidget->currentIndex() == 2 && ui->modInfoWidget->isVisible())
{
ui->screenshotsList->clear();
QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
assert(modModel->hasMod(modName)); //should be filtered out by check above
for (QString & url : modModel->getMod(modName).getValue("screenshots").toStringList())
{
// URL must be encoded to something else to get rid of symbols illegal in file names
auto hashed = QCryptographicHash::hash(url.toUtf8(), QCryptographicHash::Md5);
auto hashedStr = QString::fromUtf8(hashed.toHex());
QString fullPath = CLauncherDirs::get().downloadsPath() + '/' + hashedStr + ".png";
QPixmap pixmap(fullPath);
if (pixmap.isNull())
{
// image file not exists or corrupted - try to redownload
downloadFile(hashedStr + ".png", url, "screenshots");
}
else
{
// managed to load cached image
QIcon icon(pixmap);
QListWidgetItem * item = new QListWidgetItem(icon, QString(tr("Screenshot %1")).arg(ui->screenshotsList->count() + 1));
ui->screenshotsList->addItem(item);
}
}
}
}
void CModListView::on_screenshotsList_clicked(const QModelIndex &index)
{
if (index.isValid())
{
QIcon icon = ui->screenshotsList->item(index.row())->icon();
auto pixmap = icon.pixmap(icon.availableSizes()[0]);
ImageViewer::showPixmap(pixmap, this);
}
}
void CModListView::on_showInfoButton_clicked()
{
showModInfo();
}
|
ArseniyShestakov/vcmi
|
launcher/modManager/cmodlistview_moc.cpp
|
C++
|
gpl-2.0
| 21,268
|
/*
Copyright (C) 1997-2001 Id Software, 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 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "shared/shared.h"
#include "common/msg.h"
#include "common/protocol.h"
#include "common/sizebuf.h"
#include "common/math.h"
/*
==============================================================================
MESSAGE IO FUNCTIONS
Handles byte ordering and avoids alignment errors
==============================================================================
*/
sizebuf_t msg_write;
byte msg_write_buffer[MAX_MSGLEN];
sizebuf_t msg_read;
byte msg_read_buffer[MAX_MSGLEN];
const entity_packed_t nullEntityState;
const player_packed_t nullPlayerState;
const usercmd_t nullUserCmd;
/*
=============
MSG_Init
Initialize default buffers, clearing allow overflow/underflow flags.
This is the only place where writing buffer is initialized. Writing buffer is
never allowed to overflow.
Reading buffer is reinitialized in many other places. Reinitializing will set
the allow underflow flag as appropriate.
=============
*/
void MSG_Init(void)
{
SZ_TagInit(&msg_read, msg_read_buffer, MAX_MSGLEN, SZ_MSG_READ);
SZ_TagInit(&msg_write, msg_write_buffer, MAX_MSGLEN, SZ_MSG_WRITE);
}
/*
==============================================================================
WRITING
==============================================================================
*/
/*
=============
MSG_BeginWriting
=============
*/
void MSG_BeginWriting(void)
{
msg_write.cursize = 0;
msg_write.bitpos = 0;
msg_write.overflowed = qfalse;
}
/*
=============
MSG_WriteChar
=============
*/
void MSG_WriteChar(int c)
{
byte *buf;
#ifdef PARANOID
if (c < -128 || c > 127)
Com_Error(ERR_FATAL, "MSG_WriteChar: range error");
#endif
buf = SZ_GetSpace(&msg_write, 1);
buf[0] = c;
}
/*
=============
MSG_WriteByte
=============
*/
void MSG_WriteByte(int c)
{
byte *buf;
#ifdef PARANOID
if (c < 0 || c > 255)
Com_Error(ERR_FATAL, "MSG_WriteByte: range error");
#endif
buf = SZ_GetSpace(&msg_write, 1);
buf[0] = c;
}
/*
=============
MSG_WriteShort
=============
*/
void MSG_WriteShort(int c)
{
byte *buf;
#ifdef PARANOID
if (c < ((short)0x8000) || c > (short)0x7fff)
Com_Error(ERR_FATAL, "MSG_WriteShort: range error");
#endif
buf = SZ_GetSpace(&msg_write, 2);
buf[0] = c & 0xff;
buf[1] = c >> 8;
}
/*
=============
MSG_WriteLong
=============
*/
void MSG_WriteLong(int c)
{
byte *buf;
buf = SZ_GetSpace(&msg_write, 4);
buf[0] = c & 0xff;
buf[1] = (c >> 8) & 0xff;
buf[2] = (c >> 16) & 0xff;
buf[3] = c >> 24;
}
/*
=============
MSG_WriteString
=============
*/
void MSG_WriteString(const char *string)
{
size_t length;
if (!string) {
MSG_WriteByte(0);
return;
}
length = strlen(string);
if (length >= MAX_NET_STRING) {
Com_WPrintf("%s: overflow: %"PRIz" chars", __func__, length);
MSG_WriteByte(0);
return;
}
MSG_WriteData(string, length + 1);
}
/*
=============
MSG_WriteCoord
=============
*/
#define COORD2SHORT(x) ((int)((x)*8.0f))
#define SHORT2COORD(x) ((x)*(1.0f/8))
static inline void MSG_WriteCoord(float f)
{
MSG_WriteShort(COORD2SHORT(f));
}
/*
=============
MSG_WritePos
=============
*/
void MSG_WritePos(const vec3_t pos)
{
MSG_WriteCoord(pos[0]);
MSG_WriteCoord(pos[1]);
MSG_WriteCoord(pos[2]);
}
/*
=============
MSG_WriteAngle
=============
*/
#define ANGLE2BYTE(x) ((int)((x)*256.0f/360)&255)
#define BYTE2ANGLE(x) ((x)*(360.0f/256))
void MSG_WriteAngle(float f)
{
MSG_WriteByte(ANGLE2BYTE(f));
}
#if USE_CLIENT
/*
=============
MSG_WriteDeltaUsercmd
=============
*/
int MSG_WriteDeltaUsercmd(const usercmd_t *from, const usercmd_t *cmd, int version)
{
int bits, buttons = cmd->buttons & BUTTON_MASK;
if (!from) {
from = &nullUserCmd;
}
//
// send the movement message
//
bits = 0;
if (cmd->angles[0] != from->angles[0])
bits |= CM_ANGLE1;
if (cmd->angles[1] != from->angles[1])
bits |= CM_ANGLE2;
if (cmd->angles[2] != from->angles[2])
bits |= CM_ANGLE3;
if (cmd->forwardmove != from->forwardmove)
bits |= CM_FORWARD;
if (cmd->sidemove != from->sidemove)
bits |= CM_SIDE;
if (cmd->upmove != from->upmove)
bits |= CM_UP;
if (cmd->buttons != from->buttons)
bits |= CM_BUTTONS;
if (cmd->impulse != from->impulse)
bits |= CM_IMPULSE;
MSG_WriteByte(bits);
if (version >= PROTOCOL_VERSION_R1Q2_UCMD) {
if (bits & CM_BUTTONS) {
if ((bits & CM_FORWARD) && !(cmd->forwardmove % 5)) {
buttons |= BUTTON_FORWARD;
}
if ((bits & CM_SIDE) && !(cmd->sidemove % 5)) {
buttons |= BUTTON_SIDE;
}
if ((bits & CM_UP) && !(cmd->upmove % 5)) {
buttons |= BUTTON_UP;
}
MSG_WriteByte(buttons);
}
}
if (bits & CM_ANGLE1)
MSG_WriteShort(cmd->angles[0]);
if (bits & CM_ANGLE2)
MSG_WriteShort(cmd->angles[1]);
if (bits & CM_ANGLE3)
MSG_WriteShort(cmd->angles[2]);
if (bits & CM_FORWARD) {
if (buttons & BUTTON_FORWARD) {
MSG_WriteChar(cmd->forwardmove / 5);
} else {
MSG_WriteShort(cmd->forwardmove);
}
}
if (bits & CM_SIDE) {
if (buttons & BUTTON_SIDE) {
MSG_WriteChar(cmd->sidemove / 5);
} else {
MSG_WriteShort(cmd->sidemove);
}
}
if (bits & CM_UP) {
if (buttons & BUTTON_UP) {
MSG_WriteChar(cmd->upmove / 5);
} else {
MSG_WriteShort(cmd->upmove);
}
}
if (version < PROTOCOL_VERSION_R1Q2_UCMD) {
if (bits & CM_BUTTONS)
MSG_WriteByte(cmd->buttons);
}
if (bits & CM_IMPULSE)
MSG_WriteByte(cmd->impulse);
MSG_WriteByte(cmd->msec);
return bits;
}
/*
=============
MSG_WriteBits
=============
*/
void MSG_WriteBits(int value, int bits)
{
int i;
size_t bitpos;
if (bits == 0 || bits < -31 || bits > 32) {
Com_Error(ERR_FATAL, "MSG_WriteBits: bad bits: %d", bits);
}
if (msg_write.maxsize - msg_write.cursize < 4) {
Com_Error(ERR_FATAL, "MSG_WriteBits: overflow");
}
if (bits < 0) {
bits = -bits;
}
bitpos = msg_write.bitpos;
if ((bitpos & 7) == 0) {
// optimized case
switch (bits) {
case 8:
MSG_WriteByte(value);
return;
case 16:
MSG_WriteShort(value);
return;
case 32:
MSG_WriteLong(value);
return;
default:
break;
}
}
for (i = 0; i < bits; i++, bitpos++) {
if ((bitpos & 7) == 0) {
msg_write.data[bitpos >> 3] = 0;
}
msg_write.data[bitpos >> 3] |= (value & 1) << (bitpos & 7);
value >>= 1;
}
msg_write.bitpos = bitpos;
msg_write.cursize = (bitpos + 7) >> 3;
}
/*
=============
MSG_WriteDeltaUsercmd_Enhanced
=============
*/
int MSG_WriteDeltaUsercmd_Enhanced(const usercmd_t *from,
const usercmd_t *cmd,
int version)
{
int bits, delta, count;
if (!from) {
from = &nullUserCmd;
}
//
// send the movement message
//
bits = 0;
if (cmd->angles[0] != from->angles[0])
bits |= CM_ANGLE1;
if (cmd->angles[1] != from->angles[1])
bits |= CM_ANGLE2;
if (cmd->angles[2] != from->angles[2])
bits |= CM_ANGLE3;
if (cmd->forwardmove != from->forwardmove)
bits |= CM_FORWARD;
if (cmd->sidemove != from->sidemove)
bits |= CM_SIDE;
if (cmd->upmove != from->upmove)
bits |= CM_UP;
if (cmd->buttons != from->buttons)
bits |= CM_BUTTONS;
if (cmd->msec != from->msec)
bits |= CM_IMPULSE;
if (!bits) {
MSG_WriteBits(0, 1);
return 0;
}
MSG_WriteBits(1, 1);
MSG_WriteBits(bits, 8);
if (bits & CM_ANGLE1) {
delta = cmd->angles[0] - from->angles[0];
if (delta >= -128 && delta <= 127) {
MSG_WriteBits(1, 1);
MSG_WriteBits(delta, -8);
} else {
MSG_WriteBits(0, 1);
MSG_WriteBits(cmd->angles[0], -16);
}
}
if (bits & CM_ANGLE2) {
delta = cmd->angles[1] - from->angles[1];
if (delta >= -128 && delta <= 127) {
MSG_WriteBits(1, 1);
MSG_WriteBits(delta, -8);
} else {
MSG_WriteBits(0, 1);
MSG_WriteBits(cmd->angles[1], -16);
}
}
if (bits & CM_ANGLE3) {
MSG_WriteBits(cmd->angles[2], -16);
}
if (version >= PROTOCOL_VERSION_Q2PRO_UCMD) {
count = -10;
} else {
count = -16;
}
if (bits & CM_FORWARD) {
MSG_WriteBits(cmd->forwardmove, count);
}
if (bits & CM_SIDE) {
MSG_WriteBits(cmd->sidemove, count);
}
if (bits & CM_UP) {
MSG_WriteBits(cmd->upmove, count);
}
if (bits & CM_BUTTONS) {
int buttons = (cmd->buttons & 3) | (cmd->buttons >> 5);
MSG_WriteBits(buttons, 3);
}
if (bits & CM_IMPULSE) {
MSG_WriteBits(cmd->msec, 8);
}
return bits;
}
#endif // USE_CLIENT
void MSG_WriteDir(const vec3_t dir)
{
int best;
best = DirToByte(dir);
MSG_WriteByte(best);
}
void MSG_PackEntity(entity_packed_t *out, const entity_state_t *in, qboolean short_angles)
{
// allow 0 to accomodate empty baselines
if (in->number < 0 || in->number >= MAX_EDICTS)
Com_Error(ERR_DROP, "%s: bad number: %d", __func__, in->number);
out->number = in->number;
out->origin[0] = COORD2SHORT(in->origin[0]);
out->origin[1] = COORD2SHORT(in->origin[1]);
out->origin[2] = COORD2SHORT(in->origin[2]);
if (short_angles) {
out->angles[0] = ANGLE2SHORT(in->angles[0]);
out->angles[1] = ANGLE2SHORT(in->angles[1]);
out->angles[2] = ANGLE2SHORT(in->angles[2]);
} else {
// pack angles8 akin to angles16 to make delta compression happy when
// precision suddenly changes between entity updates
out->angles[0] = ANGLE2BYTE(in->angles[0]) << 8;
out->angles[1] = ANGLE2BYTE(in->angles[1]) << 8;
out->angles[2] = ANGLE2BYTE(in->angles[2]) << 8;
}
out->old_origin[0] = COORD2SHORT(in->old_origin[0]);
out->old_origin[1] = COORD2SHORT(in->old_origin[1]);
out->old_origin[2] = COORD2SHORT(in->old_origin[2]);
out->modelindex = in->modelindex;
out->modelindex2 = in->modelindex2;
out->modelindex3 = in->modelindex3;
out->modelindex4 = in->modelindex4;
out->skinnum = in->skinnum;
out->effects = in->effects;
out->renderfx = in->renderfx;
out->solid = in->solid;
out->frame = in->frame;
out->sound = in->sound;
out->event = in->event;
}
void MSG_WriteDeltaEntity(const entity_packed_t *from,
const entity_packed_t *to,
msgEsFlags_t flags)
{
uint32_t bits, mask;
if (!to) {
if (!from)
Com_Error(ERR_DROP, "%s: NULL", __func__);
if (from->number < 1 || from->number >= MAX_EDICTS)
Com_Error(ERR_DROP, "%s: bad number: %d", __func__, from->number);
bits = U_REMOVE;
if (from->number & 0xff00)
bits |= U_NUMBER16 | U_MOREBITS1;
MSG_WriteByte(bits & 255);
if (bits & 0x0000ff00)
MSG_WriteByte((bits >> 8) & 255);
if (bits & U_NUMBER16)
MSG_WriteShort(from->number);
else
MSG_WriteByte(from->number);
return; // remove entity
}
if (to->number < 1 || to->number >= MAX_EDICTS)
Com_Error(ERR_DROP, "%s: bad number: %d", __func__, to->number);
if (!from)
from = &nullEntityState;
// send an update
bits = 0;
if (!(flags & MSG_ES_FIRSTPERSON)) {
if (to->origin[0] != from->origin[0])
bits |= U_ORIGIN1;
if (to->origin[1] != from->origin[1])
bits |= U_ORIGIN2;
if (to->origin[2] != from->origin[2])
bits |= U_ORIGIN3;
if (flags & MSG_ES_SHORTANGLES) {
if (to->angles[0] != from->angles[0])
bits |= U_ANGLE1 | U_ANGLE16;
if (to->angles[1] != from->angles[1])
bits |= U_ANGLE2 | U_ANGLE16;
if (to->angles[2] != from->angles[2])
bits |= U_ANGLE3 | U_ANGLE16;
} else {
if (to->angles[0] != from->angles[0])
bits |= U_ANGLE1;
if (to->angles[1] != from->angles[1])
bits |= U_ANGLE2;
if (to->angles[2] != from->angles[2])
bits |= U_ANGLE3;
}
if (flags & MSG_ES_NEWENTITY) {
if (to->old_origin[0] != from->origin[0] ||
to->old_origin[1] != from->origin[1] ||
to->old_origin[2] != from->origin[2])
bits |= U_OLDORIGIN;
}
}
if (flags & MSG_ES_UMASK)
mask = 0xffff0000;
else
mask = 0xffff8000; // don't confuse old clients
if (to->skinnum != from->skinnum) {
if (to->skinnum & mask)
bits |= U_SKIN8 | U_SKIN16;
else if (to->skinnum & 0x0000ff00)
bits |= U_SKIN16;
else
bits |= U_SKIN8;
}
if (to->frame != from->frame) {
if (to->frame & 0xff00)
bits |= U_FRAME16;
else
bits |= U_FRAME8;
}
if (to->effects != from->effects) {
if (to->effects & mask)
bits |= U_EFFECTS8 | U_EFFECTS16;
else if (to->effects & 0x0000ff00)
bits |= U_EFFECTS16;
else
bits |= U_EFFECTS8;
}
if (to->renderfx != from->renderfx) {
if (to->renderfx & mask)
bits |= U_RENDERFX8 | U_RENDERFX16;
else if (to->renderfx & 0x0000ff00)
bits |= U_RENDERFX16;
else
bits |= U_RENDERFX8;
}
if (to->solid != from->solid)
bits |= U_SOLID;
// event is not delta compressed, just 0 compressed
if (to->event)
bits |= U_EVENT;
if (to->modelindex != from->modelindex)
bits |= U_MODEL;
if (to->modelindex2 != from->modelindex2)
bits |= U_MODEL2;
if (to->modelindex3 != from->modelindex3)
bits |= U_MODEL3;
if (to->modelindex4 != from->modelindex4)
bits |= U_MODEL4;
if (to->sound != from->sound)
bits |= U_SOUND;
if (to->renderfx & RF_FRAMELERP) {
bits |= U_OLDORIGIN;
} else if (to->renderfx & RF_BEAM) {
if (flags & MSG_ES_BEAMORIGIN) {
if (to->old_origin[0] != from->old_origin[0] ||
to->old_origin[1] != from->old_origin[1] ||
to->old_origin[2] != from->old_origin[2])
bits |= U_OLDORIGIN;
} else {
bits |= U_OLDORIGIN;
}
}
//
// write the message
//
if (!bits && !(flags & MSG_ES_FORCE))
return; // nothing to send!
if (flags & MSG_ES_REMOVE)
bits |= U_REMOVE; // used for MVD stream only
//----------
if (to->number & 0xff00)
bits |= U_NUMBER16; // number8 is implicit otherwise
if (bits & 0xff000000)
bits |= U_MOREBITS3 | U_MOREBITS2 | U_MOREBITS1;
else if (bits & 0x00ff0000)
bits |= U_MOREBITS2 | U_MOREBITS1;
else if (bits & 0x0000ff00)
bits |= U_MOREBITS1;
MSG_WriteByte(bits & 255);
if (bits & 0xff000000) {
MSG_WriteByte((bits >> 8) & 255);
MSG_WriteByte((bits >> 16) & 255);
MSG_WriteByte((bits >> 24) & 255);
} else if (bits & 0x00ff0000) {
MSG_WriteByte((bits >> 8) & 255);
MSG_WriteByte((bits >> 16) & 255);
} else if (bits & 0x0000ff00) {
MSG_WriteByte((bits >> 8) & 255);
}
//----------
if (bits & U_NUMBER16)
MSG_WriteShort(to->number);
else
MSG_WriteByte(to->number);
if (bits & U_MODEL)
MSG_WriteByte(to->modelindex);
if (bits & U_MODEL2)
MSG_WriteByte(to->modelindex2);
if (bits & U_MODEL3)
MSG_WriteByte(to->modelindex3);
if (bits & U_MODEL4)
MSG_WriteByte(to->modelindex4);
if (bits & U_FRAME8)
MSG_WriteByte(to->frame);
else if (bits & U_FRAME16)
MSG_WriteShort(to->frame);
if ((bits & (U_SKIN8 | U_SKIN16)) == (U_SKIN8 | U_SKIN16)) //used for laser colors
MSG_WriteLong(to->skinnum);
else if (bits & U_SKIN8)
MSG_WriteByte(to->skinnum);
else if (bits & U_SKIN16)
MSG_WriteShort(to->skinnum);
if ((bits & (U_EFFECTS8 | U_EFFECTS16)) == (U_EFFECTS8 | U_EFFECTS16))
MSG_WriteLong(to->effects);
else if (bits & U_EFFECTS8)
MSG_WriteByte(to->effects);
else if (bits & U_EFFECTS16)
MSG_WriteShort(to->effects);
if ((bits & (U_RENDERFX8 | U_RENDERFX16)) == (U_RENDERFX8 | U_RENDERFX16))
MSG_WriteLong(to->renderfx);
else if (bits & U_RENDERFX8)
MSG_WriteByte(to->renderfx);
else if (bits & U_RENDERFX16)
MSG_WriteShort(to->renderfx);
if (bits & U_ORIGIN1)
MSG_WriteShort(to->origin[0]);
if (bits & U_ORIGIN2)
MSG_WriteShort(to->origin[1]);
if (bits & U_ORIGIN3)
MSG_WriteShort(to->origin[2]);
if ((flags & MSG_ES_SHORTANGLES) && (bits & U_ANGLE16)) {
if (bits & U_ANGLE1)
MSG_WriteShort(to->angles[0]);
if (bits & U_ANGLE2)
MSG_WriteShort(to->angles[1]);
if (bits & U_ANGLE3)
MSG_WriteShort(to->angles[2]);
} else {
if (bits & U_ANGLE1)
MSG_WriteByte(to->angles[0] >> 8);
if (bits & U_ANGLE2)
MSG_WriteByte(to->angles[1] >> 8);
if (bits & U_ANGLE3)
MSG_WriteByte(to->angles[2] >> 8);
}
if (bits & U_OLDORIGIN) {
MSG_WriteShort(to->old_origin[0]);
MSG_WriteShort(to->old_origin[1]);
MSG_WriteShort(to->old_origin[2]);
}
if (bits & U_SOUND)
MSG_WriteByte(to->sound);
if (bits & U_EVENT)
MSG_WriteByte(to->event);
if (bits & U_SOLID) {
if (flags & MSG_ES_LONGSOLID)
MSG_WriteLong(to->solid);
else
MSG_WriteShort(to->solid);
}
}
void MSG_PackPlayer(player_packed_t *out, const player_state_t *in)
{
int i;
out->pmove = in->pmove;
out->viewangles[0] = ANGLE2SHORT(in->viewangles[0]);
out->viewangles[1] = ANGLE2SHORT(in->viewangles[1]);
out->viewangles[2] = ANGLE2SHORT(in->viewangles[2]);
out->viewoffset[0] = in->viewoffset[0] * 4;
out->viewoffset[1] = in->viewoffset[1] * 4;
out->viewoffset[2] = in->viewoffset[2] * 4;
out->kick_angles[0] = in->kick_angles[0] * 4;
out->kick_angles[1] = in->kick_angles[1] * 4;
out->kick_angles[2] = in->kick_angles[2] * 4;
out->gunoffset[0] = in->gunoffset[0] * 4;
out->gunoffset[1] = in->gunoffset[1] * 4;
out->gunoffset[2] = in->gunoffset[2] * 4;
out->gunangles[0] = in->gunangles[0] * 4;
out->gunangles[1] = in->gunangles[1] * 4;
out->gunangles[2] = in->gunangles[2] * 4;
out->gunindex = in->gunindex;
out->gunframe = in->gunframe;
out->blend[0] = in->blend[0] * 255;
out->blend[1] = in->blend[1] * 255;
out->blend[2] = in->blend[2] * 255;
out->blend[3] = in->blend[3] * 255;
out->fov = in->fov;
out->rdflags = in->rdflags;
for (i = 0; i < MAX_STATS; i++)
out->stats[i] = in->stats[i];
}
void MSG_WriteDeltaPlayerstate_Default(const player_packed_t *from, const player_packed_t *to)
{
int i;
int pflags;
int statbits;
if (!to)
Com_Error(ERR_DROP, "%s: NULL", __func__);
if (!from)
from = &nullPlayerState;
//
// determine what needs to be sent
//
pflags = 0;
if (to->pmove.pm_type != from->pmove.pm_type)
pflags |= PS_M_TYPE;
if (to->pmove.origin[0] != from->pmove.origin[0] ||
to->pmove.origin[1] != from->pmove.origin[1] ||
to->pmove.origin[2] != from->pmove.origin[2])
pflags |= PS_M_ORIGIN;
if (to->pmove.velocity[0] != from->pmove.velocity[0] ||
to->pmove.velocity[1] != from->pmove.velocity[1] ||
to->pmove.velocity[2] != from->pmove.velocity[2])
pflags |= PS_M_VELOCITY;
if (to->pmove.pm_time != from->pmove.pm_time)
pflags |= PS_M_TIME;
if (to->pmove.pm_flags != from->pmove.pm_flags)
pflags |= PS_M_FLAGS;
if (to->pmove.gravity != from->pmove.gravity)
pflags |= PS_M_GRAVITY;
if (to->pmove.delta_angles[0] != from->pmove.delta_angles[0] ||
to->pmove.delta_angles[1] != from->pmove.delta_angles[1] ||
to->pmove.delta_angles[2] != from->pmove.delta_angles[2])
pflags |= PS_M_DELTA_ANGLES;
if (to->viewoffset[0] != from->viewoffset[0] ||
to->viewoffset[1] != from->viewoffset[1] ||
to->viewoffset[2] != from->viewoffset[2])
pflags |= PS_VIEWOFFSET;
if (to->viewangles[0] != from->viewangles[0] ||
to->viewangles[1] != from->viewangles[1] ||
to->viewangles[2] != from->viewangles[2])
pflags |= PS_VIEWANGLES;
if (to->kick_angles[0] != from->kick_angles[0] ||
to->kick_angles[1] != from->kick_angles[1] ||
to->kick_angles[2] != from->kick_angles[2])
pflags |= PS_KICKANGLES;
if (to->blend[0] != from->blend[0] ||
to->blend[1] != from->blend[1] ||
to->blend[2] != from->blend[2] ||
to->blend[3] != from->blend[3])
pflags |= PS_BLEND;
if (to->fov != from->fov)
pflags |= PS_FOV;
if (to->rdflags != from->rdflags)
pflags |= PS_RDFLAGS;
if (to->gunframe != from->gunframe ||
to->gunoffset[0] != from->gunoffset[0] ||
to->gunoffset[1] != from->gunoffset[1] ||
to->gunoffset[2] != from->gunoffset[2] ||
to->gunangles[0] != from->gunangles[0] ||
to->gunangles[1] != from->gunangles[1] ||
to->gunangles[2] != from->gunangles[2])
pflags |= PS_WEAPONFRAME;
if (to->gunindex != from->gunindex)
pflags |= PS_WEAPONINDEX;
//
// write it
//
MSG_WriteShort(pflags);
//
// write the pmove_state_t
//
if (pflags & PS_M_TYPE)
MSG_WriteByte(to->pmove.pm_type);
if (pflags & PS_M_ORIGIN) {
MSG_WriteShort(to->pmove.origin[0]);
MSG_WriteShort(to->pmove.origin[1]);
MSG_WriteShort(to->pmove.origin[2]);
}
if (pflags & PS_M_VELOCITY) {
MSG_WriteShort(to->pmove.velocity[0]);
MSG_WriteShort(to->pmove.velocity[1]);
MSG_WriteShort(to->pmove.velocity[2]);
}
if (pflags & PS_M_TIME)
MSG_WriteByte(to->pmove.pm_time);
if (pflags & PS_M_FLAGS)
MSG_WriteByte(to->pmove.pm_flags);
if (pflags & PS_M_GRAVITY)
MSG_WriteShort(to->pmove.gravity);
if (pflags & PS_M_DELTA_ANGLES) {
MSG_WriteShort(to->pmove.delta_angles[0]);
MSG_WriteShort(to->pmove.delta_angles[1]);
MSG_WriteShort(to->pmove.delta_angles[2]);
}
//
// write the rest of the player_state_t
//
if (pflags & PS_VIEWOFFSET) {
MSG_WriteChar(to->viewoffset[0]);
MSG_WriteChar(to->viewoffset[1]);
MSG_WriteChar(to->viewoffset[2]);
}
if (pflags & PS_VIEWANGLES) {
MSG_WriteShort(to->viewangles[0]);
MSG_WriteShort(to->viewangles[1]);
MSG_WriteShort(to->viewangles[2]);
}
if (pflags & PS_KICKANGLES) {
MSG_WriteChar(to->kick_angles[0]);
MSG_WriteChar(to->kick_angles[1]);
MSG_WriteChar(to->kick_angles[2]);
}
if (pflags & PS_WEAPONINDEX)
MSG_WriteByte(to->gunindex);
if (pflags & PS_WEAPONFRAME) {
MSG_WriteByte(to->gunframe);
MSG_WriteChar(to->gunoffset[0]);
MSG_WriteChar(to->gunoffset[1]);
MSG_WriteChar(to->gunoffset[2]);
MSG_WriteChar(to->gunangles[0]);
MSG_WriteChar(to->gunangles[1]);
MSG_WriteChar(to->gunangles[2]);
}
if (pflags & PS_BLEND) {
MSG_WriteByte(to->blend[0]);
MSG_WriteByte(to->blend[1]);
MSG_WriteByte(to->blend[2]);
MSG_WriteByte(to->blend[3]);
}
if (pflags & PS_FOV)
MSG_WriteByte(to->fov);
if (pflags & PS_RDFLAGS)
MSG_WriteByte(to->rdflags);
// send stats
statbits = 0;
for (i = 0; i < MAX_STATS; i++)
if (to->stats[i] != from->stats[i])
statbits |= 1 << i;
MSG_WriteLong(statbits);
for (i = 0; i < MAX_STATS; i++)
if (statbits & (1 << i))
MSG_WriteShort(to->stats[i]);
}
int MSG_WriteDeltaPlayerstate_Enhanced(const player_packed_t *from,
player_packed_t *to,
msgPsFlags_t flags)
{
int i;
int pflags, eflags;
int statbits;
if (!to)
Com_Error(ERR_DROP, "%s: NULL", __func__);
if (!from)
from = &nullPlayerState;
//
// determine what needs to be sent
//
pflags = 0;
eflags = 0;
if (to->pmove.pm_type != from->pmove.pm_type)
pflags |= PS_M_TYPE;
if (to->pmove.origin[0] != from->pmove.origin[0] ||
to->pmove.origin[1] != from->pmove.origin[1])
pflags |= PS_M_ORIGIN;
if (to->pmove.origin[2] != from->pmove.origin[2])
eflags |= EPS_M_ORIGIN2;
if (!(flags & MSG_PS_IGNORE_PREDICTION)) {
if (to->pmove.velocity[0] != from->pmove.velocity[0] ||
to->pmove.velocity[1] != from->pmove.velocity[1])
pflags |= PS_M_VELOCITY;
if (to->pmove.velocity[2] != from->pmove.velocity[2])
eflags |= EPS_M_VELOCITY2;
if (to->pmove.pm_time != from->pmove.pm_time)
pflags |= PS_M_TIME;
if (to->pmove.pm_flags != from->pmove.pm_flags)
pflags |= PS_M_FLAGS;
if (to->pmove.gravity != from->pmove.gravity)
pflags |= PS_M_GRAVITY;
} else {
// save previous state
VectorCopy(from->pmove.velocity, to->pmove.velocity);
to->pmove.pm_time = from->pmove.pm_time;
to->pmove.pm_flags = from->pmove.pm_flags;
to->pmove.gravity = from->pmove.gravity;
}
if (!(flags & MSG_PS_IGNORE_DELTAANGLES)) {
if (to->pmove.delta_angles[0] != from->pmove.delta_angles[0] ||
to->pmove.delta_angles[1] != from->pmove.delta_angles[1] ||
to->pmove.delta_angles[2] != from->pmove.delta_angles[2])
pflags |= PS_M_DELTA_ANGLES;
} else {
// save previous state
VectorCopy(from->pmove.delta_angles, to->pmove.delta_angles);
}
if (from->viewoffset[0] != to->viewoffset[0] ||
from->viewoffset[1] != to->viewoffset[1] ||
from->viewoffset[2] != to->viewoffset[2])
pflags |= PS_VIEWOFFSET;
if (!(flags & MSG_PS_IGNORE_VIEWANGLES)) {
if (from->viewangles[0] != to->viewangles[0] ||
from->viewangles[1] != to->viewangles[1])
pflags |= PS_VIEWANGLES;
if (from->viewangles[2] != to->viewangles[2])
eflags |= EPS_VIEWANGLE2;
} else {
// save previous state
to->viewangles[0] = from->viewangles[0];
to->viewangles[1] = from->viewangles[1];
to->viewangles[2] = from->viewangles[2];
}
if (from->kick_angles[0] != to->kick_angles[0] ||
from->kick_angles[1] != to->kick_angles[1] ||
from->kick_angles[2] != to->kick_angles[2])
pflags |= PS_KICKANGLES;
if (!(flags & MSG_PS_IGNORE_BLEND)) {
if (from->blend[0] != to->blend[0] ||
from->blend[1] != to->blend[1] ||
from->blend[2] != to->blend[2] ||
from->blend[3] != to->blend[3])
pflags |= PS_BLEND;
} else {
// save previous state
to->blend[0] = from->blend[0];
to->blend[1] = from->blend[1];
to->blend[2] = from->blend[2];
to->blend[3] = from->blend[3];
}
if (from->fov != to->fov)
pflags |= PS_FOV;
if (to->rdflags != from->rdflags)
pflags |= PS_RDFLAGS;
if (!(flags & MSG_PS_IGNORE_GUNINDEX)) {
if (to->gunindex != from->gunindex)
pflags |= PS_WEAPONINDEX;
} else {
// save previous state
to->gunindex = from->gunindex;
}
if (!(flags & MSG_PS_IGNORE_GUNFRAMES)) {
if (to->gunframe != from->gunframe)
pflags |= PS_WEAPONFRAME;
if (from->gunoffset[0] != to->gunoffset[0] ||
from->gunoffset[1] != to->gunoffset[1] ||
from->gunoffset[2] != to->gunoffset[2])
eflags |= EPS_GUNOFFSET;
if (from->gunangles[0] != to->gunangles[0] ||
from->gunangles[1] != to->gunangles[1] ||
from->gunangles[2] != to->gunangles[2])
eflags |= EPS_GUNANGLES;
} else {
// save previous state
to->gunframe = from->gunframe;
to->gunoffset[0] = from->gunoffset[0];
to->gunoffset[1] = from->gunoffset[1];
to->gunoffset[2] = from->gunoffset[2];
to->gunangles[0] = from->gunangles[0];
to->gunangles[1] = from->gunangles[1];
to->gunangles[2] = from->gunangles[2];
}
statbits = 0;
for (i = 0; i < MAX_STATS; i++)
if (to->stats[i] != from->stats[i])
statbits |= 1 << i;
if (statbits)
eflags |= EPS_STATS;
//
// write it
//
MSG_WriteShort(pflags);
//
// write the pmove_state_t
//
if (pflags & PS_M_TYPE)
MSG_WriteByte(to->pmove.pm_type);
if (pflags & PS_M_ORIGIN) {
MSG_WriteShort(to->pmove.origin[0]);
MSG_WriteShort(to->pmove.origin[1]);
}
if (eflags & EPS_M_ORIGIN2)
MSG_WriteShort(to->pmove.origin[2]);
if (pflags & PS_M_VELOCITY) {
MSG_WriteShort(to->pmove.velocity[0]);
MSG_WriteShort(to->pmove.velocity[1]);
}
if (eflags & EPS_M_VELOCITY2)
MSG_WriteShort(to->pmove.velocity[2]);
if (pflags & PS_M_TIME)
MSG_WriteByte(to->pmove.pm_time);
if (pflags & PS_M_FLAGS)
MSG_WriteByte(to->pmove.pm_flags);
if (pflags & PS_M_GRAVITY)
MSG_WriteShort(to->pmove.gravity);
if (pflags & PS_M_DELTA_ANGLES) {
MSG_WriteShort(to->pmove.delta_angles[0]);
MSG_WriteShort(to->pmove.delta_angles[1]);
MSG_WriteShort(to->pmove.delta_angles[2]);
}
//
// write the rest of the player_state_t
//
if (pflags & PS_VIEWOFFSET) {
MSG_WriteChar(to->viewoffset[0]);
MSG_WriteChar(to->viewoffset[1]);
MSG_WriteChar(to->viewoffset[2]);
}
if (pflags & PS_VIEWANGLES) {
MSG_WriteShort(to->viewangles[0]);
MSG_WriteShort(to->viewangles[1]);
}
if (eflags & EPS_VIEWANGLE2)
MSG_WriteShort(to->viewangles[2]);
if (pflags & PS_KICKANGLES) {
MSG_WriteChar(to->kick_angles[0]);
MSG_WriteChar(to->kick_angles[1]);
MSG_WriteChar(to->kick_angles[2]);
}
if (pflags & PS_WEAPONINDEX)
MSG_WriteByte(to->gunindex);
if (pflags & PS_WEAPONFRAME)
MSG_WriteByte(to->gunframe);
if (eflags & EPS_GUNOFFSET) {
MSG_WriteChar(to->gunoffset[0]);
MSG_WriteChar(to->gunoffset[1]);
MSG_WriteChar(to->gunoffset[2]);
}
if (eflags & EPS_GUNANGLES) {
MSG_WriteChar(to->gunangles[0]);
MSG_WriteChar(to->gunangles[1]);
MSG_WriteChar(to->gunangles[2]);
}
if (pflags & PS_BLEND) {
MSG_WriteByte(to->blend[0]);
MSG_WriteByte(to->blend[1]);
MSG_WriteByte(to->blend[2]);
MSG_WriteByte(to->blend[3]);
}
if (pflags & PS_FOV)
MSG_WriteByte(to->fov);
if (pflags & PS_RDFLAGS)
MSG_WriteByte(to->rdflags);
// send stats
if (eflags & EPS_STATS) {
MSG_WriteLong(statbits);
for (i = 0; i < MAX_STATS; i++)
if (statbits & (1 << i))
MSG_WriteShort(to->stats[i]);
}
return eflags;
}
#if USE_MVD_SERVER || USE_MVD_CLIENT
/*
==================
MSG_WriteDeltaPlayerstate_Packet
Throws away most of the pmove_state_t fields as they are used only
for client prediction, and are not needed in MVDs.
==================
*/
void MSG_WriteDeltaPlayerstate_Packet(const player_packed_t *from,
const player_packed_t *to,
int number,
msgPsFlags_t flags)
{
int i;
int pflags;
int statbits;
if (number < 0 || number >= MAX_CLIENTS)
Com_Error(ERR_DROP, "%s: bad number: %d", __func__, number);
if (!to) {
MSG_WriteByte(number);
MSG_WriteShort(PPS_REMOVE);
return;
}
if (!from)
from = &nullPlayerState;
//
// determine what needs to be sent
//
pflags = 0;
if (to->pmove.pm_type != from->pmove.pm_type)
pflags |= PPS_M_TYPE;
if (to->pmove.origin[0] != from->pmove.origin[0] ||
to->pmove.origin[1] != from->pmove.origin[1])
pflags |= PPS_M_ORIGIN;
if (to->pmove.origin[2] != from->pmove.origin[2])
pflags |= PPS_M_ORIGIN2;
if (from->viewoffset[0] != to->viewoffset[0] ||
from->viewoffset[1] != to->viewoffset[1] ||
from->viewoffset[2] != to->viewoffset[2])
pflags |= PPS_VIEWOFFSET;
if (from->viewangles[0] != to->viewangles[0] ||
from->viewangles[1] != to->viewangles[1])
pflags |= PPS_VIEWANGLES;
if (from->viewangles[2] != to->viewangles[2])
pflags |= PPS_VIEWANGLE2;
if (from->kick_angles[0] != to->kick_angles[0] ||
from->kick_angles[1] != to->kick_angles[1] ||
from->kick_angles[2] != to->kick_angles[2])
pflags |= PPS_KICKANGLES;
if (!(flags & MSG_PS_IGNORE_BLEND)) {
if (from->blend[0] != to->blend[0] ||
from->blend[1] != to->blend[1] ||
from->blend[2] != to->blend[2] ||
from->blend[3] != to->blend[3])
pflags |= PPS_BLEND;
}
if (from->fov != to->fov)
pflags |= PPS_FOV;
if (to->rdflags != from->rdflags)
pflags |= PPS_RDFLAGS;
if (!(flags & MSG_PS_IGNORE_GUNINDEX)) {
if (to->gunindex != from->gunindex)
pflags |= PPS_WEAPONINDEX;
}
if (!(flags & MSG_PS_IGNORE_GUNFRAMES)) {
if (to->gunframe != from->gunframe)
pflags |= PPS_WEAPONFRAME;
if (from->gunoffset[0] != to->gunoffset[0] ||
from->gunoffset[1] != to->gunoffset[1] ||
from->gunoffset[2] != to->gunoffset[2])
pflags |= PPS_GUNOFFSET;
if (from->gunangles[0] != to->gunangles[0] ||
from->gunangles[1] != to->gunangles[1] ||
from->gunangles[2] != to->gunangles[2])
pflags |= PPS_GUNANGLES;
}
statbits = 0;
for (i = 0; i < MAX_STATS; i++)
if (to->stats[i] != from->stats[i])
statbits |= 1 << i;
if (statbits)
pflags |= PPS_STATS;
if (!pflags && !(flags & MSG_PS_FORCE))
return;
if (flags & MSG_PS_REMOVE)
pflags |= PPS_REMOVE; // used for MVD stream only
//
// write it
//
MSG_WriteByte(number);
MSG_WriteShort(pflags);
//
// write some part of the pmove_state_t
//
if (pflags & PPS_M_TYPE)
MSG_WriteByte(to->pmove.pm_type);
if (pflags & PPS_M_ORIGIN) {
MSG_WriteShort(to->pmove.origin[0]);
MSG_WriteShort(to->pmove.origin[1]);
}
if (pflags & PPS_M_ORIGIN2)
MSG_WriteShort(to->pmove.origin[2]);
//
// write the rest of the player_state_t
//
if (pflags & PPS_VIEWOFFSET) {
MSG_WriteChar(to->viewoffset[0]);
MSG_WriteChar(to->viewoffset[1]);
MSG_WriteChar(to->viewoffset[2]);
}
if (pflags & PPS_VIEWANGLES) {
MSG_WriteShort(to->viewangles[0]);
MSG_WriteShort(to->viewangles[1]);
}
if (pflags & PPS_VIEWANGLE2)
MSG_WriteShort(to->viewangles[2]);
if (pflags & PPS_KICKANGLES) {
MSG_WriteChar(to->kick_angles[0]);
MSG_WriteChar(to->kick_angles[1]);
MSG_WriteChar(to->kick_angles[2]);
}
if (pflags & PPS_WEAPONINDEX)
MSG_WriteByte(to->gunindex);
if (pflags & PPS_WEAPONFRAME)
MSG_WriteByte(to->gunframe);
if (pflags & PPS_GUNOFFSET) {
MSG_WriteChar(to->gunoffset[0]);
MSG_WriteChar(to->gunoffset[1]);
MSG_WriteChar(to->gunoffset[2]);
}
if (pflags & PPS_GUNANGLES) {
MSG_WriteChar(to->gunangles[0]);
MSG_WriteChar(to->gunangles[1]);
MSG_WriteChar(to->gunangles[2]);
}
if (pflags & PPS_BLEND) {
MSG_WriteByte(to->blend[0]);
MSG_WriteByte(to->blend[1]);
MSG_WriteByte(to->blend[2]);
MSG_WriteByte(to->blend[3]);
}
if (pflags & PPS_FOV)
MSG_WriteByte(to->fov);
if (pflags & PPS_RDFLAGS)
MSG_WriteByte(to->rdflags);
// send stats
if (pflags & PPS_STATS) {
MSG_WriteLong(statbits);
for (i = 0; i < MAX_STATS; i++)
if (statbits & (1 << i))
MSG_WriteShort(to->stats[i]);
}
}
#endif // USE_MVD_SERVER || USE_MVD_CLIENT
/*
==============================================================================
READING
==============================================================================
*/
void MSG_BeginReading(void)
{
msg_read.readcount = 0;
msg_read.bitpos = 0;
}
byte *MSG_ReadData(size_t len)
{
byte *buf = msg_read.data + msg_read.readcount;
msg_read.readcount += len;
msg_read.bitpos = msg_read.readcount << 3;
if (msg_read.readcount > msg_read.cursize) {
if (!msg_read.allowunderflow) {
Com_Error(ERR_DROP, "%s: read past end of message", __func__);
}
return NULL;
}
return buf;
}
// returns -1 if no more characters are available
int MSG_ReadChar(void)
{
byte *buf = MSG_ReadData(1);
int c;
if (!buf) {
c = -1;
} else {
c = (signed char)buf[0];
}
return c;
}
int MSG_ReadByte(void)
{
byte *buf = MSG_ReadData(1);
int c;
if (!buf) {
c = -1;
} else {
c = (unsigned char)buf[0];
}
return c;
}
int MSG_ReadShort(void)
{
byte *buf = MSG_ReadData(2);
int c;
if (!buf) {
c = -1;
} else {
c = (signed short)LittleShortMem(buf);
}
return c;
}
int MSG_ReadWord(void)
{
byte *buf = MSG_ReadData(2);
int c;
if (!buf) {
c = -1;
} else {
c = (unsigned short)LittleShortMem(buf);
}
return c;
}
int MSG_ReadLong(void)
{
byte *buf = MSG_ReadData(4);
int c;
if (!buf) {
c = -1;
} else {
c = LittleLongMem(buf);
}
return c;
}
size_t MSG_ReadString(char *dest, size_t size)
{
int c;
size_t len = 0;
while (1) {
c = MSG_ReadByte();
if (c == -1 || c == 0) {
break;
}
if (len + 1 < size) {
*dest++ = c;
}
len++;
}
if (size) {
*dest = 0;
}
return len;
}
size_t MSG_ReadStringLine(char *dest, size_t size)
{
int c;
size_t len = 0;
while (1) {
c = MSG_ReadByte();
if (c == -1 || c == 0 || c == '\n') {
break;
}
if (len + 1 < size) {
*dest++ = c;
}
len++;
}
if (size) {
*dest = 0;
}
return len;
}
static inline float MSG_ReadCoord(void)
{
return SHORT2COORD(MSG_ReadShort());
}
#if !USE_CLIENT
static inline
#endif
void MSG_ReadPos(vec3_t pos)
{
pos[0] = MSG_ReadCoord();
pos[1] = MSG_ReadCoord();
pos[2] = MSG_ReadCoord();
}
static inline float MSG_ReadAngle(void)
{
return BYTE2ANGLE(MSG_ReadChar());
}
static inline float MSG_ReadAngle16(void)
{
return SHORT2ANGLE(MSG_ReadShort());
}
#if USE_CLIENT
void MSG_ReadDir(vec3_t dir)
{
int b;
b = MSG_ReadByte();
if (b < 0 || b >= NUMVERTEXNORMALS)
Com_Error(ERR_DROP, "MSG_ReadDir: out of range");
VectorCopy(bytedirs[b], dir);
}
#endif
void MSG_ReadDeltaUsercmd(const usercmd_t *from, usercmd_t *to)
{
int bits;
if (from) {
memcpy(to, from, sizeof(*to));
} else {
memset(to, 0, sizeof(*to));
}
bits = MSG_ReadByte();
// read current angles
if (bits & CM_ANGLE1)
to->angles[0] = MSG_ReadShort();
if (bits & CM_ANGLE2)
to->angles[1] = MSG_ReadShort();
if (bits & CM_ANGLE3)
to->angles[2] = MSG_ReadShort();
// read movement
if (bits & CM_FORWARD)
to->forwardmove = MSG_ReadShort();
if (bits & CM_SIDE)
to->sidemove = MSG_ReadShort();
if (bits & CM_UP)
to->upmove = MSG_ReadShort();
// read buttons
if (bits & CM_BUTTONS)
to->buttons = MSG_ReadByte();
if (bits & CM_IMPULSE)
to->impulse = MSG_ReadByte();
// read time to run command
to->msec = MSG_ReadByte();
// read the light level
to->lightlevel = MSG_ReadByte();
}
void MSG_ReadDeltaUsercmd_Hacked(const usercmd_t *from, usercmd_t *to)
{
int bits, buttons = 0;
if (from) {
memcpy(to, from, sizeof(*to));
} else {
memset(to, 0, sizeof(*to));
}
bits = MSG_ReadByte();
// read buttons
if (bits & CM_BUTTONS) {
buttons = MSG_ReadByte();
to->buttons = buttons & BUTTON_MASK;
}
// read current angles
if (bits & CM_ANGLE1) {
if (buttons & BUTTON_ANGLE1) {
to->angles[0] = MSG_ReadChar() * 64;
} else {
to->angles[0] = MSG_ReadShort();
}
}
if (bits & CM_ANGLE2) {
if (buttons & BUTTON_ANGLE2) {
to->angles[1] = MSG_ReadChar() * 256;
} else {
to->angles[1] = MSG_ReadShort();
}
}
if (bits & CM_ANGLE3)
to->angles[2] = MSG_ReadShort();
// read movement
if (bits & CM_FORWARD) {
if (buttons & BUTTON_FORWARD) {
to->forwardmove = MSG_ReadChar() * 5;
} else {
to->forwardmove = MSG_ReadShort();
}
}
if (bits & CM_SIDE) {
if (buttons & BUTTON_SIDE) {
to->sidemove = MSG_ReadChar() * 5;
} else {
to->sidemove = MSG_ReadShort();
}
}
if (bits & CM_UP) {
if (buttons & BUTTON_UP) {
to->upmove = MSG_ReadChar() * 5;
} else {
to->upmove = MSG_ReadShort();
}
}
if (bits & CM_IMPULSE)
to->impulse = MSG_ReadByte();
// read time to run command
to->msec = MSG_ReadByte();
// read the light level
to->lightlevel = MSG_ReadByte();
}
int MSG_ReadBits(int bits)
{
int i, get;
size_t bitpos;
qboolean sgn;
int value;
if (bits == 0 || bits < -31 || bits > 32) {
Com_Error(ERR_FATAL, "MSG_ReadBits: bad bits: %d", bits);
}
bitpos = msg_read.bitpos;
if ((bitpos & 7) == 0) {
// optimized case
switch (bits) {
case -8:
value = MSG_ReadChar();
return value;
case 8:
value = MSG_ReadByte();
return value;
case -16:
value = MSG_ReadShort();
return value;
case 32:
value = MSG_ReadLong();
return value;
default:
break;
}
}
sgn = qfalse;
if (bits < 0) {
bits = -bits;
sgn = qtrue;
}
value = 0;
for (i = 0; i < bits; i++, bitpos++) {
get = (msg_read.data[bitpos >> 3] >> (bitpos & 7)) & 1;
value |= get << i;
}
msg_read.bitpos = bitpos;
msg_read.readcount = (bitpos + 7) >> 3;
if (sgn) {
if (value & (1 << (bits - 1))) {
value |= -1 ^((1 << bits) - 1);
}
}
return value;
}
void MSG_ReadDeltaUsercmd_Enhanced(const usercmd_t *from,
usercmd_t *to,
int version)
{
int bits, count;
if (from) {
memcpy(to, from, sizeof(*to));
} else {
memset(to, 0, sizeof(*to));
}
if (!MSG_ReadBits(1)) {
return;
}
bits = MSG_ReadBits(8);
// read current angles
if (bits & CM_ANGLE1) {
if (MSG_ReadBits(1)) {
to->angles[0] += MSG_ReadBits(-8);
} else {
to->angles[0] = MSG_ReadBits(-16);
}
}
if (bits & CM_ANGLE2) {
if (MSG_ReadBits(1)) {
to->angles[1] += MSG_ReadBits(-8);
} else {
to->angles[1] = MSG_ReadBits(-16);
}
}
if (bits & CM_ANGLE3) {
to->angles[2] = MSG_ReadBits(-16);
}
// read movement
if (version >= PROTOCOL_VERSION_Q2PRO_UCMD) {
count = -10;
} else {
count = -16;
}
if (bits & CM_FORWARD) {
to->forwardmove = MSG_ReadBits(count);
}
if (bits & CM_SIDE) {
to->sidemove = MSG_ReadBits(count);
}
if (bits & CM_UP) {
to->upmove = MSG_ReadBits(count);
}
// read buttons
if (bits & CM_BUTTONS) {
int buttons = MSG_ReadBits(3);
to->buttons = (buttons & 3) | ((buttons & 4) << 5);
}
// read time to run command
if (bits & CM_IMPULSE) {
to->msec = MSG_ReadBits(8);
}
}
#if USE_CLIENT || USE_MVD_CLIENT
/*
=================
MSG_ParseEntityBits
Returns the entity number and the header bits
=================
*/
int MSG_ParseEntityBits(int *bits)
{
int b, total;
int number;
total = MSG_ReadByte();
if (total & U_MOREBITS1) {
b = MSG_ReadByte();
total |= b << 8;
}
if (total & U_MOREBITS2) {
b = MSG_ReadByte();
total |= b << 16;
}
if (total & U_MOREBITS3) {
b = MSG_ReadByte();
total |= b << 24;
}
if (total & U_NUMBER16)
number = MSG_ReadShort();
else
number = MSG_ReadByte();
*bits = total;
return number;
}
/*
==================
MSG_ParseDeltaEntity
Can go from either a baseline or a previous packet_entity
==================
*/
void MSG_ParseDeltaEntity(const entity_state_t *from,
entity_state_t *to,
int number,
int bits,
msgEsFlags_t flags)
{
if (!to) {
Com_Error(ERR_DROP, "%s: NULL", __func__);
}
if (number < 1 || number >= MAX_EDICTS) {
Com_Error(ERR_DROP, "%s: bad entity number: %d", __func__, number);
}
// set everything to the state we are delta'ing from
if (!from) {
memset(to, 0, sizeof(*to));
} else if (to != from) {
memcpy(to, from, sizeof(*to));
}
to->number = number;
to->event = 0;
if (!bits) {
return;
}
if (bits & U_MODEL) {
to->modelindex = MSG_ReadByte();
}
if (bits & U_MODEL2) {
to->modelindex2 = MSG_ReadByte();
}
if (bits & U_MODEL3) {
to->modelindex3 = MSG_ReadByte();
}
if (bits & U_MODEL4) {
to->modelindex4 = MSG_ReadByte();
}
if (bits & U_FRAME8)
to->frame = MSG_ReadByte();
if (bits & U_FRAME16)
to->frame = MSG_ReadShort();
if ((bits & (U_SKIN8 | U_SKIN16)) == (U_SKIN8 | U_SKIN16)) //used for laser colors
to->skinnum = MSG_ReadLong();
else if (bits & U_SKIN8)
to->skinnum = MSG_ReadByte();
else if (bits & U_SKIN16)
to->skinnum = MSG_ReadWord();
if ((bits & (U_EFFECTS8 | U_EFFECTS16)) == (U_EFFECTS8 | U_EFFECTS16))
to->effects = MSG_ReadLong();
else if (bits & U_EFFECTS8)
to->effects = MSG_ReadByte();
else if (bits & U_EFFECTS16)
to->effects = MSG_ReadWord();
if ((bits & (U_RENDERFX8 | U_RENDERFX16)) == (U_RENDERFX8 | U_RENDERFX16))
to->renderfx = MSG_ReadLong();
else if (bits & U_RENDERFX8)
to->renderfx = MSG_ReadByte();
else if (bits & U_RENDERFX16)
to->renderfx = MSG_ReadWord();
if (bits & U_ORIGIN1) {
to->origin[0] = MSG_ReadCoord();
}
if (bits & U_ORIGIN2) {
to->origin[1] = MSG_ReadCoord();
}
if (bits & U_ORIGIN3) {
to->origin[2] = MSG_ReadCoord();
}
if ((flags & MSG_ES_SHORTANGLES) && (bits & U_ANGLE16)) {
if (bits & U_ANGLE1)
to->angles[0] = MSG_ReadAngle16();
if (bits & U_ANGLE2)
to->angles[1] = MSG_ReadAngle16();
if (bits & U_ANGLE3)
to->angles[2] = MSG_ReadAngle16();
} else {
if (bits & U_ANGLE1)
to->angles[0] = MSG_ReadAngle();
if (bits & U_ANGLE2)
to->angles[1] = MSG_ReadAngle();
if (bits & U_ANGLE3)
to->angles[2] = MSG_ReadAngle();
}
if (bits & U_OLDORIGIN) {
MSG_ReadPos(to->old_origin);
}
if (bits & U_SOUND) {
to->sound = MSG_ReadByte();
}
if (bits & U_EVENT) {
to->event = MSG_ReadByte();
}
if (bits & U_SOLID) {
if (flags & MSG_ES_LONGSOLID) {
to->solid = MSG_ReadLong();
} else {
to->solid = MSG_ReadWord();
}
}
}
#endif // USE_CLIENT || USE_MVD_CLIENT
#if USE_CLIENT
/*
===================
MSG_ParseDeltaPlayerstate_Default
===================
*/
void MSG_ParseDeltaPlayerstate_Default(const player_state_t *from,
player_state_t *to,
int flags)
{
int i;
int statbits;
if (!to) {
Com_Error(ERR_DROP, "%s: NULL", __func__);
}
// clear to old value before delta parsing
if (!from) {
memset(to, 0, sizeof(*to));
} else if (to != from) {
memcpy(to, from, sizeof(*to));
}
//
// parse the pmove_state_t
//
if (flags & PS_M_TYPE)
to->pmove.pm_type = MSG_ReadByte();
if (flags & PS_M_ORIGIN) {
to->pmove.origin[0] = MSG_ReadShort();
to->pmove.origin[1] = MSG_ReadShort();
to->pmove.origin[2] = MSG_ReadShort();
}
if (flags & PS_M_VELOCITY) {
to->pmove.velocity[0] = MSG_ReadShort();
to->pmove.velocity[1] = MSG_ReadShort();
to->pmove.velocity[2] = MSG_ReadShort();
}
if (flags & PS_M_TIME)
to->pmove.pm_time = MSG_ReadByte();
if (flags & PS_M_FLAGS)
to->pmove.pm_flags = MSG_ReadByte();
if (flags & PS_M_GRAVITY)
to->pmove.gravity = MSG_ReadShort();
if (flags & PS_M_DELTA_ANGLES) {
to->pmove.delta_angles[0] = MSG_ReadShort();
to->pmove.delta_angles[1] = MSG_ReadShort();
to->pmove.delta_angles[2] = MSG_ReadShort();
}
//
// parse the rest of the player_state_t
//
if (flags & PS_VIEWOFFSET) {
to->viewoffset[0] = MSG_ReadChar() * 0.25f;
to->viewoffset[1] = MSG_ReadChar() * 0.25f;
to->viewoffset[2] = MSG_ReadChar() * 0.25f;
}
if (flags & PS_VIEWANGLES) {
to->viewangles[0] = MSG_ReadAngle16();
to->viewangles[1] = MSG_ReadAngle16();
to->viewangles[2] = MSG_ReadAngle16();
}
if (flags & PS_KICKANGLES) {
to->kick_angles[0] = MSG_ReadChar() * 0.25f;
to->kick_angles[1] = MSG_ReadChar() * 0.25f;
to->kick_angles[2] = MSG_ReadChar() * 0.25f;
}
if (flags & PS_WEAPONINDEX) {
to->gunindex = MSG_ReadByte();
}
if (flags & PS_WEAPONFRAME) {
to->gunframe = MSG_ReadByte();
to->gunoffset[0] = MSG_ReadChar() * 0.25f;
to->gunoffset[1] = MSG_ReadChar() * 0.25f;
to->gunoffset[2] = MSG_ReadChar() * 0.25f;
to->gunangles[0] = MSG_ReadChar() * 0.25f;
to->gunangles[1] = MSG_ReadChar() * 0.25f;
to->gunangles[2] = MSG_ReadChar() * 0.25f;
}
if (flags & PS_BLEND) {
to->blend[0] = MSG_ReadByte() / 255.0f;
to->blend[1] = MSG_ReadByte() / 255.0f;
to->blend[2] = MSG_ReadByte() / 255.0f;
to->blend[3] = MSG_ReadByte() / 255.0f;
}
if (flags & PS_FOV)
to->fov = MSG_ReadByte();
if (flags & PS_RDFLAGS)
to->rdflags = MSG_ReadByte();
// parse stats
statbits = MSG_ReadLong();
for (i = 0; i < MAX_STATS; i++)
if (statbits & (1 << i))
to->stats[i] = MSG_ReadShort();
}
/*
===================
MSG_ParseDeltaPlayerstate_Default
===================
*/
void MSG_ParseDeltaPlayerstate_Enhanced(const player_state_t *from,
player_state_t *to,
int flags,
int extraflags)
{
int i;
int statbits;
if (!to) {
Com_Error(ERR_DROP, "%s: NULL", __func__);
}
// clear to old value before delta parsing
if (!from) {
memset(to, 0, sizeof(*to));
} else if (to != from) {
memcpy(to, from, sizeof(*to));
}
//
// parse the pmove_state_t
//
if (flags & PS_M_TYPE)
to->pmove.pm_type = MSG_ReadByte();
if (flags & PS_M_ORIGIN) {
to->pmove.origin[0] = MSG_ReadShort();
to->pmove.origin[1] = MSG_ReadShort();
}
if (extraflags & EPS_M_ORIGIN2) {
to->pmove.origin[2] = MSG_ReadShort();
}
if (flags & PS_M_VELOCITY) {
to->pmove.velocity[0] = MSG_ReadShort();
to->pmove.velocity[1] = MSG_ReadShort();
}
if (extraflags & EPS_M_VELOCITY2) {
to->pmove.velocity[2] = MSG_ReadShort();
}
if (flags & PS_M_TIME)
to->pmove.pm_time = MSG_ReadByte();
if (flags & PS_M_FLAGS)
to->pmove.pm_flags = MSG_ReadByte();
if (flags & PS_M_GRAVITY)
to->pmove.gravity = MSG_ReadShort();
if (flags & PS_M_DELTA_ANGLES) {
to->pmove.delta_angles[0] = MSG_ReadShort();
to->pmove.delta_angles[1] = MSG_ReadShort();
to->pmove.delta_angles[2] = MSG_ReadShort();
}
//
// parse the rest of the player_state_t
//
if (flags & PS_VIEWOFFSET) {
to->viewoffset[0] = MSG_ReadChar() * 0.25f;
to->viewoffset[1] = MSG_ReadChar() * 0.25f;
to->viewoffset[2] = MSG_ReadChar() * 0.25f;
}
if (flags & PS_VIEWANGLES) {
to->viewangles[0] = MSG_ReadAngle16();
to->viewangles[1] = MSG_ReadAngle16();
}
if (extraflags & EPS_VIEWANGLE2) {
to->viewangles[2] = MSG_ReadAngle16();
}
if (flags & PS_KICKANGLES) {
to->kick_angles[0] = MSG_ReadChar() * 0.25f;
to->kick_angles[1] = MSG_ReadChar() * 0.25f;
to->kick_angles[2] = MSG_ReadChar() * 0.25f;
}
if (flags & PS_WEAPONINDEX) {
to->gunindex = MSG_ReadByte();
}
if (flags & PS_WEAPONFRAME) {
to->gunframe = MSG_ReadByte();
}
if (extraflags & EPS_GUNOFFSET) {
to->gunoffset[0] = MSG_ReadChar() * 0.25f;
to->gunoffset[1] = MSG_ReadChar() * 0.25f;
to->gunoffset[2] = MSG_ReadChar() * 0.25f;
}
if (extraflags & EPS_GUNANGLES) {
to->gunangles[0] = MSG_ReadChar() * 0.25f;
to->gunangles[1] = MSG_ReadChar() * 0.25f;
to->gunangles[2] = MSG_ReadChar() * 0.25f;
}
if (flags & PS_BLEND) {
to->blend[0] = MSG_ReadByte() / 255.0f;
to->blend[1] = MSG_ReadByte() / 255.0f;
to->blend[2] = MSG_ReadByte() / 255.0f;
to->blend[3] = MSG_ReadByte() / 255.0f;
}
if (flags & PS_FOV)
to->fov = MSG_ReadByte();
if (flags & PS_RDFLAGS)
to->rdflags = MSG_ReadByte();
// parse stats
if (extraflags & EPS_STATS) {
statbits = MSG_ReadLong();
for (i = 0; i < MAX_STATS; i++) {
if (statbits & (1 << i)) {
to->stats[i] = MSG_ReadShort();
}
}
}
}
#endif // USE_CLIENT
#if USE_MVD_CLIENT
/*
===================
MSG_ParseDeltaPlayerstate_Packet
===================
*/
void MSG_ParseDeltaPlayerstate_Packet(const player_state_t *from,
player_state_t *to,
int flags)
{
int i;
int statbits;
if (!to) {
Com_Error(ERR_DROP, "%s: NULL", __func__);
}
// clear to old value before delta parsing
if (!from) {
memset(to, 0, sizeof(*to));
} else if (to != from) {
memcpy(to, from, sizeof(*to));
}
//
// parse the pmove_state_t
//
if (flags & PPS_M_TYPE)
to->pmove.pm_type = MSG_ReadByte();
if (flags & PPS_M_ORIGIN) {
to->pmove.origin[0] = MSG_ReadShort();
to->pmove.origin[1] = MSG_ReadShort();
}
if (flags & PPS_M_ORIGIN2) {
to->pmove.origin[2] = MSG_ReadShort();
}
//
// parse the rest of the player_state_t
//
if (flags & PPS_VIEWOFFSET) {
to->viewoffset[0] = MSG_ReadChar() * 0.25f;
to->viewoffset[1] = MSG_ReadChar() * 0.25f;
to->viewoffset[2] = MSG_ReadChar() * 0.25f;
}
if (flags & PPS_VIEWANGLES) {
to->viewangles[0] = MSG_ReadAngle16();
to->viewangles[1] = MSG_ReadAngle16();
}
if (flags & PPS_VIEWANGLE2) {
to->viewangles[2] = MSG_ReadAngle16();
}
if (flags & PPS_KICKANGLES) {
to->kick_angles[0] = MSG_ReadChar() * 0.25f;
to->kick_angles[1] = MSG_ReadChar() * 0.25f;
to->kick_angles[2] = MSG_ReadChar() * 0.25f;
}
if (flags & PPS_WEAPONINDEX) {
to->gunindex = MSG_ReadByte();
}
if (flags & PPS_WEAPONFRAME) {
to->gunframe = MSG_ReadByte();
}
if (flags & PPS_GUNOFFSET) {
to->gunoffset[0] = MSG_ReadChar() * 0.25f;
to->gunoffset[1] = MSG_ReadChar() * 0.25f;
to->gunoffset[2] = MSG_ReadChar() * 0.25f;
}
if (flags & PPS_GUNANGLES) {
to->gunangles[0] = MSG_ReadChar() * 0.25f;
to->gunangles[1] = MSG_ReadChar() * 0.25f;
to->gunangles[2] = MSG_ReadChar() * 0.25f;
}
if (flags & PPS_BLEND) {
to->blend[0] = MSG_ReadByte() / 255.0f;
to->blend[1] = MSG_ReadByte() / 255.0f;
to->blend[2] = MSG_ReadByte() / 255.0f;
to->blend[3] = MSG_ReadByte() / 255.0f;
}
if (flags & PPS_FOV)
to->fov = MSG_ReadByte();
if (flags & PPS_RDFLAGS)
to->rdflags = MSG_ReadByte();
// parse stats
if (flags & PPS_STATS) {
statbits = MSG_ReadLong();
for (i = 0; i < MAX_STATS; i++) {
if (statbits & (1 << i)) {
to->stats[i] = MSG_ReadShort();
}
}
}
}
#endif // USE_MVD_CLIENT
/*
==============================================================================
DEBUGGING STUFF
==============================================================================
*/
#ifdef _DEBUG
#define SHOWBITS(x) Com_LPrintf(PRINT_DEVELOPER, x " ")
#if USE_CLIENT
void MSG_ShowDeltaPlayerstateBits_Default(int flags)
{
#define S(b,s) if(flags&PS_##b) SHOWBITS(s)
S(M_TYPE, "pmove.pm_type");
S(M_ORIGIN, "pmove.origin");
S(M_VELOCITY, "pmove.velocity");
S(M_TIME, "pmove.pm_time");
S(M_FLAGS, "pmove.pm_flags");
S(M_GRAVITY, "pmove.gravity");
S(M_DELTA_ANGLES, "pmove.delta_angles");
S(VIEWOFFSET, "viewoffset");
S(VIEWANGLES, "viewangles");
S(KICKANGLES, "kick_angles");
S(WEAPONINDEX, "gunindex");
S(WEAPONFRAME, "gunframe");
S(BLEND, "blend");
S(FOV, "fov");
S(RDFLAGS, "rdflags");
#undef S
}
void MSG_ShowDeltaPlayerstateBits_Enhanced(int flags, int extraflags)
{
#define SP(b,s) if(flags&PS_##b) SHOWBITS(s)
#define SE(b,s) if(extraflags&EPS_##b) SHOWBITS(s)
SP(M_TYPE, "pmove.pm_type");
SP(M_ORIGIN, "pmove.origin[0,1]");
SE(M_ORIGIN2, "pmove.origin[2]");
SP(M_VELOCITY, "pmove.velocity[0,1]");
SE(M_VELOCITY2, "pmove.velocity[2]");
SP(M_TIME, "pmove.pm_time");
SP(M_FLAGS, "pmove.pm_flags");
SP(M_GRAVITY, "pmove.gravity");
SP(M_DELTA_ANGLES, "pmove.delta_angles");
SP(VIEWOFFSET, "viewoffset");
SP(VIEWANGLES, "viewangles[0,1]");
SE(VIEWANGLE2, "viewangles[2]");
SP(KICKANGLES, "kick_angles");
SP(WEAPONINDEX, "gunindex");
SP(WEAPONFRAME, "gunframe");
SE(GUNOFFSET, "gunoffset");
SE(GUNANGLES, "gunangles");
SP(BLEND, "blend");
SP(FOV, "fov");
SP(RDFLAGS, "rdflags");
SE(STATS, "stats");
#undef SP
#undef SE
}
void MSG_ShowDeltaUsercmdBits_Enhanced(int bits)
{
if (!bits) {
SHOWBITS("<none>");
return;
}
#define S(b,s) if(bits&CM_##b) SHOWBITS(s)
S(ANGLE1, "angle1");
S(ANGLE2, "angle2");
S(ANGLE3, "angle3");
S(FORWARD, "forward");
S(SIDE, "side");
S(UP, "up");
S(BUTTONS, "buttons");
S(IMPULSE, "msec");
#undef S
}
#endif // USE_CLIENT
#if USE_CLIENT || USE_MVD_CLIENT
void MSG_ShowDeltaEntityBits(int bits)
{
#define S(b,s) if(bits&U_##b) SHOWBITS(s)
S(MODEL, "modelindex");
S(MODEL2, "modelindex2");
S(MODEL3, "modelindex3");
S(MODEL4, "modelindex4");
if (bits & U_FRAME8)
SHOWBITS("frame8");
if (bits & U_FRAME16)
SHOWBITS("frame16");
if ((bits & (U_SKIN8 | U_SKIN16)) == (U_SKIN8 | U_SKIN16))
SHOWBITS("skinnum32");
else if (bits & U_SKIN8)
SHOWBITS("skinnum8");
else if (bits & U_SKIN16)
SHOWBITS("skinnum16");
if ((bits & (U_EFFECTS8 | U_EFFECTS16)) == (U_EFFECTS8 | U_EFFECTS16))
SHOWBITS("effects32");
else if (bits & U_EFFECTS8)
SHOWBITS("effects8");
else if (bits & U_EFFECTS16)
SHOWBITS("effects16");
if ((bits & (U_RENDERFX8 | U_RENDERFX16)) == (U_RENDERFX8 | U_RENDERFX16))
SHOWBITS("renderfx32");
else if (bits & U_RENDERFX8)
SHOWBITS("renderfx8");
else if (bits & U_RENDERFX16)
SHOWBITS("renderfx16");
S(ORIGIN1, "origin[0]");
S(ORIGIN2, "origin[1]");
S(ORIGIN3, "origin[2]");
S(ANGLE1, "angles[0]");
S(ANGLE2, "angles[1]");
S(ANGLE3, "angles[2]");
S(OLDORIGIN, "old_origin");
S(SOUND, "sound");
S(EVENT, "event");
S(SOLID, "solid");
#undef S
}
void MSG_ShowDeltaPlayerstateBits_Packet(int flags)
{
#define S(b,s) if(flags&PPS_##b) SHOWBITS(s)
S(M_TYPE, "pmove.pm_type");
S(M_ORIGIN, "pmove.origin[0,1]");
S(M_ORIGIN2, "pmove.origin[2]");
S(VIEWOFFSET, "viewoffset");
S(VIEWANGLES, "viewangles[0,1]");
S(VIEWANGLE2, "viewangles[2]");
S(KICKANGLES, "kick_angles");
S(WEAPONINDEX, "gunindex");
S(WEAPONFRAME, "gunframe");
S(GUNOFFSET, "gunoffset");
S(GUNANGLES, "gunangles");
S(BLEND, "blend");
S(FOV, "fov");
S(RDFLAGS, "rdflags");
S(STATS, "stats");
#undef S
}
const char *MSG_ServerCommandString(int cmd)
{
switch (cmd) {
case -1: return "END OF MESSAGE";
default: return "UNKNOWN COMMAND";
#define S(x) case svc_##x: return "svc_" #x;
S(bad)
S(muzzleflash)
S(muzzleflash2)
S(temp_entity)
S(layout)
S(inventory)
S(nop)
S(disconnect)
S(reconnect)
S(sound)
S(print)
S(stufftext)
S(serverdata)
S(configstring)
S(spawnbaseline)
S(centerprint)
S(download)
S(playerinfo)
S(packetentities)
S(deltapacketentities)
S(frame)
S(zpacket)
S(zdownload)
S(gamestate)
#undef S
}
}
#endif // USE_CLIENT || USE_MVD_CLIENT
#endif // _DEBUG
|
qbism/coopx
|
src/common/msg.c
|
C
|
gpl-2.0
| 64,865
|
// $Id$
(function ($) {
/**
* Toggles the collapsible region.
*/
Drupal.behaviors.mementoAdminToggle = {
attach: function (context, settings) {
$('.collapsible-toggle a, context').click(function() {
$('#section-collapsible').toggleClass('toggle-active').find('.region-collapsible').slideToggle('fast');
return false;
});
}
}
/**
* CSS Help for IE.
* - Adds even odd striping and containers for images in posts.
* - Adds a .first-child class to the first paragraph in each wrapper.
* - Adds a prompt containing the link to a comment for the permalink.
*/
Drupal.behaviors.mementoPosts = {
attach: function (context, settings) {
// Detects IE6-8.
if (!jQuery.support.leadingWhitespace) {
$('.article-content p:first-child').addClass('first-child');
$('.article-content img, context').parent(':not(.field-item, .user-picture)').each(function(index) {
var stripe = (index/2) ? 'even' : 'odd';
$(this).wrap('<div class="content-image-' + stripe + '"></div>');
});
}
// Comment link copy promt.
$("time span a").click( function() {
prompt('Link to this comment:', this.href);
return false;
});
}
}
})(jQuery);
|
geoffreygevalt/ywp
|
sites/all/themes/at_memento/js/scripts.js
|
JavaScript
|
gpl-2.0
| 1,253
|
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2015 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2015
*/
/**
* Files required.
*/
class CRM_Campaign_Form_Search_Petition extends CRM_Core_Form {
/**
* Are we forced to run a search.
*
* @var int
*/
protected $_force;
/**
* Processing needed for buildForm and later.
*/
public function preProcess() {
$this->_search = CRM_Utils_Array::value('search', $_GET);
$this->_force = CRM_Utils_Request::retrieve('force', 'Boolean', $this, FALSE, FALSE);
$this->_searchTab = CRM_Utils_Request::retrieve('type', 'String', $this, FALSE, 'petition');
//when we do load tab, lets load the default objects.
$this->assign('force', ($this->_force || $this->_searchTab) ? TRUE : FALSE);
$this->assign('searchParams', json_encode($this->get('searchParams')));
$this->assign('buildSelector', $this->_search);
$this->assign('searchFor', $this->_searchTab);
$this->assign('petitionCampaigns', json_encode($this->get('petitionCampaigns')));
$this->assign('suppressForm', TRUE);
//set the form title.
CRM_Utils_System::setTitle(ts('Find Petition'));
}
/**
* Build the form object.
*/
public function buildQuickForm() {
if ($this->_search) {
return;
}
$attributes = CRM_Core_DAO::getAttribute('CRM_Campaign_DAO_Survey');
$this->add('text', 'petition_title', ts('Title'), $attributes['title']);
//campaigns
$campaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
$this->add('select', 'petition_campaign_id', ts('Campaign'), array('' => ts('- select -')) + $campaigns);
$this->set('petitionCampaigns', $campaigns);
$this->assign('petitionCampaigns', json_encode($campaigns));
//build the array of all search params.
$this->_searchParams = array();
foreach ($this->_elements as $element) {
$name = $element->_attributes['name'];
$label = $element->_label;
if ($name == 'qfKey') {
continue;
}
$this->_searchParams[$name] = ($label) ? $label : $name;
}
$this->set('searchParams', $this->_searchParams);
$this->assign('searchParams', json_encode($this->_searchParams));
}
}
|
alfonsom/ccdrupal
|
sites/all/modules/civicrm/CRM/Campaign/Form/Search/Petition.php
|
PHP
|
gpl-2.0
| 3,864
|
#!/bin/sh
REQUEST=""
while read name
do
LINE=`echo "$name" | egrep -i "[a-z:]"`
if [ -z "$LINE" ]
then
break
fi
echo "$name" >> scripts/logs/iis.log
NEWREQUEST=`echo "$name" | grep "GET .scripts.*cmd.exe.*dir.* HTTP/1.0"`
if [ ! -z "$NEWREQUEST" ] ; then
REQUEST=$NEWREQUEST
fi
done
if [ -z "$REQUEST" ] ; then
cat << _eof_
HTTP/1.1 404 NOT FOUND
Server: Microsoft-IIS/5.0
P3P: CP='ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR SAMo CNT COM INT NAV ONL PHY PRE PUR UNI'
Content-Location: http://cpmsftwbw27/default.htm
Date: Thu, 04 Apr 2002 06:42:18 GMT
Content-Type: text/html
Accept-Ranges: bytes
<html><title>You are in Error</title>
<body>
<h1>You are in Error</h1>
O strange and inconceivable thing! We did not really die, we were not really buried, we were not really crucified and raised again, but our imitation was but a figure, while our salvation is in reality. Christ was actually crucified, and actually buried, and truly rose again; and all these things have been vouchsafed to us, that we, by imitation communicating in His sufferings, might gain salvation in reality. O surpassing loving-kindness! Christ received the nails in His undefiled hands and feet, and endured anguish; while to me without suffering or toil, by the fellowship of His pain He vouchsafed salvation.
<p>
St. Cyril of Jerusalem, On the Christian Sacraments.
</body>
</html>
_eof_
exit 0
fi
DATE=`date`
cat << _eof_
HTTP/1.0 200 OK
Date: $DATE
Server: Microsoft-IIS/5.0
Connection: close
Content-Type: text/plain
Volume in drive C is Webserver
Volume Serial Number is 3421-07F5
Directory of C:\inetpub
01-20-02 3:58a <DIR> .
08-21-01 9:12a <DIR> ..
08-21-01 11:28a <DIR> AdminScripts
08-21-01 6:43p <DIR> ftproot
07-09-00 12:04a <DIR> iissamples
07-03-00 2:09a <DIR> mailroot
07-16-00 3:49p <DIR> Scripts
07-09-00 3:10p <DIR> webpub
07-16-00 4:43p <DIR> wwwroot
0 file(s) 0 bytes
20 dir(s) 290,897,920 bytes free
_eof_
|
Banjong1990/honey
|
scripts/backdoors/web.sh
|
Shell
|
gpl-2.0
| 2,138
|
<?php
/**
* DNS Library for handling lookups and updates.
*
* Copyright (c) 2020, Mike Pultz <mike@mikepultz.com>. All rights reserved.
*
* See LICENSE for more details.
*
* @category Networking
* @package Net_DNS2
* @author Mike Pultz <mike@mikepultz.com>
* @copyright 2020 Mike Pultz <mike@mikepultz.com>
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @link https://netdns2.com/
* @since File available since Release 1.4.0
*
*/
/**
* The CDNSKEY RR is implemented exactly like the DNSKEY record, so
* for now we just extend the DNSKEY RR and use it.
*
* http://www.rfc-editor.org/rfc/rfc7344.txt
*
*/
class Net_DNS2_RR_CDNSKEY extends Net_DNS2_RR_DNSKEY
{
}
|
Cacti/plugin_mactrack
|
Net/DNS2/RR/CDNSKEY.php
|
PHP
|
gpl-2.0
| 731
|
<?php
/**
* SpecialMobileWebApp.php
*/
/**
* Get raw mobile formatted content for App
*/
class SpecialMobileWebApp extends MobileSpecialPage {
/**
* Construct function
*/
public function __construct() {
parent::__construct( 'MobileWebApp' );
}
/**
* Render the special page
* @param string|null $par Special page to load (for now only "manifest")
*/
public function executeWhenAvailable( $par ) {
if ( $par === 'manifest' ) {
$this->generateManifest();
} else {
$out = $this->getOutput();
$out->addModules( 'mobile.special.app.scripts' );
$out->setPageTitle( $this->msg( 'mobile-frontend-app-title' )->escaped() );
}
}
/**
* Show the App cache manifest
* @see genAppCache()
*/
public function generateManifest() {
$this->getOutput()->disable();
$this->genAppCache();
}
/**
* Given HTML markup searches for URLs inside elements
* FIXME: Refactor OutputPage in MediaWiki core so this is unnecessary
* @param string $html
* @param string $tag A tag to extract URLs from (e.g. 'link' or 'script')
* @param string $attr An attribute to find the URL (e.g. 'href' or 'src')
* @return array of urls
*/
private function extractUrls( $html, $tag, $attr ) {
$doc = new DOMDocument();
$doc->loadHTML( $html );
$links = $doc->getElementsByTagName( $tag );
$urls = array();
foreach( $links as $link ) {
$val = $link->getAttribute( $attr );
if ( $val ) {
$urls[] = $val;
}
}
return $urls;
}
/**
* Utility function to get relative path part of the URL.
* @param string $url The URL from which to extract the relative path
* @return string The relative path of the URL
*/
private function getRelativePath( $url ) {
// first, let's try the easy way
$parts = wfParseUrl( $url );
// if that didn't work, let's try the standard way
$parts = $parts ? $parts : parse_url( $url );
return isset( $parts['path'] ) && isset( $parts['query'] ) ?
$parts['path'] . '?' . $parts['query'] :
$parts['path'];
}
/**
* Generates a cache manifest for the current skin
* that contains JavaScript start up URL, and the URLs
* for stylesheets in the page for use in an offline web
* application
* See: http://www.w3.org/TR/2011/WD-html5-20110525/offline.html
*/
private function genAppCache() {
// This parameter currently hardcoded
$target = 'mobile';
$out = $this->getOutput();
$out->setTarget( $target );
$css = $out->buildCssLinks();
$scriptUrls = implode( "\n", $this->extractUrls( $out->getHeadScripts(), 'script', 'src' ) );
$scriptUrls = $this->getRelativePath( $scriptUrls );
$styleUrls = implode( "\n", $this->extractUrls( $css, 'link', 'href' ) );
$styleUrls = $this->getRelativePath( $styleUrls );
$rl = $out->getResourceLoader();
$styles = $out->getModuleStyles();
$ctx = new ResourceLoaderContext( $rl, new FauxRequest() );
$fr = new FauxRequest( array(
'debug' => false,
'lang' => $this->getLanguage()->getCode(),
'modules' => 'startup',
'only' => 'scripts',
'skin' => $out->getSkin()->getSkinName(),
'target' => $out->getTarget(),
));
$startupCtx = new ResourceLoaderContext( new ResourceLoader(), $fr );
$startupUrl = ResourceLoaderStartUpModule::getStartupModulesUrl( $startupCtx );
$startupUrl = $this->getRelativePath( $startupUrl );
// Add a ts parameter for cachebusting when things change
$urls = "\n$scriptUrls\n$styleUrls\n$startupUrl";
// TODO: add timestamp components in checksum calculation?
// Granted, it's used below. So maybe that's good enough,
// at least if we're totally confident in the timestamp logic.
// We'll just make it more user friendly in time.
$checksum = sha1( $urls );
$req = $this->getRequest();
$resp = $req->response();
$resp->header( 'Content-type: text/cache-manifest; charset=UTF-8' );
$resp->header( 'Cache-Control: public, max-age=300, s-maxage=300' );
$resp->header( "ETag: $checksum" );
$localBasePath = dirname( __DIR__ );
$ts = max(
filemtime( "${localBasePath}/specials/SpecialMobileWebApp.php" ),
filemtime( "${localBasePath}/skins/SkinMinervaApp.php" )
);
// TODO: validate timestamp checking. Some bugs don't manifest on
// WMF production's PECL memcached backing, although it becomes
// a problem with Redis (e.g., in MediaWiki-Vagrant) at the moment
foreach( $styles as $name) {
$module = $rl->getModule( $name );
if ( $module ) {
$lastModified = $module->getModifiedTime( $ctx );
if ( $lastModified === $module->getDefinitionMtime( $ctx ) ) {
// This means no caching is setup (see bug 59623)
// round module changes to nearest 10 minutes
// (shouldn't happen in production)
$lastModified = $lastModified - ( $lastModified % 600 );
}
$ts = max( $ts, $lastModified );
}
}
echo <<<HTML
CACHE MANIFEST
# Last modified ${ts}
NETWORK:
*
HTML;
echo <<<HTML
CACHE:
{$urls}
# {$checksum}
HTML;
}
}
|
dannypage/datum-club
|
extensions/MobileFrontend/includes/specials/SpecialMobileWebApp.php
|
PHP
|
gpl-2.0
| 4,923
|
/*
* This file is part of SEconomy - A server-sided currency implementation
* Copyright (C) 2013-2014, Tyler Watson <tyler@tw.id.au>
*
* 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Wolfje.Plugins.SEconomy.Journal {
public class PendingTransactionEventArgs : EventArgs {
IBankAccount fromAccount;
IBankAccount toAccount;
public PendingTransactionEventArgs(IBankAccount From, IBankAccount To, Money Amount, BankAccountTransferOptions Options, string TransactionMessage, string LogMessage) : base()
{
this.fromAccount = From;
this.toAccount = To;
this.Amount = Amount;
this.Options = Options;
this.TransactionMessage = TransactionMessage;
this.JournalLogMessage = LogMessage;
this.IsCancelled = false;
}
/// <summary>
/// Specifies the source bank account the amount is to be transferred from
/// </summary>
public IBankAccount FromAccount {
get {
return fromAccount;
}
set {
if (value == null) {
throw new ArgumentNullException("FromAaccount cannot be set to null.");
}
fromAccount = value;
}
}
/// <summary>
/// Specifies the destination account the amount is to be transferred to
/// </summary>
public IBankAccount ToAccount {
get {
return toAccount;
}
set {
if (value == null) {
throw new ArgumentNullException("ToAccount cannot be set to null.");
}
toAccount = value;
}
}
public Money Amount { get; set; }
public BankAccountTransferOptions Options { get; private set; }
/// <summary>
/// Specifies the transaction message
/// </summary>
public string TransactionMessage { get; set; }
/// <summary>
/// Specifies the journal message
/// </summary>
public string JournalLogMessage { get; set; }
/// <summary>
/// Cancels the transaction
/// </summary>
public bool IsCancelled { get; set; }
}
}
|
tylerjwatson/SEconomy
|
SEconomyPlugin/Journal/PendingTransactionEventArgs.cs
|
C#
|
gpl-2.0
| 2,635
|
#
# Makefile for RTC class/drivers.
#
obj-$(CONFIG_RTC_LIB) += rtc-lib.o
obj-$(CONFIG_RTC_CLASS) += class.o
# Keep the list ordered.
obj-$(CONFIG_RTC_DRV_ABRACON) += rtc-abracon.o
obj-$(CONFIG_RTC_DRV_DS1307) += rtc-ds1307.o
obj-$(CONFIG_RTC_DRV_IMXDI) += rtc-imxdi.o
obj-$(CONFIG_RTC_DRV_JZ4740) += rtc-jz4740.o
|
masahir0y/barebox-yamada
|
drivers/rtc/Makefile
|
Makefile
|
gpl-2.0
| 339
|
//
// RECommonFunctions.h
// RESideMenu
//
// Copyright (c) 2013-2014 Roman Efimov (https://github.com/romaonthego)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#ifndef REUIKitIsFlatMode
#define REUIKitIsFlatMode() RESideMenuUIKitIsFlatMode()
#endif
#ifndef kCFCoreFoundationVersionNumber_iOS_6_1
#define kCFCoreFoundationVersionNumber_iOS_6_1 793.00
#endif
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_6_1
#define IF_IOS7_OR_GREATER(...) \
if (kCFCoreFoundationVersionNumber > kCFCoreFoundationVersionNumber_iOS_6_1) \
{ \
__VA_ARGS__ \
}
#else
#define IF_IOS7_OR_GREATER(...)
#endif
BOOL RESideMenuUIKitIsFlatMode(void);
|
loiwu/MEUM
|
iMEUM/iMEUM/3rd/RESideMenu/RECommonFunctions.h
|
C
|
gpl-2.0
| 1,721
|
/*
* Copyright (C) 2015-2016 Team Kodi
* http://kodi.tv
*
* 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; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#pragma once
#include "JoystickTypes.h"
namespace JOYSTICK
{
/*!
* \brief Interface for handling keymap keys
*
* Keys can be mapped to analog actions (e.g. "AnalogSeekForward") or digital
* actions (e.g. "Up").
*/
class IKeymapHandler
{
public:
virtual ~IKeymapHandler(void) { }
/*!
* \brief Get the type of action mapped to the specified key ID
*
* \param keyId The key ID from Key.h
*
* \return The type of action mapped to keyId, or INPUT_TYPE::UNKNOWN if
* no action is mapped to the specified key
*/
virtual INPUT_TYPE GetInputType(unsigned int keyId) const = 0;
/*!
* \brief Get the action ID mapped to the specified key ID
*
* \param keyId The key ID from Key.h
*
* \return The action ID, or ACTION_NONE if no action is mapped to the
* specified key
*/
virtual int GetActionID(unsigned int keyId) const = 0;
/*!
* \brief A key mapped to a digital action has been pressed or released
*
* \param keyId The key ID from Key.h
* \param bPressed true if the key's button/axis is activated, false if deactivated
* \param holdTimeMs The held time in ms for pressed buttons, or 0 for released
*/
virtual void OnDigitalKey(unsigned int keyId, bool bPressed, unsigned int holdTimeMs = 0) = 0;
/*!
* \brief Callback for keys mapped to analog actions
*
* \param keyId The button key ID from Key.h
* \param magnitude The amount of the analog action
*
* If keyId is not mapped to an analog action, no action need be taken
*/
virtual void OnAnalogKey(unsigned int buttonKeyId, float magnitude) = 0;
};
}
|
koying/xbmc
|
xbmc/input/joysticks/IKeymapHandler.h
|
C
|
gpl-2.0
| 2,472
|
# Django 모델
이번에 우리가 만들고자 하는 부분은 블로그 내 모든 포스트를 저장하는 부분이에요. 먼저 우리는 `객체(object)`에 대해서 조금 알고 있어야해요.
## 객체(Object)
프로그래밍 개발 방법 중에는 `객체 지향 프로그래밍`이라 부르는 개념이 있어요. 이 개발 방법은 프로그램이 어떻게 작동해야하는지 모든 것을 하나하나 지시하는 것 대신, 모델을 만들어 그 모델이 어떤 역할을 가지고 어떻게 행동해야하는지 정의하여 서로 알아서 상호작용할 수 있도록 만드는 것입니다.
그렇다면 객체란 무엇일까요? 객체란 속성과 행동을 모아놓은 것이라고 할 수 있어요. 낯설게 느껴지지만 예를 들어보면 별 것 아님을 알게 될 거에요.
예를 들어 `고양이(Cat)`라는 객체를 모델링한다고 해볼게요. 이 고양이는 여러 속성을 가지고 있어요: `색깔`, `나이`, `분위기`(착한, 나쁜, 졸려워하는), `주인`(주인이 `사람`일 수도 있지만, 길고양이면 주인이 없으니 속성이 빈 값이 될 수 있어요.) 등이 될 수 있겠지요.
또 `고양이는` 특정 행동을 할 수 있어요: `야옹야옹하기`, `긁기`, 또는 `먹기` 등이 있겠네요. (`맛`과, 고양이에게 `고양이먹이`는 행동하는 객체가 달라요).
고양이
--------
색깔
나이
분위기
주인
야옹야옹하기()
긁기()
먹기(음식)
고양이먹이
--------
맛
기본적으로 객체지향설계 개념은 현실에 존재하는 것을 속성과 행위로 나타내는 것입니다. 여기서 속성은 `객체 속성(properties)`, 행위는 `메서드(methods)`로 구현됩니다).
그렇다면 블로그 글을 모델로 만들 수 있을까요? 우리는 블로그를 만들고 싶잖아요, 그렇죠?
우리는 다음 질문에 답할 수 있어야 해요: 블로그 글이란 무엇일까? 어떤 속성들을 가져야 할까?
블로그는 제목과 내용이 필요하죠? 그리고 누가 썼는지도 알 수 있게 작성자(author) 도 추가하면 좋을 것 같아요. 마지막으로, 그 글이 작성된 날짜와 게시된 날짜도 알면 좋겠어요.
Post
--------
title
text
author
created_date
published_date
블로그 글로 할 수 있는 것은 어떤 것들이 있을까요? 글을 출판하는 `메서드(method)`가 있으면 좋겠죠?
그래서 우리는 `publish` 메서드도 만들어야 합니다.
이제 무엇을 만들어야하는지 이미 알았으니, 장고에서 모델을 만들어 봅시다!
## 장고 모델
객체(object) 가 어떻게 구성되어야 하는지 이전에 살펴봤으니, 이번에는 블로그 글을 위한 장고 모델을 만들어봅시다.
장고 안의 모델은 객체의 특별한 종류입니다. 이 모델을 저장하면 그 내용이 `데이터베이스`에 저장되는 것이 특별한 점이죠. 데이터베이스란 데이터의 집합입니다. 데이터들이 모아져 있는 곳이지요. 이곳에 유저에 대한 정보나 여러분의 블로그 글 등등이 저장되어 있습니다. 우리는 데이터를 저장하기 위해서 여러가지 데이터베이스를 입맛에 맞게 고를 수 있는데요, 여기서는 SQLite 데이터베이스를 사용하겠습니다. 'Sqlite 데이터베이스는 기본 장고 데이터베이스 어댑터입니다.' 라는 것까지만 알고 있어도 충분해요. 어댑터가 무엇인지를 알려면 내용이 너무 길어지니 일단 여기까지만 알고 계세요.
쉽게 말해 데이터베이스안의 모델이란 엑셀 스프레드시트와 같다고 말할 수 있어요. 엑셀 스프레드시트를 보면 열(필드) 와 행(데이터) 로 구성되어 있죠? 모델도 마찬가지입니다.
### 어플리케이션 제작하기
잘 정돈된 상태에서 시작하기 위해, 프로젝트 내부에 별도의 어플리케이션을 만들어볼 거에요. 처음부터 모든 것이 잘 준비되어있다면 훌륭하죠. 어플리케이션을 만들기 위해 콘솔창(`djangogirls` 디렉토리에서 `manage.py` 파일)에서 아래 명령어를 실행하세요.
(myvenv) ~/djangogirls$ python manage.py startapp blog
이제 `blog` 디렉토리가 생성되고 그 안에 여러 파일들도 같이 들어있는 것을 알 수 있어요. 현재 디렉토리와 파일들은 다음과 같을 거에요:
djangogirls
├── mysite
| __init__.py
| settings.py
| urls.py
| wsgi.py
├── manage.py
└── blog
├── migrations
| __init__.py
├── __init__.py
├── admin.py
├── models.py
├── tests.py
└── views.py
어플리케이션을 생성한 후 장고에게 사용해야한다고 알려줘야 합니다. 이 역할을 하는 파일이 `mysite/settings.py`입니다. 이 파일 안에서 `INSTALLED_APPS`를 열어, `)`바로 위에 `'blog'`를 추가하세요. 최종 결과물은 아래와 다음과 같을 거에요.
python
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
)
### 블로그 글 모델 만들기
모든 `Model` 객체는 `blog/models.py` 파일에 선언하여 모델을 만듭니다. 이 파일에 우리의 블로그 글 모델도 정의할 거에요.
`blog/models.py` 파일을 열어서 안에 모든 내용을 삭제한 후 아래 코드를 추가하세요:
python
from django.db import models
from django.utils import timezone
class Post(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
> `str`양 옆에 언더스코어(`_`) 를 두 개씩 넣었는지 다시 확인하세요. 이건 관습은 파이썬에서 자주 사용되는데, "던더(dunder; 더블-언더스코어의 준말)"라고도 불려요.
으음... 코드가 좀 무서워졌죠? 걱정마세요. 각 줄마다 어떤 의미인지 설명해드릴거에요.
`from` 또는 `import`로 시작하는 부분은 다른 파일에 있는 것을 추가하라는 뜻입니다. 다시 말해, 매번 다른 파일에 있는 것을 복사&붙여넣기로 해야하는 작업을 `from</0>이 대신 불러와주는 거죠 .</p>
<p><code>class Post(models.Model):`는 모델을 정의하는 코드입니다. (모델은 `객체(object)`라고 했죠?).
* `class`는 특별한 키워드로, 객체를 정의한다는 것을 알려줍니다.
* `Post`는 모델의 이름입니다. (특수문자와 공백 제외한다면) 다른 이름을 붙일 수도 있습니다. 항상 클래스 이름의 첫 글자는 대문자로 써야 합니다.
* `models.Model`은 Post가 장고 모델임을 의미합니다. 이 코드 때문에 장고는 Post가 데이터베이스에 저장되어야 된다고 알게 됩니다.
이제 속성을 정의하는 것에 대해서 이야기해볼게요: `title`, `text`, `created_date`, `published_date`, `author`에 대해서 말할 거에요. 속성을 정의하기 위해, 각 필드마다 어떤 종류의 데이터 타입을 가지는지를 정해야해요. 여기서 데이터 타입에는 텍스트, 숫자, 날짜, 유저 같은 다른 객체 참조 등이 있습니다.
* `models.CharField` - 글자 수가 제한된 텍스트를 정의할 때 사용합니다. 글 제목같이 대부분의 짧은 문자열 정보를 저장할 때 사용합니다.
* `models.TextField` - 글자 수에 제한이 없는 긴 텍스트를 위한 속성입니다. 블로그 콘텐츠를 담기 좋겠죠?
* `models.DateTimeField` - 이것은 날짜와 시간을 의미합니다.
* `models.ForeignKey` - 다른 모델이 대한 링크를 의미합니다.
시간 관계 상 모든 코드들을 하나하나 다 설명하지는 않을 거에요. 대신 모델의 필드와 정의하는 방법에 궁금하다면 아래 장고 공식 문서를 꼭 읽어보길 바랍니다. (https://docs.djangoproject.com/en/1.8/ref/models/fields/#field-types).
`def publish(self):`는 무슨 뜻일까요? 이 것이 바로 앞서 말했던 `publish`라는 메서드(method) 입니다. `def`는 이 것이 함수/메서드라는 뜻이고, `publish`는 메서드의 이름입니다. 원한다면 메서드 이름을 변경할 수도 있어요. 이름을 붙일 때는 공백 대신, 소문자와 언더스코어를 사용해야 합니다. 예를 들어, 평균 가격을 계산하는 메서드는 `calculate_average_price`라고 부를 수 있겠네요.
메서드는 자주 무언가를 되돌려주죠. (`return`) 그 예로 `__str__` 메서드를 봅시다. 이 시나리오대로라면, `__str__`를 호출하면 Post 모델의 제목 텍스트(**string**) 를 얻게 될 거에요.
아직 모델에 대해서 잘 모르는 부분이 있다면, 코치에게 자유롭게 물어보세요! 지금 배운 내용이 너무 복잡하게 느껴질 수 있어요. 객체와 함수를 배운 적이 없는 분들이 한꺼번에 배우게 된다면 특히 그렇겠죠. 그래도 해 볼 만한 마법이라고 생각했으면 좋겠어요!
### 데이터베이스에 모델을 위한 테이블 만들기
이 장의 마지막 단계입니다. 이제 데이터베이스에 우리의 새 모델, Post 모델을 추가할 거에요. 먼저 우리는 장고 모델에 (우리가 방금 만든!) 몇 가지 변화가 생겼다는 걸 알게 해줘야 합니다. `python manage.py makemigrations blog` 를 입력해 보세요. 아마도 화면에 이렇게 보이겠죠?
(myvenv) ~/djangogirls$ python manage.py makemigrations blog
Migrations for 'blog':
0001_initial.py:
- Create model Post
장고는 데이터베이스에 지금 반영할 수 있도록 마이그레이션 파일(migration file)이라는 것을 준비해 두었답니다. 이제 `python manage.py migrate blog` 명령을 실행해, 실제 데이터베이스에 모델 추가를 반영하겠습니다. :
(myvenv) ~/djangogirls$ python manage.py migrate blog
Operations to perform:
Apply all migrations: blog
Running migrations:
Rendering model states... DONE
Applying blog.0001_initial... OK
만세! 드디어 글 모델이 데이터베이스에 저장되었습니다. 너무 멋지 않나요? 빨리 다음 장으로 넘어가서 블로그 글을 확인하러 가요!
|
humitos/argentinaenpython.com.ar
|
djangogirls/tutorial/crowdin/ko/django_models/README.md
|
Markdown
|
gpl-2.0
| 11,074
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Intel, Pavel A. Ozhdikhin
*
*/
#ifndef _OPTARITHMETIC_H
#define _OPTARITHMETIC_H
namespace Jitrino {
/*
* Implemented algorithms are similar to the ones described in
* [T.Granlund and P.L.Montgomery. Division by Invariant Integers using
* Multiplication. PLDI, 1994]
*/
template <typename inttype, int width> inline int popcount(inttype x);
template <>
inline
int popcount<I_32, 32> (I_32 x)
{
#ifdef _USE_ITANIUM_INTRINSICS_
U_32 y = x; // avoid sign extension
__m64 z = _m_from_int(int(y));
__m64 r = __m64_popcnt(z);
return _m_to_int(r);
#else
x = x - ((x >>1) & 0x55555555);
x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
x = (x + (x >> 4)) & 0x0f0f0f0f;
x = x + (x >> 8);
x = x + (x >> 16);
return x & 0x0000003F;
#endif
}
template <>
inline
int popcount<int64, 64> (int64 x)
{
#ifdef _USE_ITANIUM_INTRINSICS_
__m64 y = _m_fron_int(int(x));
__m64 r = __m64_popcnt(y);
return _m_to_int(r);
#else
int64 tmp5 = 0x55555555;
tmp5 = tmp5 | (tmp5 << 32);
x = x - ((x >>1) & tmp5);
int64 tmp3 = 0x33333333;
tmp3 = tmp3 | (tmp3 << 32);
x = (x & tmp3) + ((x >> 2) & tmp3);
int64 tmp0f = 0x0f0f0f0f;
tmp0f = tmp0f | (tmp0f << 32);
x = (x + (x >> 4)) & tmp0f;
x = x + (x >> 8);
x = x + (x >> 16);
x = x + (x >> 32);
return int(x & 0x0000007F);
#endif
}
template <typename inttype>
bool isPowerOf2(inttype d) {
if (d < 0) {
d = -d;
}
// turn trailing 0s into 1s, others become 0
inttype justrightzeros = (~d) & (d - 1);
inttype bitandleftbits = ~justrightzeros;
// rightmost 1-bit and trailing 0s:
inttype bitandrightzeros = d ^ (d - 1);
inttype justrightbit = bitandrightzeros & bitandleftbits;
if (d == justrightbit) {
return true;
} else {
return false;
}
}
template <typename inttype, typename uinttype,
int width>
void
getMagic(inttype d, inttype *magicNum, inttype *shiftBy)
{
// d must not be -1, 0, 1
assert((d < -1) || (d > 1));
const uinttype hiBitSet = (uinttype)1 << (width-1);
uinttype ad = abs(d); // ad = |d|
uinttype t = hiBitSet + (((uinttype)d) >> (width-1));
uinttype anc = t - 1 - (t%ad); // anc = |nc|
// initial value, we try values from [width-1, 2*width]
uinttype p = width-1; // power of 2 to divide by
// these are maintained incrementally in loop as p is changed
uinttype q1 = hiBitSet / anc; // q1 = 2**p/|nc|
uinttype r1 = hiBitSet - q1*anc; // r1 = rem(2**p, |nc|)
uinttype q2 = hiBitSet / ad; // q2 = 2**p /|d|
uinttype r2 = hiBitSet - q2*ad; // r2 = rem(2**p, |d|)
uinttype delta = 0;
do {
p = p + 1;
// increment q1, r1, q2, r2
q1 = q1 << 1;
r1 = r1 << 1;
q2 = q2 << 1;
r2 = r2 << 1;
// r1 overflows into q1
if (r1 >= anc) {
q1 = q1 + 1;
r1 = r1 - anc;
}
// r2 overflows into q2
if (r2 >= ad) {
q2 = q2 + 1;
r2 = r2 - ad;
}
delta = ad - r2;
} while ((q1 < delta) || ((q1 == delta) && (r1 == 0)));
inttype mag1 = q2 + 1;
*magicNum = (d < 0) ? -mag1 : mag1;
*shiftBy = p - width;
}
// isolate leftmost 1
template <typename inttype>
inline
inttype leftmost1(inttype x);
template <>
inline
I_32 leftmost1<I_32>(I_32 x)
{
if (x == 1) return 1;
if (x == 0) return 0;
x = x | (x >> 1);
x = x | (x >> 2);
x = x | (x >> 4);
x = x | (x >> 8);
x = x | (x >> 16);
x = x >> 1;
x = x + 1;
return x;
}
template <>
inline
int64 leftmost1<int64>(int64 x)
{
if (x == 1) return 1;
if (x == 0) return 0;
x = x | (x >> 1);
x = x | (x >> 2);
x = x | (x >> 4);
x = x | (x >> 8);
x = x | (x >> 16);
x = x | (x >> 32);
x = x >> 1;
x = x + 1;
return x;
}
// number of leading (leftmost) zeros
template <typename inttype, int width>
inline
int nlz(inttype x);
template <>
inline
int nlz<I_32, 32>(I_32 x)
{
x = x | (x >> 1);
x = x | (x >> 2);
x = x | (x >> 4);
x = x | (x >> 8);
x = x | (x >> 16);
return popcount<I_32, 32>(~x);
}
template <>
inline
int nlz<int64, 64>(int64 x)
{
x = x | (x >> 1);
x = x | (x >> 2);
x = x | (x >> 4);
x = x | (x >> 8);
x = x | (x >> 16);
x = x | (x >> 32);
return popcount<int64, 64>(~x);
}
// number of trailing (rightmost) zeros
template <typename inttype, int width>
inline
int ntz(inttype x)
{
inttype trailingzeromask = (~x) & (x - 1);
return popcount<inttype, width>(trailingzeromask);
}
template <typename inttype, int width>
inline
int whichPowerOf2(inttype d) {
bool isNegative = ((d < 0) && (d != -d));
if (isNegative) {
d = -d;
}
int i = ntz<inttype, width>(d);
if (isNegative)
return -i;
else
return i;
}
template <typename inttype>
inline
int shifttomakeOdd(inttype d, inttype &newd)
{
assert(d != 0);
int i = 0;
while ((d & 1) == 0) {
++i;
d = d >> 1;
}
newd = d;
return i;
}
template <typename uinttype>
inline uinttype isqrt_iter(uinttype n, uinttype approx)
{
uinttype q = n / approx;
uinttype newapprox = (approx + q) / 2;
while (q != newapprox) {
if (newapprox == approx) return approx;
approx = newapprox;
q = n / approx;
newapprox = (approx + q) / 2;
}
return newapprox;
}
template <typename uinttype> inline uinttype isqrt(uinttype n);
template <> inline uint64 isqrt(uint64 n) { return isqrt_iter(n, (uint64) 65536); }
template <> inline U_32 isqrt(U_32 n) { return isqrt_iter(n, (U_32) 256); }
template <> inline uint16 isqrt(uint16 n) { return isqrt_iter(n, (uint16) 16); }
template <> inline U_8 isqrt(U_8 n) { return isqrt_iter(n, (U_8) 4); }
} //namespace Jitrino
#endif // _OPTARITHMETIC_H
|
skyHALud/codenameone
|
Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/drlvm/vm/jitrino/src/optimizer/optarithmetic.h
|
C
|
gpl-2.0
| 7,121
|
<?php
/**
* Pro features meta box.
*
* @package WP_Smush
*
* @var string $upsell_url Upsell URL.
*/
if ( ! defined( 'WPINC' ) ) {
die;
}
?>
<ul class="smush-pro-features">
<li class="smush-pro-feature-row">
<div class="smush-pro-feature-title">
<?php esc_html_e( 'Super-smush lossy compression', 'wp-smushit' ); ?></div>
<div class="smush-pro-feature-desc">
<?php
esc_html_e(
'Optimize images 2x more than regular smushing and with no visible loss in quality using Smush’s intelligent multi-pass lossy compression.',
'wp-smushit'
);
?>
</div>
</li>
<li class="smush-pro-feature-row">
<div class="smush-pro-feature-title">
<?php esc_html_e( 'WPMU DEV CDN with WebP Support', 'wp-smushit' ); ?></div>
<div class="smush-pro-feature-desc">
<?php
esc_html_e(
'Serve your images from our CDN from 45 blazing fast servers around the world. Enable automatic image sizing and WebP support and your website will be absolutely flying.',
'wp-smushit'
);
?>
</div>
</li>
<li class="smush-pro-feature-row">
<div class="smush-pro-feature-title">
<?php esc_html_e( 'Smush my original full size images', 'wp-smushit' ); ?></div>
<div class="smush-pro-feature-desc">
<?php
esc_html_e(
'By default, Smush only compresses thumbnails and image sizes generated by WordPress. With Smush Pro you can also smush your original images.',
'wp-smushit'
);
?>
</div>
</li>
<li class="smush-pro-feature-row">
<div class="smush-pro-feature-title">
<?php esc_html_e( 'Make a copy of my full size images', 'wp-smushit' ); ?></div>
<div class="smush-pro-feature-desc">
<?php
esc_html_e(
'Save copies the original full-size images you upload to your site so you can restore them at any point. Note: Activating this setting will double the size of the uploads folder where your site’s images are stored.',
'wp-smushit'
);
?>
</div>
</li>
<li class="smush-pro-feature-row">
<div class="smush-pro-feature-title">
<?php esc_html_e( 'Auto-convert PNGs to JPEGs (lossy)', 'wp-smushit' ); ?></div>
<div class="smush-pro-feature-desc">
<?php
esc_html_e(
'When you compress a PNG, Smush will check if converting it to JPEG could further reduce its size, and do so if necessary,',
'wp-smushit'
);
?>
</div>
</li>
<li class="smush-pro-feature-row">
<div class="smush-pro-feature-title">
<?php esc_html_e( 'NextGen Gallery Integration', 'wp-smushit' ); ?></div>
<div class="smush-pro-feature-desc">
<?php
esc_html_e( 'Allow smushing images directly through NextGen Gallery settings.', 'wp-smushit' );
?>
</div>
</li>
</ul>
<div class="sui-upsell-row">
<img class="sui-image sui-upsell-image sui-upsell-image-smush" src="<?php echo esc_url( WP_SMUSH_URL . 'app/assets/images/smush-promo.png' ); ?>">
<div class="sui-notice sui-notice-purple smush-upsell-notice">
<p>
<?php
printf(
/* translators: %1$s: starting a tag, %2$s: ending a tag */
esc_html__(
'Smush Pro gives you all these extra settings and absolutely no limits on smushing your images. Did we mention Smush Pro also gives you up to 2x better compression too? %1$sTry it all free with a WPMU DEV membership today!%2$s',
'wp-smushit'
),
'<strong>',
'</strong>'
);
?>
</p>
<div class="sui-notice-buttons">
<a href="<?php echo esc_url( $upsell_url ); ?>" class="sui-button sui-button-purple" target="_blank">
<?php esc_html_e( 'Try Free for 30 Days', 'wp-smushit' ); ?>
</a>
</div>
</div>
</div>
|
isabisa/nccdi
|
wp-content/plugins/wp-smushit/app/views/meta-boxes/pro-features/meta-box.php
|
PHP
|
gpl-2.0
| 3,559
|
/* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
#include "base/utility.hpp"
#include <chrono>
#include <BoostTestTargetConfig.h>
using namespace icinga;
BOOST_AUTO_TEST_SUITE(base_utility)
BOOST_AUTO_TEST_CASE(parse_version)
{
BOOST_CHECK(Utility::ParseVersion("2.11.0-0.rc1.1") == "2.11.0");
BOOST_CHECK(Utility::ParseVersion("v2.10.5") == "2.10.5");
BOOST_CHECK(Utility::ParseVersion("r2.11.1") == "2.11.1");
BOOST_CHECK(Utility::ParseVersion("v2.11.0-rc1-58-g7c1f716da") == "2.11.0");
BOOST_CHECK(Utility::ParseVersion("v2.11butactually3.0") == "v2.11butactually3.0");
}
BOOST_AUTO_TEST_CASE(compare_version)
{
BOOST_CHECK(Utility::CompareVersion("2.10.5", Utility::ParseVersion("v2.10.4")) < 0);
BOOST_CHECK(Utility::CompareVersion("2.11.0", Utility::ParseVersion("2.11.0-0")) == 0);
BOOST_CHECK(Utility::CompareVersion("2.10.5", Utility::ParseVersion("2.11.0-0.rc1.1")) > 0);
}
BOOST_AUTO_TEST_CASE(comparepasswords_works)
{
BOOST_CHECK(Utility::ComparePasswords("", ""));
BOOST_CHECK(!Utility::ComparePasswords("x", ""));
BOOST_CHECK(!Utility::ComparePasswords("", "x"));
BOOST_CHECK(Utility::ComparePasswords("x", "x"));
BOOST_CHECK(!Utility::ComparePasswords("x", "y"));
BOOST_CHECK(Utility::ComparePasswords("abcd", "abcd"));
BOOST_CHECK(!Utility::ComparePasswords("abc", "abcd"));
BOOST_CHECK(!Utility::ComparePasswords("abcde", "abcd"));
}
BOOST_AUTO_TEST_CASE(comparepasswords_issafe)
{
using std::chrono::duration_cast;
using std::chrono::microseconds;
using std::chrono::steady_clock;
String a, b;
a.Append(200000001, 'a');
b.Append(200000002, 'b');
auto start1 (steady_clock::now());
Utility::ComparePasswords(a, a);
auto duration1 (steady_clock::now() - start1);
auto start2 (steady_clock::now());
Utility::ComparePasswords(a, b);
auto duration2 (steady_clock::now() - start2);
double diff = (double)duration_cast<microseconds>(duration1).count() / (double)duration_cast<microseconds>(duration2).count();
BOOST_WARN(0.9 <= diff && diff <= 1.1);
}
BOOST_AUTO_TEST_CASE(validateutf8)
{
BOOST_CHECK(Utility::ValidateUTF8("") == "");
BOOST_CHECK(Utility::ValidateUTF8("a") == "a");
BOOST_CHECK(Utility::ValidateUTF8("\xC3") == "\xEF\xBF\xBD");
BOOST_CHECK(Utility::ValidateUTF8("\xC3\xA4") == "\xC3\xA4");
}
BOOST_AUTO_TEST_SUITE_END()
|
bebehei/icinga2
|
test/base-utility.cpp
|
C++
|
gpl-2.0
| 2,303
|
@import url(framing.css);
@import url(pretty.css);
|
rydnr/queryj-rt
|
docs/slides/ui/themes/default/hook.css
|
CSS
|
gpl-2.0
| 50
|
CFILES = client.c socket.c
OFILES = client.o socket.o
LDFLAGS = -lcurses
ECHO = /bin/echo
MV = /bin/mv
TOUCH = touch
CC = gcc -Wall -pedantic
all : client
@${ECHO} AberMUD5 client is up to date.
client : ${OFILES}
${CC} ${LDFLAGS} ${OFILES}
@${TOUCH} client
@${MV} client client.old
@${MV} a.out client
clean:
rm -f *.o *~ client client.old
|
facet42/AberMUD
|
Original/AberClient/Makefile
|
Makefile
|
gpl-2.0
| 370
|
/*
This file is part of Warzone 2100.
Copyright (C) 1999-2004 Eidos Interactive
Copyright (C) 2005-2009 Warzone Resurrection Project
Warzone 2100 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.
Warzone 2100 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 Warzone 2100; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
* Loop.c
*
* The main game loop
*
*/
#include "lib/framework/frame.h"
#include "lib/framework/input.h"
#include "lib/framework/strres.h"
#include "lib/ivis_common/rendmode.h"
#include "lib/ivis_common/piestate.h" //ivis render code
#include "lib/ivis_common/piemode.h"
// FIXME Direct iVis implementation include!
#include "lib/ivis_common/rendmode.h" //ivis render code
#include "lib/ivis_opengl/screen.h"
#include "lib/gamelib/gtime.h"
#include "lib/gamelib/animobj.h"
#include "lib/script/script.h"
#include "lib/sound/audio.h"
#include "lib/sound/cdaudio.h"
#include "lib/sound/mixer.h"
#include "lib/netplay/netplay.h"
#include "loop.h"
#include "objects.h"
#include "display.h"
#include "map.h"
#include "hci.h"
#include "ingameop.h"
#include "miscimd.h"
#include "effects.h"
#include "radar.h"
#include "projectile.h"
#include "console.h"
#include "power.h"
#include "message.h"
#include "bucket3d.h"
#include "display3d.h"
#include "warzoneconfig.h"
#include "multiplay.h" //ajl
#include "scripttabs.h"
#include "levels.h"
#include "visibility.h"
#include "multimenu.h"
#include "intelmap.h"
#include "loadsave.h"
#include "game.h"
#include "multijoin.h"
#include "lighting.h"
#include "intimage.h"
#include "lib/framework/cursors.h"
#include "seqdisp.h"
#include "mission.h"
#include "warcam.h"
#include "lighting.h"
#include "mapgrid.h"
#include "edit3d.h"
#include "drive.h"
#include "fpath.h"
#include "scriptextern.h"
#include "cluster.h"
#include "cmddroid.h"
#include "keybind.h"
#include "wrappers.h"
#include "warzoneconfig.h"
#ifdef DEBUG
#include "objmem.h"
#endif
static void fireWaitingCallbacks(void);
/*
* Global variables
*/
unsigned int loopPieCount;
unsigned int loopTileCount;
unsigned int loopPolyCount;
unsigned int loopStateChanges;
/*
* local variables
*/
static BOOL paused=false;
static BOOL video=false;
//holds which pause is valid at any one time
typedef struct _pause_state
{
unsigned gameUpdatePause : 1;
unsigned audioPause : 1;
unsigned scriptPause : 1;
unsigned scrollPause : 1;
unsigned consolePause : 1;
unsigned editPause : 1;
} PAUSE_STATE;
static PAUSE_STATE pauseState;
static UDWORD numDroids[MAX_PLAYERS];
static UDWORD numMissionDroids[MAX_PLAYERS];
static UDWORD numTransporterDroids[MAX_PLAYERS];
static UDWORD numCommandDroids[MAX_PLAYERS];
static UDWORD numConstructorDroids[MAX_PLAYERS];
static SDWORD videoMode = 0;
LOOP_MISSION_STATE loopMissionState = LMS_NORMAL;
// this is set by scrStartMission to say what type of new level is to be started
SDWORD nextMissionType = LDS_NONE;//MISSION_NONE;
/* Force 3D display */
UDWORD mcTime;
/* The main game loop */
GAMECODE gameLoop(void)
{
DROID *psCurr, *psNext;
STRUCTURE *psCBuilding, *psNBuilding;
FEATURE *psCFeat, *psNFeat;
UDWORD i,widgval;
BOOL quitting=false;
INT_RETVAL intRetVal;
int clearMode = 0;
bool gameTicked = deltaGameTime != 0;
if (bMultiPlayer && !NetPlay.isHostAlive && NetPlay.bComms && !NetPlay.isHost)
{
intAddInGamePopup();
}
if (!war_GetFog())
{
PIELIGHT black;
// set the fog color to black (RGB)
// the fogbox will get this color
black.rgba = 0;
black.byte.a = 255;
pie_SetFogColour(black);
}
if(getDrawShadows())
{
clearMode |= CLEAR_SHADOW;
}
if (loopMissionState == LMS_SAVECONTINUE)
{
pie_SetFogStatus(false);
clearMode = CLEAR_BLACK;
}
pie_ScreenFlip(clearMode);//gameloopflip
HandleClosingWindows(); // Needs to be done outside the pause case.
audio_Update();
pie_ShowMouse(true);
if (!paused)
{
if (!scriptPaused() && !editPaused() && gameTicked)
{
/* Update the event system */
if (!bInTutorial)
{
eventProcessTriggers(gameTime/SCR_TICKRATE);
}
else
{
eventProcessTriggers(realTime/SCR_TICKRATE);
}
}
/* Run the in game interface and see if it grabbed any mouse clicks */
if (!rotActive && getWidgetsStatus() && dragBox3D.status != DRAG_DRAGGING && wallDrag.status != DRAG_DRAGGING)
{
intRetVal = intRunWidgets();
}
else
{
intRetVal = INT_NONE;
}
//don't process the object lists if paused or about to quit to the front end
if (!gameUpdatePaused() && intRetVal != INT_QUIT)
{
if( dragBox3D.status != DRAG_DRAGGING
&& wallDrag.status != DRAG_DRAGGING
&& ( intRetVal == INT_INTERCEPT
|| ( radarOnScreen
&& CoordInRadar(mouseX(), mouseY())
&& getHQExists(selectedPlayer) ) ) )
{
// Using software cursors (when on) for these menus due to a bug in SDL's SDL_ShowCursor()
pie_SetMouse(CURSOR_DEFAULT, war_GetColouredCursor());
intRetVal = INT_INTERCEPT;
}
#ifdef DEBUG
// check all flag positions for duplicate delivery points
checkFactoryFlags();
#endif
if (!editPaused() && gameTicked)
{
// Update abandoned structures
handleAbandonedStructures();
}
//handles callbacks for positioning of DP's
process3DBuilding();
// Update the base movement stuff
// FIXME This function will be redundant with logical updates.
moveUpdateBaseSpeed();
// Update the visibility change stuff
visUpdateLevel();
if (!editPaused() && gameTicked)
{
// Put all droids/structures/features into the grid.
gridReset();
// Check which objects are visible.
processVisibility();
//update the findpath system
fpathUpdate();
// update the cluster system
clusterUpdate();
// update the command droids
cmdDroidUpdate();
if(getDrivingStatus())
{
driveUpdate();
}
}
//ajl. get the incoming netgame messages and process them.
if (bMultiPlayer)
{
multiPlayerLoop();
}
if (!editPaused() && gameTicked)
{
fireWaitingCallbacks(); //Now is the good time to fire waiting callbacks (since interpreter is off now)
throttleEconomy();
for(i = 0; i < MAX_PLAYERS; i++)
{
//update the current power available for a player
updatePlayerPower(i);
//set the flag for each player
setHQExists(false, i);
setSatUplinkExists(false, i);
numCommandDroids[i] = 0;
numConstructorDroids[i] = 0;
numDroids[i]=0;
numTransporterDroids[i]=0;
for(psCurr = apsDroidLists[i]; psCurr; psCurr = psNext)
{
/* Copy the next pointer - not 100% sure if the droid could get destroyed
but this covers us anyway */
psNext = psCurr->psNext;
droidUpdate(psCurr);
// update the droid counts
numDroids[i]++;
switch (psCurr->droidType)
{
case DROID_COMMAND:
numCommandDroids[i] += 1;
break;
case DROID_CONSTRUCT:
case DROID_CYBORG_CONSTRUCT:
numConstructorDroids[i] += 1;
break;
case DROID_TRANSPORTER:
if( (psCurr->psGroup != NULL) )
{
DROID *psDroid = NULL;
numTransporterDroids[i] += psCurr->psGroup->refCount-1;
// and count the units inside it...
for (psDroid = psCurr->psGroup->psList; psDroid != NULL && psDroid != psCurr; psDroid = psDroid->psGrpNext)
{
if (psDroid->droidType == DROID_CYBORG_CONSTRUCT || psDroid->droidType == DROID_CONSTRUCT)
{
numConstructorDroids[i] += 1;
}
if (psDroid->droidType == DROID_COMMAND)
{
numCommandDroids[i] += 1;
}
}
}
break;
default:
break;
}
}
numMissionDroids[i]=0;
for(psCurr = mission.apsDroidLists[i]; psCurr; psCurr = psNext)
{
/* Copy the next pointer - not 100% sure if the droid could
get destroyed but this covers us anyway */
psNext = psCurr->psNext;
missionDroidUpdate(psCurr);
numMissionDroids[i]++;
switch (psCurr->droidType)
{
case DROID_COMMAND:
numCommandDroids[i] += 1;
break;
case DROID_CONSTRUCT:
case DROID_CYBORG_CONSTRUCT:
numConstructorDroids[i] += 1;
break;
case DROID_TRANSPORTER:
if( (psCurr->psGroup != NULL) )
{
numTransporterDroids[i] += psCurr->psGroup->refCount-1;
}
break;
default:
break;
}
}
for(psCurr = apsLimboDroids[i]; psCurr; psCurr = psNext)
{
/* Copy the next pointer - not 100% sure if the droid could
get destroyed but this covers us anyway */
psNext = psCurr->psNext;
// count the type of units
switch (psCurr->droidType)
{
case DROID_COMMAND:
numCommandDroids[i] += 1;
break;
case DROID_CONSTRUCT:
case DROID_CYBORG_CONSTRUCT:
numConstructorDroids[i] += 1;
break;
default:
break;
}
}
// FIXME: These for-loops are code duplicationo
/*set this up AFTER droidUpdate so that if trying to building a
new one, we know whether one exists already*/
setLasSatExists(false, i);
for (psCBuilding = apsStructLists[i]; psCBuilding; psCBuilding = psNBuilding)
{
/* Copy the next pointer - not 100% sure if the structure could get destroyed but this covers us anyway */
psNBuilding = psCBuilding->psNext;
structureUpdate(psCBuilding, false);
//set animation flag
if (psCBuilding->pStructureType->type == REF_HQ &&
psCBuilding->status == SS_BUILT)
{
setHQExists(true, i);
}
if (psCBuilding->pStructureType->type == REF_SAT_UPLINK &&
psCBuilding->status == SS_BUILT)
{
setSatUplinkExists(true, i);
}
//don't wait for the Las Sat to be built - can't build another if one is partially built
if (asWeaponStats[psCBuilding->asWeaps[0].nStat].
weaponSubClass == WSC_LAS_SAT)
{
setLasSatExists(true, i);
}
}
for (psCBuilding = mission.apsStructLists[i]; psCBuilding;
psCBuilding = psNBuilding)
{
/* Copy the next pointer - not 100% sure if the structure could get destroyed but this covers us anyway. It shouldn't do since its not even on the map!*/
psNBuilding = psCBuilding->psNext;
structureUpdate(psCBuilding, true); // update for mission
if (psCBuilding->pStructureType->type == REF_HQ &&
psCBuilding->status == SS_BUILT)
{
setHQExists(true, i);
}
if (psCBuilding->pStructureType->type == REF_SAT_UPLINK &&
psCBuilding->status == SS_BUILT)
{
setSatUplinkExists(true, i);
}
//don't wait for the Las Sat to be built - can't build another if one is partially built
if (asWeaponStats[psCBuilding->asWeaps[0].nStat].
weaponSubClass == WSC_LAS_SAT)
{
setLasSatExists(true, i);
}
}
}
missionTimerUpdate();
proj_UpdateAll();
for(psCFeat = apsFeatureLists[0]; psCFeat; psCFeat = psNFeat)
{
psNFeat = psCFeat->psNext;
featureUpdate(psCFeat);
}
}
else // if editPaused() or not gameTicked - make sure visual effects are updated
{
for (i = 0; i < MAX_PLAYERS; i++)
{
for(psCurr = apsDroidLists[i]; psCurr; psCurr = psNext)
{
/* Copy the next pointer - not 100% sure if the droid could get destroyed
but this covers us anyway */
psNext = psCurr->psNext;
processVisibilityLevel((BASE_OBJECT *)psCurr);
calcDroidIllumination(psCurr);
}
for (psCBuilding = apsStructLists[i]; psCBuilding; psCBuilding = psNBuilding)
{
/* Copy the next pointer - not 100% sure if the structure could get destroyed but this covers us anyway */
psNBuilding = psCBuilding->psNext;
processVisibilityLevel((BASE_OBJECT *)psCBuilding);
}
}
}
/* update animations */
animObj_Update();
if (gameTicked)
{
objmemUpdate();
}
}
if (!consolePaused())
{
/* Process all the console messages */
updateConsoleMessages();
}
if (!scrollPaused() && !getWarCamStatus() && dragBox3D.status != DRAG_DRAGGING && intMode != INT_INGAMEOP )
{
scroll();
}
}
else // paused
{
// Using software cursors (when on) for these menus due to a bug in SDL's SDL_ShowCursor()
pie_SetMouse(CURSOR_DEFAULT, war_GetColouredCursor());
intRetVal = INT_NONE;
if(dragBox3D.status != DRAG_DRAGGING)
{
scroll();
}
if(InGameOpUp || isInGamePopupUp) // ingame options menu up, run it!
{
widgval = widgRunScreen(psWScreen);
intProcessInGameOptions(widgval);
if(widgval == INTINGAMEOP_QUIT_CONFIRM || widgval == INTINGAMEOP_POPUP_QUIT)
{
if(gamePaused())
{
kf_TogglePauseMode();
}
intRetVal = INT_QUIT;
}
}
if(bLoadSaveUp && runLoadSave(true) && strlen(sRequestResult))
{
debug( LOG_NEVER, "Returned %s", sRequestResult );
if(bRequestLoad)
{
loopMissionState = LMS_LOADGAME;
NET_InitPlayers(); // otherwise alliances were not cleared
sstrcpy(saveGameName, sRequestResult);
}
else
{
char msgbuffer[256]= {'\0'};
if (saveInMissionRes())
{
if (saveGame(sRequestResult, GTYPE_SAVE_START))
{
sstrcpy(msgbuffer, _("GAME SAVED: "));
sstrcat(msgbuffer, sRequestResult);
addConsoleMessage( msgbuffer, LEFT_JUSTIFY, NOTIFY_MESSAGE);
}
else
{
ASSERT( false,"Mission Results: saveGame Failed" );
sstrcpy(msgbuffer, _("Could not save game!"));
addConsoleMessage( msgbuffer, LEFT_JUSTIFY, NOTIFY_MESSAGE);
deleteSaveGame(sRequestResult);
}
}
else if (bMultiPlayer || saveMidMission())
{
if (saveGame(sRequestResult, GTYPE_SAVE_MIDMISSION))//mid mission from [esc] menu
{
sstrcpy(msgbuffer, _("GAME SAVED: "));
sstrcat(msgbuffer, sRequestResult);
addConsoleMessage( msgbuffer, LEFT_JUSTIFY, NOTIFY_MESSAGE);
}
else
{
ASSERT(!"saveGame(sRequestResult, GTYPE_SAVE_MIDMISSION) failed", "Mid Mission: saveGame Failed" );
sstrcpy(msgbuffer, _("Could not save game!"));
addConsoleMessage( msgbuffer, LEFT_JUSTIFY, NOTIFY_MESSAGE);
deleteSaveGame(sRequestResult);
}
}
else
{
ASSERT( false, "Attempt to save game with incorrect load/save mode" );
}
}
}
}
/* Check for quit */
if (intRetVal == INT_QUIT)
{
if (!loop_GetVideoStatus())
{
//quitting from the game to the front end
//so get a new backdrop
quitting = true;
pie_LoadBackDrop(SCREEN_RANDOMBDROP);
}
}
if (!loop_GetVideoStatus() && !quitting)
{
if (!gameUpdatePaused())
{
if (dragBox3D.status != DRAG_DRAGGING
&& wallDrag.status != DRAG_DRAGGING)
{
ProcessRadarInput();
}
processInput();
//no key clicks or in Intelligence Screen
if (intRetVal == INT_NONE && !InGameOpUp && !isInGamePopupUp)
{
processMouseClickInput();
}
displayWorld();
}
/* Display the in game interface */
pie_SetDepthBufferStatus(DEPTH_CMP_ALWAYS_WRT_ON);
pie_SetFogStatus(false);
if(bMultiPlayer && bDisplayMultiJoiningStatus)
{
intDisplayMultiJoiningStatus(bDisplayMultiJoiningStatus);
setWidgetsStatus(false);
}
if(getWidgetsStatus())
{
intDisplayWidgets();
}
pie_SetDepthBufferStatus(DEPTH_CMP_LEQ_WRT_ON);
pie_SetFogStatus(true);
pie_DrawMouse(mouseX(), mouseY());
}
pie_GetResetCounts(&loopPieCount, &loopTileCount, &loopPolyCount, &loopStateChanges);
if (fogStatus & FOG_BACKGROUND)
{
if (loopMissionState == LMS_SAVECONTINUE)
{
pie_SetFogStatus(false);
clearMode = CLEAR_BLACK;
}
}
else
{
clearMode = CLEAR_BLACK;//force to black 3DFX
}
if (!quitting)
{
/* Check for toggling display mode */
if ((keyDown(KEY_LALT) || keyDown(KEY_RALT)) && keyPressed(KEY_RETURN))
{
screenToggleMode();
}
}
// deal with the mission state
switch (loopMissionState)
{
case LMS_CLEAROBJECTS:
missionDestroyObjects();
setScriptPause(true);
loopMissionState = LMS_SETUPMISSION;
break;
case LMS_NORMAL:
// default
break;
case LMS_SETUPMISSION:
setScriptPause(false);
if (!setUpMission(nextMissionType))
{
return GAMECODE_QUITGAME;
}
break;
case LMS_SAVECONTINUE:
// just wait for this to be changed when the new mission starts
clearMode = CLEAR_BLACK;
break;
case LMS_NEWLEVEL:
//nextMissionType = MISSION_NONE;
nextMissionType = LDS_NONE;
return GAMECODE_NEWLEVEL;
break;
case LMS_LOADGAME:
return GAMECODE_LOADGAME;
break;
default:
ASSERT( false, "unknown loopMissionState" );
break;
}
if (quitting)
{
pie_SetFogStatus(false);
pie_ScreenFlip(CLEAR_BLACK);//gameloopflip
/* Check for toggling display mode */
if ((keyDown(KEY_LALT) || keyDown(KEY_RALT)) && keyPressed(KEY_RETURN))
{
screenToggleMode();
}
return GAMECODE_QUITGAME;
}
else if (loop_GetVideoStatus())
{
audio_StopAll();
return GAMECODE_PLAYVIDEO;
}
return GAMECODE_CONTINUE;
}
/* The video playback loop */
void videoLoop(void)
{
bool videoFinished;
ASSERT( videoMode == 1, "videoMode out of sync" );
// display a frame of the FMV
videoFinished = !seq_UpdateFullScreenVideo(NULL);
pie_ScreenFlip(CLEAR_BLACK);
// should we stop playing?
if (videoFinished || keyPressed(KEY_ESC) || mouseReleased(MOUSE_LMB))
{
seq_StopFullScreenVideo();
//set the next video off - if any
if (videoFinished && seq_AnySeqLeft())
{
seq_StartNextFullScreenVideo();
}
else
{
// remove the intelligence screen if necessary
if (messageIsImmediate())
{
intResetScreen(true);
setMessageImmediate(false);
}
//don't do the callback if we're playing the win/lose video
if (!getScriptWinLoseVideo())
{
eventFireCallbackTrigger((TRIGGER_TYPE)CALL_VIDEO_QUIT);
}
else
{
displayGameOver(getScriptWinLoseVideo() == PLAY_WIN);
}
}
}
}
void loop_SetVideoPlaybackMode(void)
{
videoMode += 1;
paused = true;
video = true;
gameTimeStop();
pie_SetFogStatus(false);
audio_StopAll();
pie_ShowMouse(false);
screen_StopBackDrop();
pie_ScreenFlip(CLEAR_BLACK);
}
void loop_ClearVideoPlaybackMode(void)
{
videoMode -=1;
paused = false;
video = false;
gameTimeStart();
pie_SetFogStatus(true);
cdAudio_Resume();
pie_ShowMouse(true);
ASSERT( videoMode == 0, "loop_ClearVideoPlaybackMode: out of sync." );
}
SDWORD loop_GetVideoMode(void)
{
return videoMode;
}
BOOL loop_GetVideoStatus(void)
{
return video;
}
BOOL editPaused(void)
{
return pauseState.editPause;
}
void setEditPause(bool state)
{
pauseState.editPause = state;
}
BOOL gamePaused( void )
{
return paused;
}
void setGamePauseStatus( BOOL val )
{
paused = val;
}
BOOL gameUpdatePaused(void)
{
return pauseState.gameUpdatePause;
}
BOOL audioPaused(void)
{
return pauseState.audioPause;
}
BOOL scriptPaused(void)
{
return pauseState.scriptPause;
}
BOOL scrollPaused(void)
{
return pauseState.scrollPause;
}
BOOL consolePaused(void)
{
return pauseState.consolePause;
}
void setGameUpdatePause(BOOL state)
{
pauseState.gameUpdatePause = state;
}
void setAudioPause(BOOL state)
{
pauseState.audioPause = state;
}
void setScriptPause(BOOL state)
{
pauseState.scriptPause = state;
}
void setScrollPause(BOOL state)
{
pauseState.scrollPause = state;
}
void setConsolePause(BOOL state)
{
pauseState.consolePause = state;
}
//set all the pause states to the state value
void setAllPauseStates(BOOL state)
{
setGameUpdatePause(state);
setAudioPause(state);
setScriptPause(state);
setScrollPause(state);
setConsolePause(state);
}
UDWORD getNumDroids(UDWORD player)
{
return(numDroids[player]);
}
UDWORD getNumTransporterDroids(UDWORD player)
{
return(numTransporterDroids[player]);
}
UDWORD getNumMissionDroids(UDWORD player)
{
return(numMissionDroids[player]);
}
UDWORD getNumCommandDroids(UDWORD player)
{
return numCommandDroids[player];
}
UDWORD getNumConstructorDroids(UDWORD player)
{
return numConstructorDroids[player];
}
// increase the droid counts - used by update factory to keep the counts in sync
void incNumDroids(UDWORD player)
{
numDroids[player] += 1;
}
void incNumCommandDroids(UDWORD player)
{
numCommandDroids[player] += 1;
}
void incNumConstructorDroids(UDWORD player)
{
numConstructorDroids[player] += 1;
}
/* Fire waiting beacon messages which we couldn't run before */
static void fireWaitingCallbacks(void)
{
BOOL bOK = true;
while(!isMsgStackEmpty() && bOK)
{
bOK = msgStackFireTop();
if(!bOK){
ASSERT(false, "fireWaitingCallbacks: msgStackFireTop() failed (stack count: %d)", msgStackGetCount());
}
}
}
|
venkatarajasekhar/wzgraphicsmods
|
src/loop.c
|
C
|
gpl-2.0
| 21,078
|
/*******************************************************************************
Intel(R) 82576 Virtual Function Linux driver
Copyright(c) 2009 - 2012 Intel Corporation.
This program is free software; you can redistribute it and/or modify it
under the terms and conditions of the GNU General Public License,
version 2, as published by the Free Software Foundation.
This program is distributed in the hope it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
this program; if not, see <http://www.gnu.org/licenses/>.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
Contact Information:
e1000-devel Mailing List <e1000-devel@lists.sourceforge.net>
Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*******************************************************************************/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/vmalloc.h>
#include <linux/pagemap.h>
#include <linux/delay.h>
#include <linux/netdevice.h>
#include <linux/tcp.h>
#include <linux/ipv6.h>
#include <linux/slab.h>
#include <net/checksum.h>
#include <net/ip6_checksum.h>
#include <linux/mii.h>
#include <linux/ethtool.h>
#include <linux/if_vlan.h>
#include <linux/prefetch.h>
#include "igbvf.h"
#define DRV_VERSION "2.0.2-k"
char igbvf_driver_name[] = "igbvf";
const char igbvf_driver_version[] = DRV_VERSION;
static const char igbvf_driver_string[] =
"Intel(R) Gigabit Virtual Function Network Driver";
static const char igbvf_copyright[] =
"Copyright (c) 2009 - 2012 Intel Corporation.";
#define DEFAULT_MSG_ENABLE (NETIF_MSG_DRV|NETIF_MSG_PROBE|NETIF_MSG_LINK)
static int debug = -1;
module_param(debug, int, 0);
MODULE_PARM_DESC(debug, "Debug level (0=none,...,16=all)");
static int igbvf_poll(struct napi_struct *napi, int budget);
static void igbvf_reset(struct igbvf_adapter *);
static void igbvf_set_interrupt_capability(struct igbvf_adapter *);
static void igbvf_reset_interrupt_capability(struct igbvf_adapter *);
static struct igbvf_info igbvf_vf_info = {
.mac = e1000_vfadapt,
.flags = 0,
.pba = 10,
.init_ops = e1000_init_function_pointers_vf,
};
static struct igbvf_info igbvf_i350_vf_info = {
.mac = e1000_vfadapt_i350,
.flags = 0,
.pba = 10,
.init_ops = e1000_init_function_pointers_vf,
};
static const struct igbvf_info *igbvf_info_tbl[] = {
[board_vf] = &igbvf_vf_info,
[board_i350_vf] = &igbvf_i350_vf_info,
};
/**
* igbvf_desc_unused - calculate if we have unused descriptors
* @rx_ring: address of receive ring structure
**/
static int igbvf_desc_unused(struct igbvf_ring *ring)
{
if (ring->next_to_clean > ring->next_to_use)
return ring->next_to_clean - ring->next_to_use - 1;
return ring->count + ring->next_to_clean - ring->next_to_use - 1;
}
/**
* igbvf_receive_skb - helper function to handle Rx indications
* @adapter: board private structure
* @status: descriptor status field as written by hardware
* @vlan: descriptor vlan field as written by hardware (no le/be conversion)
* @skb: pointer to sk_buff to be indicated to stack
**/
static void igbvf_receive_skb(struct igbvf_adapter *adapter,
struct net_device *netdev,
struct sk_buff *skb,
u32 status, u16 vlan)
{
u16 vid;
if (status & E1000_RXD_STAT_VP) {
if ((adapter->flags & IGBVF_FLAG_RX_LB_VLAN_BSWAP) &&
(status & E1000_RXDEXT_STATERR_LB))
vid = be16_to_cpu(vlan) & E1000_RXD_SPC_VLAN_MASK;
else
vid = le16_to_cpu(vlan) & E1000_RXD_SPC_VLAN_MASK;
if (test_bit(vid, adapter->active_vlans))
__vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), vid);
}
napi_gro_receive(&adapter->rx_ring->napi, skb);
}
static inline void igbvf_rx_checksum_adv(struct igbvf_adapter *adapter,
u32 status_err, struct sk_buff *skb)
{
skb_checksum_none_assert(skb);
/* Ignore Checksum bit is set or checksum is disabled through ethtool */
if ((status_err & E1000_RXD_STAT_IXSM) ||
(adapter->flags & IGBVF_FLAG_RX_CSUM_DISABLED))
return;
/* TCP/UDP checksum error bit is set */
if (status_err &
(E1000_RXDEXT_STATERR_TCPE | E1000_RXDEXT_STATERR_IPE)) {
/* let the stack verify checksum errors */
adapter->hw_csum_err++;
return;
}
/* It must be a TCP or UDP packet with a valid checksum */
if (status_err & (E1000_RXD_STAT_TCPCS | E1000_RXD_STAT_UDPCS))
skb->ip_summed = CHECKSUM_UNNECESSARY;
adapter->hw_csum_good++;
}
/**
* igbvf_alloc_rx_buffers - Replace used receive buffers; packet split
* @rx_ring: address of ring structure to repopulate
* @cleaned_count: number of buffers to repopulate
**/
static void igbvf_alloc_rx_buffers(struct igbvf_ring *rx_ring,
int cleaned_count)
{
struct igbvf_adapter *adapter = rx_ring->adapter;
struct net_device *netdev = adapter->netdev;
struct pci_dev *pdev = adapter->pdev;
union e1000_adv_rx_desc *rx_desc;
struct igbvf_buffer *buffer_info;
struct sk_buff *skb;
unsigned int i;
int bufsz;
i = rx_ring->next_to_use;
buffer_info = &rx_ring->buffer_info[i];
if (adapter->rx_ps_hdr_size)
bufsz = adapter->rx_ps_hdr_size;
else
bufsz = adapter->rx_buffer_len;
while (cleaned_count--) {
rx_desc = IGBVF_RX_DESC_ADV(*rx_ring, i);
if (adapter->rx_ps_hdr_size && !buffer_info->page_dma) {
if (!buffer_info->page) {
buffer_info->page = alloc_page(GFP_ATOMIC);
if (!buffer_info->page) {
adapter->alloc_rx_buff_failed++;
goto no_buffers;
}
buffer_info->page_offset = 0;
} else {
buffer_info->page_offset ^= PAGE_SIZE / 2;
}
buffer_info->page_dma =
dma_map_page(&pdev->dev, buffer_info->page,
buffer_info->page_offset,
PAGE_SIZE / 2,
DMA_FROM_DEVICE);
if (dma_mapping_error(&pdev->dev,
buffer_info->page_dma)) {
__free_page(buffer_info->page);
buffer_info->page = NULL;
dev_err(&pdev->dev, "RX DMA map failed\n");
break;
}
}
if (!buffer_info->skb) {
skb = netdev_alloc_skb_ip_align(netdev, bufsz);
if (!skb) {
adapter->alloc_rx_buff_failed++;
goto no_buffers;
}
buffer_info->skb = skb;
buffer_info->dma = dma_map_single(&pdev->dev, skb->data,
bufsz,
DMA_FROM_DEVICE);
if (dma_mapping_error(&pdev->dev, buffer_info->dma)) {
dev_kfree_skb(buffer_info->skb);
buffer_info->skb = NULL;
dev_err(&pdev->dev, "RX DMA map failed\n");
goto no_buffers;
}
}
/* Refresh the desc even if buffer_addrs didn't change because
* each write-back erases this info.
*/
if (adapter->rx_ps_hdr_size) {
rx_desc->read.pkt_addr =
cpu_to_le64(buffer_info->page_dma);
rx_desc->read.hdr_addr = cpu_to_le64(buffer_info->dma);
} else {
rx_desc->read.pkt_addr = cpu_to_le64(buffer_info->dma);
rx_desc->read.hdr_addr = 0;
}
i++;
if (i == rx_ring->count)
i = 0;
buffer_info = &rx_ring->buffer_info[i];
}
no_buffers:
if (rx_ring->next_to_use != i) {
rx_ring->next_to_use = i;
if (i == 0)
i = (rx_ring->count - 1);
else
i--;
/* Force memory writes to complete before letting h/w
* know there are new descriptors to fetch. (Only
* applicable for weak-ordered memory model archs,
* such as IA-64).
*/
wmb();
writel(i, adapter->hw.hw_addr + rx_ring->tail);
}
}
/**
* igbvf_clean_rx_irq - Send received data up the network stack; legacy
* @adapter: board private structure
*
* the return value indicates whether actual cleaning was done, there
* is no guarantee that everything was cleaned
**/
static bool igbvf_clean_rx_irq(struct igbvf_adapter *adapter,
int *work_done, int work_to_do)
{
struct igbvf_ring *rx_ring = adapter->rx_ring;
struct net_device *netdev = adapter->netdev;
struct pci_dev *pdev = adapter->pdev;
union e1000_adv_rx_desc *rx_desc, *next_rxd;
struct igbvf_buffer *buffer_info, *next_buffer;
struct sk_buff *skb;
bool cleaned = false;
int cleaned_count = 0;
unsigned int total_bytes = 0, total_packets = 0;
unsigned int i;
u32 length, hlen, staterr;
i = rx_ring->next_to_clean;
rx_desc = IGBVF_RX_DESC_ADV(*rx_ring, i);
staterr = le32_to_cpu(rx_desc->wb.upper.status_error);
while (staterr & E1000_RXD_STAT_DD) {
if (*work_done >= work_to_do)
break;
(*work_done)++;
rmb(); /* read descriptor and rx_buffer_info after status DD */
buffer_info = &rx_ring->buffer_info[i];
/* HW will not DMA in data larger than the given buffer, even
* if it parses the (NFS, of course) header to be larger. In
* that case, it fills the header buffer and spills the rest
* into the page.
*/
hlen = (le16_to_cpu(rx_desc->wb.lower.lo_dword.hs_rss.hdr_info)
& E1000_RXDADV_HDRBUFLEN_MASK) >>
E1000_RXDADV_HDRBUFLEN_SHIFT;
if (hlen > adapter->rx_ps_hdr_size)
hlen = adapter->rx_ps_hdr_size;
length = le16_to_cpu(rx_desc->wb.upper.length);
cleaned = true;
cleaned_count++;
skb = buffer_info->skb;
prefetch(skb->data - NET_IP_ALIGN);
buffer_info->skb = NULL;
if (!adapter->rx_ps_hdr_size) {
dma_unmap_single(&pdev->dev, buffer_info->dma,
adapter->rx_buffer_len,
DMA_FROM_DEVICE);
buffer_info->dma = 0;
skb_put(skb, length);
goto send_up;
}
if (!skb_shinfo(skb)->nr_frags) {
dma_unmap_single(&pdev->dev, buffer_info->dma,
adapter->rx_ps_hdr_size,
DMA_FROM_DEVICE);
skb_put(skb, hlen);
}
if (length) {
dma_unmap_page(&pdev->dev, buffer_info->page_dma,
PAGE_SIZE / 2,
DMA_FROM_DEVICE);
buffer_info->page_dma = 0;
skb_fill_page_desc(skb, skb_shinfo(skb)->nr_frags,
buffer_info->page,
buffer_info->page_offset,
length);
if ((adapter->rx_buffer_len > (PAGE_SIZE / 2)) ||
(page_count(buffer_info->page) != 1))
buffer_info->page = NULL;
else
get_page(buffer_info->page);
skb->len += length;
skb->data_len += length;
skb->truesize += PAGE_SIZE / 2;
}
send_up:
i++;
if (i == rx_ring->count)
i = 0;
next_rxd = IGBVF_RX_DESC_ADV(*rx_ring, i);
prefetch(next_rxd);
next_buffer = &rx_ring->buffer_info[i];
if (!(staterr & E1000_RXD_STAT_EOP)) {
buffer_info->skb = next_buffer->skb;
buffer_info->dma = next_buffer->dma;
next_buffer->skb = skb;
next_buffer->dma = 0;
goto next_desc;
}
if (staterr & E1000_RXDEXT_ERR_FRAME_ERR_MASK) {
dev_kfree_skb_irq(skb);
goto next_desc;
}
total_bytes += skb->len;
total_packets++;
igbvf_rx_checksum_adv(adapter, staterr, skb);
skb->protocol = eth_type_trans(skb, netdev);
igbvf_receive_skb(adapter, netdev, skb, staterr,
rx_desc->wb.upper.vlan);
next_desc:
rx_desc->wb.upper.status_error = 0;
/* return some buffers to hardware, one at a time is too slow */
if (cleaned_count >= IGBVF_RX_BUFFER_WRITE) {
igbvf_alloc_rx_buffers(rx_ring, cleaned_count);
cleaned_count = 0;
}
/* use prefetched values */
rx_desc = next_rxd;
buffer_info = next_buffer;
staterr = le32_to_cpu(rx_desc->wb.upper.status_error);
}
rx_ring->next_to_clean = i;
cleaned_count = igbvf_desc_unused(rx_ring);
if (cleaned_count)
igbvf_alloc_rx_buffers(rx_ring, cleaned_count);
adapter->total_rx_packets += total_packets;
adapter->total_rx_bytes += total_bytes;
adapter->net_stats.rx_bytes += total_bytes;
adapter->net_stats.rx_packets += total_packets;
return cleaned;
}
static void igbvf_put_txbuf(struct igbvf_adapter *adapter,
struct igbvf_buffer *buffer_info)
{
if (buffer_info->dma) {
if (buffer_info->mapped_as_page)
dma_unmap_page(&adapter->pdev->dev,
buffer_info->dma,
buffer_info->length,
DMA_TO_DEVICE);
else
dma_unmap_single(&adapter->pdev->dev,
buffer_info->dma,
buffer_info->length,
DMA_TO_DEVICE);
buffer_info->dma = 0;
}
if (buffer_info->skb) {
dev_kfree_skb_any(buffer_info->skb);
buffer_info->skb = NULL;
}
buffer_info->time_stamp = 0;
}
/**
* igbvf_setup_tx_resources - allocate Tx resources (Descriptors)
* @adapter: board private structure
*
* Return 0 on success, negative on failure
**/
int igbvf_setup_tx_resources(struct igbvf_adapter *adapter,
struct igbvf_ring *tx_ring)
{
struct pci_dev *pdev = adapter->pdev;
int size;
size = sizeof(struct igbvf_buffer) * tx_ring->count;
tx_ring->buffer_info = vzalloc(size);
if (!tx_ring->buffer_info)
goto err;
/* round up to nearest 4K */
tx_ring->size = tx_ring->count * sizeof(union e1000_adv_tx_desc);
tx_ring->size = ALIGN(tx_ring->size, 4096);
tx_ring->desc = dma_alloc_coherent(&pdev->dev, tx_ring->size,
&tx_ring->dma, GFP_KERNEL);
if (!tx_ring->desc)
goto err;
tx_ring->adapter = adapter;
tx_ring->next_to_use = 0;
tx_ring->next_to_clean = 0;
return 0;
err:
vfree(tx_ring->buffer_info);
dev_err(&adapter->pdev->dev,
"Unable to allocate memory for the transmit descriptor ring\n");
return -ENOMEM;
}
/**
* igbvf_setup_rx_resources - allocate Rx resources (Descriptors)
* @adapter: board private structure
*
* Returns 0 on success, negative on failure
**/
int igbvf_setup_rx_resources(struct igbvf_adapter *adapter,
struct igbvf_ring *rx_ring)
{
struct pci_dev *pdev = adapter->pdev;
int size, desc_len;
size = sizeof(struct igbvf_buffer) * rx_ring->count;
rx_ring->buffer_info = vzalloc(size);
if (!rx_ring->buffer_info)
goto err;
desc_len = sizeof(union e1000_adv_rx_desc);
/* Round up to nearest 4K */
rx_ring->size = rx_ring->count * desc_len;
rx_ring->size = ALIGN(rx_ring->size, 4096);
rx_ring->desc = dma_alloc_coherent(&pdev->dev, rx_ring->size,
&rx_ring->dma, GFP_KERNEL);
if (!rx_ring->desc)
goto err;
rx_ring->next_to_clean = 0;
rx_ring->next_to_use = 0;
rx_ring->adapter = adapter;
return 0;
err:
vfree(rx_ring->buffer_info);
rx_ring->buffer_info = NULL;
dev_err(&adapter->pdev->dev,
"Unable to allocate memory for the receive descriptor ring\n");
return -ENOMEM;
}
/**
* igbvf_clean_tx_ring - Free Tx Buffers
* @tx_ring: ring to be cleaned
**/
static void igbvf_clean_tx_ring(struct igbvf_ring *tx_ring)
{
struct igbvf_adapter *adapter = tx_ring->adapter;
struct igbvf_buffer *buffer_info;
unsigned long size;
unsigned int i;
if (!tx_ring->buffer_info)
return;
/* Free all the Tx ring sk_buffs */
for (i = 0; i < tx_ring->count; i++) {
buffer_info = &tx_ring->buffer_info[i];
igbvf_put_txbuf(adapter, buffer_info);
}
size = sizeof(struct igbvf_buffer) * tx_ring->count;
memset(tx_ring->buffer_info, 0, size);
/* Zero out the descriptor ring */
memset(tx_ring->desc, 0, tx_ring->size);
tx_ring->next_to_use = 0;
tx_ring->next_to_clean = 0;
writel(0, adapter->hw.hw_addr + tx_ring->head);
writel(0, adapter->hw.hw_addr + tx_ring->tail);
}
/**
* igbvf_free_tx_resources - Free Tx Resources per Queue
* @tx_ring: ring to free resources from
*
* Free all transmit software resources
**/
void igbvf_free_tx_resources(struct igbvf_ring *tx_ring)
{
struct pci_dev *pdev = tx_ring->adapter->pdev;
igbvf_clean_tx_ring(tx_ring);
vfree(tx_ring->buffer_info);
tx_ring->buffer_info = NULL;
dma_free_coherent(&pdev->dev, tx_ring->size, tx_ring->desc,
tx_ring->dma);
tx_ring->desc = NULL;
}
/**
* igbvf_clean_rx_ring - Free Rx Buffers per Queue
* @adapter: board private structure
**/
static void igbvf_clean_rx_ring(struct igbvf_ring *rx_ring)
{
struct igbvf_adapter *adapter = rx_ring->adapter;
struct igbvf_buffer *buffer_info;
struct pci_dev *pdev = adapter->pdev;
unsigned long size;
unsigned int i;
if (!rx_ring->buffer_info)
return;
/* Free all the Rx ring sk_buffs */
for (i = 0; i < rx_ring->count; i++) {
buffer_info = &rx_ring->buffer_info[i];
if (buffer_info->dma) {
if (adapter->rx_ps_hdr_size) {
dma_unmap_single(&pdev->dev, buffer_info->dma,
adapter->rx_ps_hdr_size,
DMA_FROM_DEVICE);
} else {
dma_unmap_single(&pdev->dev, buffer_info->dma,
adapter->rx_buffer_len,
DMA_FROM_DEVICE);
}
buffer_info->dma = 0;
}
if (buffer_info->skb) {
dev_kfree_skb(buffer_info->skb);
buffer_info->skb = NULL;
}
if (buffer_info->page) {
if (buffer_info->page_dma)
dma_unmap_page(&pdev->dev,
buffer_info->page_dma,
PAGE_SIZE / 2,
DMA_FROM_DEVICE);
put_page(buffer_info->page);
buffer_info->page = NULL;
buffer_info->page_dma = 0;
buffer_info->page_offset = 0;
}
}
size = sizeof(struct igbvf_buffer) * rx_ring->count;
memset(rx_ring->buffer_info, 0, size);
/* Zero out the descriptor ring */
memset(rx_ring->desc, 0, rx_ring->size);
rx_ring->next_to_clean = 0;
rx_ring->next_to_use = 0;
writel(0, adapter->hw.hw_addr + rx_ring->head);
writel(0, adapter->hw.hw_addr + rx_ring->tail);
}
/**
* igbvf_free_rx_resources - Free Rx Resources
* @rx_ring: ring to clean the resources from
*
* Free all receive software resources
**/
void igbvf_free_rx_resources(struct igbvf_ring *rx_ring)
{
struct pci_dev *pdev = rx_ring->adapter->pdev;
igbvf_clean_rx_ring(rx_ring);
vfree(rx_ring->buffer_info);
rx_ring->buffer_info = NULL;
dma_free_coherent(&pdev->dev, rx_ring->size, rx_ring->desc,
rx_ring->dma);
rx_ring->desc = NULL;
}
/**
* igbvf_update_itr - update the dynamic ITR value based on statistics
* @adapter: pointer to adapter
* @itr_setting: current adapter->itr
* @packets: the number of packets during this measurement interval
* @bytes: the number of bytes during this measurement interval
*
* Stores a new ITR value based on packets and byte counts during the last
* interrupt. The advantage of per interrupt computation is faster updates
* and more accurate ITR for the current traffic pattern. Constants in this
* function were computed based on theoretical maximum wire speed and thresholds
* were set based on testing data as well as attempting to minimize response
* time while increasing bulk throughput.
**/
static enum latency_range igbvf_update_itr(struct igbvf_adapter *adapter,
enum latency_range itr_setting,
int packets, int bytes)
{
enum latency_range retval = itr_setting;
if (packets == 0)
goto update_itr_done;
switch (itr_setting) {
case lowest_latency:
/* handle TSO and jumbo frames */
if (bytes/packets > 8000)
retval = bulk_latency;
else if ((packets < 5) && (bytes > 512))
retval = low_latency;
break;
case low_latency: /* 50 usec aka 20000 ints/s */
if (bytes > 10000) {
/* this if handles the TSO accounting */
if (bytes/packets > 8000)
retval = bulk_latency;
else if ((packets < 10) || ((bytes/packets) > 1200))
retval = bulk_latency;
else if ((packets > 35))
retval = lowest_latency;
} else if (bytes/packets > 2000) {
retval = bulk_latency;
} else if (packets <= 2 && bytes < 512) {
retval = lowest_latency;
}
break;
case bulk_latency: /* 250 usec aka 4000 ints/s */
if (bytes > 25000) {
if (packets > 35)
retval = low_latency;
} else if (bytes < 6000) {
retval = low_latency;
}
break;
default:
break;
}
update_itr_done:
return retval;
}
static int igbvf_range_to_itr(enum latency_range current_range)
{
int new_itr;
switch (current_range) {
/* counts and packets in update_itr are dependent on these numbers */
case lowest_latency:
new_itr = IGBVF_70K_ITR;
break;
case low_latency:
new_itr = IGBVF_20K_ITR;
break;
case bulk_latency:
new_itr = IGBVF_4K_ITR;
break;
default:
new_itr = IGBVF_START_ITR;
break;
}
return new_itr;
}
static void igbvf_set_itr(struct igbvf_adapter *adapter)
{
u32 new_itr;
adapter->tx_ring->itr_range =
igbvf_update_itr(adapter,
adapter->tx_ring->itr_val,
adapter->total_tx_packets,
adapter->total_tx_bytes);
/* conservative mode (itr 3) eliminates the lowest_latency setting */
if (adapter->requested_itr == 3 &&
adapter->tx_ring->itr_range == lowest_latency)
adapter->tx_ring->itr_range = low_latency;
new_itr = igbvf_range_to_itr(adapter->tx_ring->itr_range);
if (new_itr != adapter->tx_ring->itr_val) {
u32 current_itr = adapter->tx_ring->itr_val;
/* this attempts to bias the interrupt rate towards Bulk
* by adding intermediate steps when interrupt rate is
* increasing
*/
new_itr = new_itr > current_itr ?
min(current_itr + (new_itr >> 2), new_itr) :
new_itr;
adapter->tx_ring->itr_val = new_itr;
adapter->tx_ring->set_itr = 1;
}
adapter->rx_ring->itr_range =
igbvf_update_itr(adapter, adapter->rx_ring->itr_val,
adapter->total_rx_packets,
adapter->total_rx_bytes);
if (adapter->requested_itr == 3 &&
adapter->rx_ring->itr_range == lowest_latency)
adapter->rx_ring->itr_range = low_latency;
new_itr = igbvf_range_to_itr(adapter->rx_ring->itr_range);
if (new_itr != adapter->rx_ring->itr_val) {
u32 current_itr = adapter->rx_ring->itr_val;
new_itr = new_itr > current_itr ?
min(current_itr + (new_itr >> 2), new_itr) :
new_itr;
adapter->rx_ring->itr_val = new_itr;
adapter->rx_ring->set_itr = 1;
}
}
/**
* igbvf_clean_tx_irq - Reclaim resources after transmit completes
* @adapter: board private structure
*
* returns true if ring is completely cleaned
**/
static bool igbvf_clean_tx_irq(struct igbvf_ring *tx_ring)
{
struct igbvf_adapter *adapter = tx_ring->adapter;
struct net_device *netdev = adapter->netdev;
struct igbvf_buffer *buffer_info;
struct sk_buff *skb;
union e1000_adv_tx_desc *tx_desc, *eop_desc;
unsigned int total_bytes = 0, total_packets = 0;
unsigned int i, count = 0;
bool cleaned = false;
i = tx_ring->next_to_clean;
buffer_info = &tx_ring->buffer_info[i];
eop_desc = buffer_info->next_to_watch;
do {
/* if next_to_watch is not set then there is no work pending */
if (!eop_desc)
break;
/* prevent any other reads prior to eop_desc */
read_barrier_depends();
/* if DD is not set pending work has not been completed */
if (!(eop_desc->wb.status & cpu_to_le32(E1000_TXD_STAT_DD)))
break;
/* clear next_to_watch to prevent false hangs */
buffer_info->next_to_watch = NULL;
for (cleaned = false; !cleaned; count++) {
tx_desc = IGBVF_TX_DESC_ADV(*tx_ring, i);
cleaned = (tx_desc == eop_desc);
skb = buffer_info->skb;
if (skb) {
unsigned int segs, bytecount;
/* gso_segs is currently only valid for tcp */
segs = skb_shinfo(skb)->gso_segs ?: 1;
/* multiply data chunks by size of headers */
bytecount = ((segs - 1) * skb_headlen(skb)) +
skb->len;
total_packets += segs;
total_bytes += bytecount;
}
igbvf_put_txbuf(adapter, buffer_info);
tx_desc->wb.status = 0;
i++;
if (i == tx_ring->count)
i = 0;
buffer_info = &tx_ring->buffer_info[i];
}
eop_desc = buffer_info->next_to_watch;
} while (count < tx_ring->count);
tx_ring->next_to_clean = i;
if (unlikely(count && netif_carrier_ok(netdev) &&
igbvf_desc_unused(tx_ring) >= IGBVF_TX_QUEUE_WAKE)) {
/* Make sure that anybody stopping the queue after this
* sees the new next_to_clean.
*/
smp_mb();
if (netif_queue_stopped(netdev) &&
!(test_bit(__IGBVF_DOWN, &adapter->state))) {
netif_wake_queue(netdev);
++adapter->restart_queue;
}
}
adapter->net_stats.tx_bytes += total_bytes;
adapter->net_stats.tx_packets += total_packets;
return count < tx_ring->count;
}
static irqreturn_t igbvf_msix_other(int irq, void *data)
{
struct net_device *netdev = data;
struct igbvf_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
adapter->int_counter1++;
netif_carrier_off(netdev);
hw->mac.get_link_status = 1;
if (!test_bit(__IGBVF_DOWN, &adapter->state))
mod_timer(&adapter->watchdog_timer, jiffies + 1);
ew32(EIMS, adapter->eims_other);
return IRQ_HANDLED;
}
static irqreturn_t igbvf_intr_msix_tx(int irq, void *data)
{
struct net_device *netdev = data;
struct igbvf_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
struct igbvf_ring *tx_ring = adapter->tx_ring;
if (tx_ring->set_itr) {
writel(tx_ring->itr_val,
adapter->hw.hw_addr + tx_ring->itr_register);
adapter->tx_ring->set_itr = 0;
}
adapter->total_tx_bytes = 0;
adapter->total_tx_packets = 0;
/* auto mask will automatically re-enable the interrupt when we write
* EICS
*/
if (!igbvf_clean_tx_irq(tx_ring))
/* Ring was not completely cleaned, so fire another interrupt */
ew32(EICS, tx_ring->eims_value);
else
ew32(EIMS, tx_ring->eims_value);
return IRQ_HANDLED;
}
static irqreturn_t igbvf_intr_msix_rx(int irq, void *data)
{
struct net_device *netdev = data;
struct igbvf_adapter *adapter = netdev_priv(netdev);
adapter->int_counter0++;
/* Write the ITR value calculated at the end of the
* previous interrupt.
*/
if (adapter->rx_ring->set_itr) {
writel(adapter->rx_ring->itr_val,
adapter->hw.hw_addr + adapter->rx_ring->itr_register);
adapter->rx_ring->set_itr = 0;
}
if (napi_schedule_prep(&adapter->rx_ring->napi)) {
adapter->total_rx_bytes = 0;
adapter->total_rx_packets = 0;
__napi_schedule(&adapter->rx_ring->napi);
}
return IRQ_HANDLED;
}
#define IGBVF_NO_QUEUE -1
static void igbvf_assign_vector(struct igbvf_adapter *adapter, int rx_queue,
int tx_queue, int msix_vector)
{
struct e1000_hw *hw = &adapter->hw;
u32 ivar, index;
/* 82576 uses a table-based method for assigning vectors.
* Each queue has a single entry in the table to which we write
* a vector number along with a "valid" bit. Sadly, the layout
* of the table is somewhat counterintuitive.
*/
if (rx_queue > IGBVF_NO_QUEUE) {
index = (rx_queue >> 1);
ivar = array_er32(IVAR0, index);
if (rx_queue & 0x1) {
/* vector goes into third byte of register */
ivar = ivar & 0xFF00FFFF;
ivar |= (msix_vector | E1000_IVAR_VALID) << 16;
} else {
/* vector goes into low byte of register */
ivar = ivar & 0xFFFFFF00;
ivar |= msix_vector | E1000_IVAR_VALID;
}
adapter->rx_ring[rx_queue].eims_value = 1 << msix_vector;
array_ew32(IVAR0, index, ivar);
}
if (tx_queue > IGBVF_NO_QUEUE) {
index = (tx_queue >> 1);
ivar = array_er32(IVAR0, index);
if (tx_queue & 0x1) {
/* vector goes into high byte of register */
ivar = ivar & 0x00FFFFFF;
ivar |= (msix_vector | E1000_IVAR_VALID) << 24;
} else {
/* vector goes into second byte of register */
ivar = ivar & 0xFFFF00FF;
ivar |= (msix_vector | E1000_IVAR_VALID) << 8;
}
adapter->tx_ring[tx_queue].eims_value = 1 << msix_vector;
array_ew32(IVAR0, index, ivar);
}
}
/**
* igbvf_configure_msix - Configure MSI-X hardware
* @adapter: board private structure
*
* igbvf_configure_msix sets up the hardware to properly
* generate MSI-X interrupts.
**/
static void igbvf_configure_msix(struct igbvf_adapter *adapter)
{
u32 tmp;
struct e1000_hw *hw = &adapter->hw;
struct igbvf_ring *tx_ring = adapter->tx_ring;
struct igbvf_ring *rx_ring = adapter->rx_ring;
int vector = 0;
adapter->eims_enable_mask = 0;
igbvf_assign_vector(adapter, IGBVF_NO_QUEUE, 0, vector++);
adapter->eims_enable_mask |= tx_ring->eims_value;
writel(tx_ring->itr_val, hw->hw_addr + tx_ring->itr_register);
igbvf_assign_vector(adapter, 0, IGBVF_NO_QUEUE, vector++);
adapter->eims_enable_mask |= rx_ring->eims_value;
writel(rx_ring->itr_val, hw->hw_addr + rx_ring->itr_register);
/* set vector for other causes, i.e. link changes */
tmp = (vector++ | E1000_IVAR_VALID);
ew32(IVAR_MISC, tmp);
adapter->eims_enable_mask = (1 << (vector)) - 1;
adapter->eims_other = 1 << (vector - 1);
e1e_flush();
}
static void igbvf_reset_interrupt_capability(struct igbvf_adapter *adapter)
{
if (adapter->msix_entries) {
pci_disable_msix(adapter->pdev);
kfree(adapter->msix_entries);
adapter->msix_entries = NULL;
}
}
/**
* igbvf_set_interrupt_capability - set MSI or MSI-X if supported
* @adapter: board private structure
*
* Attempt to configure interrupts using the best available
* capabilities of the hardware and kernel.
**/
static void igbvf_set_interrupt_capability(struct igbvf_adapter *adapter)
{
int err = -ENOMEM;
int i;
/* we allocate 3 vectors, 1 for Tx, 1 for Rx, one for PF messages */
adapter->msix_entries = kcalloc(3, sizeof(struct msix_entry),
GFP_KERNEL);
if (adapter->msix_entries) {
for (i = 0; i < 3; i++)
adapter->msix_entries[i].entry = i;
err = pci_enable_msix_range(adapter->pdev,
adapter->msix_entries, 3, 3);
}
if (err < 0) {
/* MSI-X failed */
dev_err(&adapter->pdev->dev,
"Failed to initialize MSI-X interrupts.\n");
igbvf_reset_interrupt_capability(adapter);
}
}
/**
* igbvf_request_msix - Initialize MSI-X interrupts
* @adapter: board private structure
*
* igbvf_request_msix allocates MSI-X vectors and requests interrupts from the
* kernel.
**/
static int igbvf_request_msix(struct igbvf_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
int err = 0, vector = 0;
if (strlen(netdev->name) < (IFNAMSIZ - 5)) {
sprintf(adapter->tx_ring->name, "%s-tx-0", netdev->name);
sprintf(adapter->rx_ring->name, "%s-rx-0", netdev->name);
} else {
memcpy(adapter->tx_ring->name, netdev->name, IFNAMSIZ);
memcpy(adapter->rx_ring->name, netdev->name, IFNAMSIZ);
}
err = request_irq(adapter->msix_entries[vector].vector,
igbvf_intr_msix_tx, 0, adapter->tx_ring->name,
netdev);
if (err)
goto out;
adapter->tx_ring->itr_register = E1000_EITR(vector);
adapter->tx_ring->itr_val = adapter->current_itr;
vector++;
err = request_irq(adapter->msix_entries[vector].vector,
igbvf_intr_msix_rx, 0, adapter->rx_ring->name,
netdev);
if (err)
goto out;
adapter->rx_ring->itr_register = E1000_EITR(vector);
adapter->rx_ring->itr_val = adapter->current_itr;
vector++;
err = request_irq(adapter->msix_entries[vector].vector,
igbvf_msix_other, 0, netdev->name, netdev);
if (err)
goto out;
igbvf_configure_msix(adapter);
return 0;
out:
return err;
}
/**
* igbvf_alloc_queues - Allocate memory for all rings
* @adapter: board private structure to initialize
**/
static int igbvf_alloc_queues(struct igbvf_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
adapter->tx_ring = kzalloc(sizeof(struct igbvf_ring), GFP_KERNEL);
if (!adapter->tx_ring)
return -ENOMEM;
adapter->rx_ring = kzalloc(sizeof(struct igbvf_ring), GFP_KERNEL);
if (!adapter->rx_ring) {
kfree(adapter->tx_ring);
return -ENOMEM;
}
netif_napi_add(netdev, &adapter->rx_ring->napi, igbvf_poll, 64);
return 0;
}
/**
* igbvf_request_irq - initialize interrupts
* @adapter: board private structure
*
* Attempts to configure interrupts using the best available
* capabilities of the hardware and kernel.
**/
static int igbvf_request_irq(struct igbvf_adapter *adapter)
{
int err = -1;
/* igbvf supports msi-x only */
if (adapter->msix_entries)
err = igbvf_request_msix(adapter);
if (!err)
return err;
dev_err(&adapter->pdev->dev,
"Unable to allocate interrupt, Error: %d\n", err);
return err;
}
static void igbvf_free_irq(struct igbvf_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
int vector;
if (adapter->msix_entries) {
for (vector = 0; vector < 3; vector++)
free_irq(adapter->msix_entries[vector].vector, netdev);
}
}
/**
* igbvf_irq_disable - Mask off interrupt generation on the NIC
* @adapter: board private structure
**/
static void igbvf_irq_disable(struct igbvf_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
ew32(EIMC, ~0);
if (adapter->msix_entries)
ew32(EIAC, 0);
}
/**
* igbvf_irq_enable - Enable default interrupt generation settings
* @adapter: board private structure
**/
static void igbvf_irq_enable(struct igbvf_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
ew32(EIAC, adapter->eims_enable_mask);
ew32(EIAM, adapter->eims_enable_mask);
ew32(EIMS, adapter->eims_enable_mask);
}
/**
* igbvf_poll - NAPI Rx polling callback
* @napi: struct associated with this polling callback
* @budget: amount of packets driver is allowed to process this poll
**/
static int igbvf_poll(struct napi_struct *napi, int budget)
{
struct igbvf_ring *rx_ring = container_of(napi, struct igbvf_ring, napi);
struct igbvf_adapter *adapter = rx_ring->adapter;
struct e1000_hw *hw = &adapter->hw;
int work_done = 0;
igbvf_clean_rx_irq(adapter, &work_done, budget);
/* If not enough Rx work done, exit the polling mode */
if (work_done < budget) {
napi_complete(napi);
if (adapter->requested_itr & 3)
igbvf_set_itr(adapter);
if (!test_bit(__IGBVF_DOWN, &adapter->state))
ew32(EIMS, adapter->rx_ring->eims_value);
}
return work_done;
}
/**
* igbvf_set_rlpml - set receive large packet maximum length
* @adapter: board private structure
*
* Configure the maximum size of packets that will be received
*/
static void igbvf_set_rlpml(struct igbvf_adapter *adapter)
{
int max_frame_size;
struct e1000_hw *hw = &adapter->hw;
max_frame_size = adapter->max_frame_size + VLAN_TAG_SIZE;
e1000_rlpml_set_vf(hw, max_frame_size);
}
static int igbvf_vlan_rx_add_vid(struct net_device *netdev,
__be16 proto, u16 vid)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
if (hw->mac.ops.set_vfta(hw, vid, true)) {
dev_err(&adapter->pdev->dev, "Failed to add vlan id %d\n", vid);
return -EINVAL;
}
set_bit(vid, adapter->active_vlans);
return 0;
}
static int igbvf_vlan_rx_kill_vid(struct net_device *netdev,
__be16 proto, u16 vid)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
if (hw->mac.ops.set_vfta(hw, vid, false)) {
dev_err(&adapter->pdev->dev,
"Failed to remove vlan id %d\n", vid);
return -EINVAL;
}
clear_bit(vid, adapter->active_vlans);
return 0;
}
static void igbvf_restore_vlan(struct igbvf_adapter *adapter)
{
u16 vid;
for_each_set_bit(vid, adapter->active_vlans, VLAN_N_VID)
igbvf_vlan_rx_add_vid(adapter->netdev, htons(ETH_P_8021Q), vid);
}
/**
* igbvf_configure_tx - Configure Transmit Unit after Reset
* @adapter: board private structure
*
* Configure the Tx unit of the MAC after a reset.
**/
static void igbvf_configure_tx(struct igbvf_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
struct igbvf_ring *tx_ring = adapter->tx_ring;
u64 tdba;
u32 txdctl, dca_txctrl;
/* disable transmits */
txdctl = er32(TXDCTL(0));
ew32(TXDCTL(0), txdctl & ~E1000_TXDCTL_QUEUE_ENABLE);
e1e_flush();
msleep(10);
/* Setup the HW Tx Head and Tail descriptor pointers */
ew32(TDLEN(0), tx_ring->count * sizeof(union e1000_adv_tx_desc));
tdba = tx_ring->dma;
ew32(TDBAL(0), (tdba & DMA_BIT_MASK(32)));
ew32(TDBAH(0), (tdba >> 32));
ew32(TDH(0), 0);
ew32(TDT(0), 0);
tx_ring->head = E1000_TDH(0);
tx_ring->tail = E1000_TDT(0);
/* Turn off Relaxed Ordering on head write-backs. The writebacks
* MUST be delivered in order or it will completely screw up
* our bookkeeping.
*/
dca_txctrl = er32(DCA_TXCTRL(0));
dca_txctrl &= ~E1000_DCA_TXCTRL_TX_WB_RO_EN;
ew32(DCA_TXCTRL(0), dca_txctrl);
/* enable transmits */
txdctl |= E1000_TXDCTL_QUEUE_ENABLE;
ew32(TXDCTL(0), txdctl);
/* Setup Transmit Descriptor Settings for eop descriptor */
adapter->txd_cmd = E1000_ADVTXD_DCMD_EOP | E1000_ADVTXD_DCMD_IFCS;
/* enable Report Status bit */
adapter->txd_cmd |= E1000_ADVTXD_DCMD_RS;
}
/**
* igbvf_setup_srrctl - configure the receive control registers
* @adapter: Board private structure
**/
static void igbvf_setup_srrctl(struct igbvf_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
u32 srrctl = 0;
srrctl &= ~(E1000_SRRCTL_DESCTYPE_MASK |
E1000_SRRCTL_BSIZEHDR_MASK |
E1000_SRRCTL_BSIZEPKT_MASK);
/* Enable queue drop to avoid head of line blocking */
srrctl |= E1000_SRRCTL_DROP_EN;
/* Setup buffer sizes */
srrctl |= ALIGN(adapter->rx_buffer_len, 1024) >>
E1000_SRRCTL_BSIZEPKT_SHIFT;
if (adapter->rx_buffer_len < 2048) {
adapter->rx_ps_hdr_size = 0;
srrctl |= E1000_SRRCTL_DESCTYPE_ADV_ONEBUF;
} else {
adapter->rx_ps_hdr_size = 128;
srrctl |= adapter->rx_ps_hdr_size <<
E1000_SRRCTL_BSIZEHDRSIZE_SHIFT;
srrctl |= E1000_SRRCTL_DESCTYPE_HDR_SPLIT_ALWAYS;
}
ew32(SRRCTL(0), srrctl);
}
/**
* igbvf_configure_rx - Configure Receive Unit after Reset
* @adapter: board private structure
*
* Configure the Rx unit of the MAC after a reset.
**/
static void igbvf_configure_rx(struct igbvf_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
struct igbvf_ring *rx_ring = adapter->rx_ring;
u64 rdba;
u32 rdlen, rxdctl;
/* disable receives */
rxdctl = er32(RXDCTL(0));
ew32(RXDCTL(0), rxdctl & ~E1000_RXDCTL_QUEUE_ENABLE);
e1e_flush();
msleep(10);
rdlen = rx_ring->count * sizeof(union e1000_adv_rx_desc);
/* Setup the HW Rx Head and Tail Descriptor Pointers and
* the Base and Length of the Rx Descriptor Ring
*/
rdba = rx_ring->dma;
ew32(RDBAL(0), (rdba & DMA_BIT_MASK(32)));
ew32(RDBAH(0), (rdba >> 32));
ew32(RDLEN(0), rx_ring->count * sizeof(union e1000_adv_rx_desc));
rx_ring->head = E1000_RDH(0);
rx_ring->tail = E1000_RDT(0);
ew32(RDH(0), 0);
ew32(RDT(0), 0);
rxdctl |= E1000_RXDCTL_QUEUE_ENABLE;
rxdctl &= 0xFFF00000;
rxdctl |= IGBVF_RX_PTHRESH;
rxdctl |= IGBVF_RX_HTHRESH << 8;
rxdctl |= IGBVF_RX_WTHRESH << 16;
igbvf_set_rlpml(adapter);
/* enable receives */
ew32(RXDCTL(0), rxdctl);
}
/**
* igbvf_set_multi - Multicast and Promiscuous mode set
* @netdev: network interface device structure
*
* The set_multi entry point is called whenever the multicast address
* list or the network interface flags are updated. This routine is
* responsible for configuring the hardware for proper multicast,
* promiscuous mode, and all-multi behavior.
**/
static void igbvf_set_multi(struct net_device *netdev)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
struct netdev_hw_addr *ha;
u8 *mta_list = NULL;
int i;
if (!netdev_mc_empty(netdev)) {
mta_list = kmalloc_array(netdev_mc_count(netdev), ETH_ALEN,
GFP_ATOMIC);
if (!mta_list)
return;
}
/* prepare a packed array of only addresses. */
i = 0;
netdev_for_each_mc_addr(ha, netdev)
memcpy(mta_list + (i++ * ETH_ALEN), ha->addr, ETH_ALEN);
hw->mac.ops.update_mc_addr_list(hw, mta_list, i, 0, 0);
kfree(mta_list);
}
/**
* igbvf_configure - configure the hardware for Rx and Tx
* @adapter: private board structure
**/
static void igbvf_configure(struct igbvf_adapter *adapter)
{
igbvf_set_multi(adapter->netdev);
igbvf_restore_vlan(adapter);
igbvf_configure_tx(adapter);
igbvf_setup_srrctl(adapter);
igbvf_configure_rx(adapter);
igbvf_alloc_rx_buffers(adapter->rx_ring,
igbvf_desc_unused(adapter->rx_ring));
}
/* igbvf_reset - bring the hardware into a known good state
* @adapter: private board structure
*
* This function boots the hardware and enables some settings that
* require a configuration cycle of the hardware - those cannot be
* set/changed during runtime. After reset the device needs to be
* properly configured for Rx, Tx etc.
*/
static void igbvf_reset(struct igbvf_adapter *adapter)
{
struct e1000_mac_info *mac = &adapter->hw.mac;
struct net_device *netdev = adapter->netdev;
struct e1000_hw *hw = &adapter->hw;
/* Allow time for pending master requests to run */
if (mac->ops.reset_hw(hw))
dev_err(&adapter->pdev->dev, "PF still resetting\n");
mac->ops.init_hw(hw);
if (is_valid_ether_addr(adapter->hw.mac.addr)) {
memcpy(netdev->dev_addr, adapter->hw.mac.addr,
netdev->addr_len);
memcpy(netdev->perm_addr, adapter->hw.mac.addr,
netdev->addr_len);
}
adapter->last_reset = jiffies;
}
int igbvf_up(struct igbvf_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
/* hardware has been reset, we need to reload some things */
igbvf_configure(adapter);
clear_bit(__IGBVF_DOWN, &adapter->state);
napi_enable(&adapter->rx_ring->napi);
if (adapter->msix_entries)
igbvf_configure_msix(adapter);
/* Clear any pending interrupts. */
er32(EICR);
igbvf_irq_enable(adapter);
/* start the watchdog */
hw->mac.get_link_status = 1;
mod_timer(&adapter->watchdog_timer, jiffies + 1);
return 0;
}
void igbvf_down(struct igbvf_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
struct e1000_hw *hw = &adapter->hw;
u32 rxdctl, txdctl;
/* signal that we're down so the interrupt handler does not
* reschedule our watchdog timer
*/
set_bit(__IGBVF_DOWN, &adapter->state);
/* disable receives in the hardware */
rxdctl = er32(RXDCTL(0));
ew32(RXDCTL(0), rxdctl & ~E1000_RXDCTL_QUEUE_ENABLE);
netif_stop_queue(netdev);
/* disable transmits in the hardware */
txdctl = er32(TXDCTL(0));
ew32(TXDCTL(0), txdctl & ~E1000_TXDCTL_QUEUE_ENABLE);
/* flush both disables and wait for them to finish */
e1e_flush();
msleep(10);
napi_disable(&adapter->rx_ring->napi);
igbvf_irq_disable(adapter);
del_timer_sync(&adapter->watchdog_timer);
netif_carrier_off(netdev);
/* record the stats before reset*/
igbvf_update_stats(adapter);
adapter->link_speed = 0;
adapter->link_duplex = 0;
igbvf_reset(adapter);
igbvf_clean_tx_ring(adapter->tx_ring);
igbvf_clean_rx_ring(adapter->rx_ring);
}
void igbvf_reinit_locked(struct igbvf_adapter *adapter)
{
might_sleep();
while (test_and_set_bit(__IGBVF_RESETTING, &adapter->state))
usleep_range(1000, 2000);
igbvf_down(adapter);
igbvf_up(adapter);
clear_bit(__IGBVF_RESETTING, &adapter->state);
}
/**
* igbvf_sw_init - Initialize general software structures (struct igbvf_adapter)
* @adapter: board private structure to initialize
*
* igbvf_sw_init initializes the Adapter private data structure.
* Fields are initialized based on PCI device information and
* OS network device settings (MTU size).
**/
static int igbvf_sw_init(struct igbvf_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
s32 rc;
adapter->rx_buffer_len = ETH_FRAME_LEN + VLAN_HLEN + ETH_FCS_LEN;
adapter->rx_ps_hdr_size = 0;
adapter->max_frame_size = netdev->mtu + ETH_HLEN + ETH_FCS_LEN;
adapter->min_frame_size = ETH_ZLEN + ETH_FCS_LEN;
adapter->tx_int_delay = 8;
adapter->tx_abs_int_delay = 32;
adapter->rx_int_delay = 0;
adapter->rx_abs_int_delay = 8;
adapter->requested_itr = 3;
adapter->current_itr = IGBVF_START_ITR;
/* Set various function pointers */
adapter->ei->init_ops(&adapter->hw);
rc = adapter->hw.mac.ops.init_params(&adapter->hw);
if (rc)
return rc;
rc = adapter->hw.mbx.ops.init_params(&adapter->hw);
if (rc)
return rc;
igbvf_set_interrupt_capability(adapter);
if (igbvf_alloc_queues(adapter))
return -ENOMEM;
spin_lock_init(&adapter->tx_queue_lock);
/* Explicitly disable IRQ since the NIC can be in any state. */
igbvf_irq_disable(adapter);
spin_lock_init(&adapter->stats_lock);
set_bit(__IGBVF_DOWN, &adapter->state);
return 0;
}
static void igbvf_initialize_last_counter_stats(struct igbvf_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
adapter->stats.last_gprc = er32(VFGPRC);
adapter->stats.last_gorc = er32(VFGORC);
adapter->stats.last_gptc = er32(VFGPTC);
adapter->stats.last_gotc = er32(VFGOTC);
adapter->stats.last_mprc = er32(VFMPRC);
adapter->stats.last_gotlbc = er32(VFGOTLBC);
adapter->stats.last_gptlbc = er32(VFGPTLBC);
adapter->stats.last_gorlbc = er32(VFGORLBC);
adapter->stats.last_gprlbc = er32(VFGPRLBC);
adapter->stats.base_gprc = er32(VFGPRC);
adapter->stats.base_gorc = er32(VFGORC);
adapter->stats.base_gptc = er32(VFGPTC);
adapter->stats.base_gotc = er32(VFGOTC);
adapter->stats.base_mprc = er32(VFMPRC);
adapter->stats.base_gotlbc = er32(VFGOTLBC);
adapter->stats.base_gptlbc = er32(VFGPTLBC);
adapter->stats.base_gorlbc = er32(VFGORLBC);
adapter->stats.base_gprlbc = er32(VFGPRLBC);
}
/**
* igbvf_open - Called when a network interface is made active
* @netdev: network interface device structure
*
* Returns 0 on success, negative value on failure
*
* The open entry point is called when a network interface is made
* active by the system (IFF_UP). At this point all resources needed
* for transmit and receive operations are allocated, the interrupt
* handler is registered with the OS, the watchdog timer is started,
* and the stack is notified that the interface is ready.
**/
static int igbvf_open(struct net_device *netdev)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
int err;
/* disallow open during test */
if (test_bit(__IGBVF_TESTING, &adapter->state))
return -EBUSY;
/* allocate transmit descriptors */
err = igbvf_setup_tx_resources(adapter, adapter->tx_ring);
if (err)
goto err_setup_tx;
/* allocate receive descriptors */
err = igbvf_setup_rx_resources(adapter, adapter->rx_ring);
if (err)
goto err_setup_rx;
/* before we allocate an interrupt, we must be ready to handle it.
* Setting DEBUG_SHIRQ in the kernel makes it fire an interrupt
* as soon as we call pci_request_irq, so we have to setup our
* clean_rx handler before we do so.
*/
igbvf_configure(adapter);
err = igbvf_request_irq(adapter);
if (err)
goto err_req_irq;
/* From here on the code is the same as igbvf_up() */
clear_bit(__IGBVF_DOWN, &adapter->state);
napi_enable(&adapter->rx_ring->napi);
/* clear any pending interrupts */
er32(EICR);
igbvf_irq_enable(adapter);
/* start the watchdog */
hw->mac.get_link_status = 1;
mod_timer(&adapter->watchdog_timer, jiffies + 1);
return 0;
err_req_irq:
igbvf_free_rx_resources(adapter->rx_ring);
err_setup_rx:
igbvf_free_tx_resources(adapter->tx_ring);
err_setup_tx:
igbvf_reset(adapter);
return err;
}
/**
* igbvf_close - Disables a network interface
* @netdev: network interface device structure
*
* Returns 0, this is not allowed to fail
*
* The close entry point is called when an interface is de-activated
* by the OS. The hardware is still under the drivers control, but
* needs to be disabled. A global MAC reset is issued to stop the
* hardware, and all transmit and receive resources are freed.
**/
static int igbvf_close(struct net_device *netdev)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
WARN_ON(test_bit(__IGBVF_RESETTING, &adapter->state));
igbvf_down(adapter);
igbvf_free_irq(adapter);
igbvf_free_tx_resources(adapter->tx_ring);
igbvf_free_rx_resources(adapter->rx_ring);
return 0;
}
/**
* igbvf_set_mac - Change the Ethernet Address of the NIC
* @netdev: network interface device structure
* @p: pointer to an address structure
*
* Returns 0 on success, negative on failure
**/
static int igbvf_set_mac(struct net_device *netdev, void *p)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
struct sockaddr *addr = p;
if (!is_valid_ether_addr(addr->sa_data))
return -EADDRNOTAVAIL;
memcpy(hw->mac.addr, addr->sa_data, netdev->addr_len);
hw->mac.ops.rar_set(hw, hw->mac.addr, 0);
if (!ether_addr_equal(addr->sa_data, hw->mac.addr))
return -EADDRNOTAVAIL;
memcpy(netdev->dev_addr, addr->sa_data, netdev->addr_len);
return 0;
}
#define UPDATE_VF_COUNTER(reg, name) \
{ \
u32 current_counter = er32(reg); \
if (current_counter < adapter->stats.last_##name) \
adapter->stats.name += 0x100000000LL; \
adapter->stats.last_##name = current_counter; \
adapter->stats.name &= 0xFFFFFFFF00000000LL; \
adapter->stats.name |= current_counter; \
}
/**
* igbvf_update_stats - Update the board statistics counters
* @adapter: board private structure
**/
void igbvf_update_stats(struct igbvf_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
struct pci_dev *pdev = adapter->pdev;
/* Prevent stats update while adapter is being reset, link is down
* or if the pci connection is down.
*/
if (adapter->link_speed == 0)
return;
if (test_bit(__IGBVF_RESETTING, &adapter->state))
return;
if (pci_channel_offline(pdev))
return;
UPDATE_VF_COUNTER(VFGPRC, gprc);
UPDATE_VF_COUNTER(VFGORC, gorc);
UPDATE_VF_COUNTER(VFGPTC, gptc);
UPDATE_VF_COUNTER(VFGOTC, gotc);
UPDATE_VF_COUNTER(VFMPRC, mprc);
UPDATE_VF_COUNTER(VFGOTLBC, gotlbc);
UPDATE_VF_COUNTER(VFGPTLBC, gptlbc);
UPDATE_VF_COUNTER(VFGORLBC, gorlbc);
UPDATE_VF_COUNTER(VFGPRLBC, gprlbc);
/* Fill out the OS statistics structure */
adapter->net_stats.multicast = adapter->stats.mprc;
}
static void igbvf_print_link_info(struct igbvf_adapter *adapter)
{
dev_info(&adapter->pdev->dev, "Link is Up %d Mbps %s Duplex\n",
adapter->link_speed,
adapter->link_duplex == FULL_DUPLEX ? "Full" : "Half");
}
static bool igbvf_has_link(struct igbvf_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
s32 ret_val = E1000_SUCCESS;
bool link_active;
/* If interface is down, stay link down */
if (test_bit(__IGBVF_DOWN, &adapter->state))
return false;
ret_val = hw->mac.ops.check_for_link(hw);
link_active = !hw->mac.get_link_status;
/* if check for link returns error we will need to reset */
if (ret_val && time_after(jiffies, adapter->last_reset + (10 * HZ)))
schedule_work(&adapter->reset_task);
return link_active;
}
/**
* igbvf_watchdog - Timer Call-back
* @data: pointer to adapter cast into an unsigned long
**/
static void igbvf_watchdog(unsigned long data)
{
struct igbvf_adapter *adapter = (struct igbvf_adapter *)data;
/* Do the rest outside of interrupt context */
schedule_work(&adapter->watchdog_task);
}
static void igbvf_watchdog_task(struct work_struct *work)
{
struct igbvf_adapter *adapter = container_of(work,
struct igbvf_adapter,
watchdog_task);
struct net_device *netdev = adapter->netdev;
struct e1000_mac_info *mac = &adapter->hw.mac;
struct igbvf_ring *tx_ring = adapter->tx_ring;
struct e1000_hw *hw = &adapter->hw;
u32 link;
int tx_pending = 0;
link = igbvf_has_link(adapter);
if (link) {
if (!netif_carrier_ok(netdev)) {
mac->ops.get_link_up_info(&adapter->hw,
&adapter->link_speed,
&adapter->link_duplex);
igbvf_print_link_info(adapter);
netif_carrier_on(netdev);
netif_wake_queue(netdev);
}
} else {
if (netif_carrier_ok(netdev)) {
adapter->link_speed = 0;
adapter->link_duplex = 0;
dev_info(&adapter->pdev->dev, "Link is Down\n");
netif_carrier_off(netdev);
netif_stop_queue(netdev);
}
}
if (netif_carrier_ok(netdev)) {
igbvf_update_stats(adapter);
} else {
tx_pending = (igbvf_desc_unused(tx_ring) + 1 <
tx_ring->count);
if (tx_pending) {
/* We've lost link, so the controller stops DMA,
* but we've got queued Tx work that's never going
* to get done, so reset controller to flush Tx.
* (Do the reset outside of interrupt context).
*/
adapter->tx_timeout_count++;
schedule_work(&adapter->reset_task);
}
}
/* Cause software interrupt to ensure Rx ring is cleaned */
ew32(EICS, adapter->rx_ring->eims_value);
/* Reset the timer */
if (!test_bit(__IGBVF_DOWN, &adapter->state))
mod_timer(&adapter->watchdog_timer,
round_jiffies(jiffies + (2 * HZ)));
}
#define IGBVF_TX_FLAGS_CSUM 0x00000001
#define IGBVF_TX_FLAGS_VLAN 0x00000002
#define IGBVF_TX_FLAGS_TSO 0x00000004
#define IGBVF_TX_FLAGS_IPV4 0x00000008
#define IGBVF_TX_FLAGS_VLAN_MASK 0xffff0000
#define IGBVF_TX_FLAGS_VLAN_SHIFT 16
static int igbvf_tso(struct igbvf_adapter *adapter,
struct igbvf_ring *tx_ring,
struct sk_buff *skb, u32 tx_flags, u8 *hdr_len,
__be16 protocol)
{
struct e1000_adv_tx_context_desc *context_desc;
struct igbvf_buffer *buffer_info;
u32 info = 0, tu_cmd = 0;
u32 mss_l4len_idx, l4len;
unsigned int i;
int err;
*hdr_len = 0;
err = skb_cow_head(skb, 0);
if (err < 0) {
dev_err(&adapter->pdev->dev, "igbvf_tso returning an error\n");
return err;
}
l4len = tcp_hdrlen(skb);
*hdr_len += l4len;
if (protocol == htons(ETH_P_IP)) {
struct iphdr *iph = ip_hdr(skb);
iph->tot_len = 0;
iph->check = 0;
tcp_hdr(skb)->check = ~csum_tcpudp_magic(iph->saddr,
iph->daddr, 0,
IPPROTO_TCP,
0);
} else if (skb_is_gso_v6(skb)) {
ipv6_hdr(skb)->payload_len = 0;
tcp_hdr(skb)->check = ~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
&ipv6_hdr(skb)->daddr,
0, IPPROTO_TCP, 0);
}
i = tx_ring->next_to_use;
buffer_info = &tx_ring->buffer_info[i];
context_desc = IGBVF_TX_CTXTDESC_ADV(*tx_ring, i);
/* VLAN MACLEN IPLEN */
if (tx_flags & IGBVF_TX_FLAGS_VLAN)
info |= (tx_flags & IGBVF_TX_FLAGS_VLAN_MASK);
info |= (skb_network_offset(skb) << E1000_ADVTXD_MACLEN_SHIFT);
*hdr_len += skb_network_offset(skb);
info |= (skb_transport_header(skb) - skb_network_header(skb));
*hdr_len += (skb_transport_header(skb) - skb_network_header(skb));
context_desc->vlan_macip_lens = cpu_to_le32(info);
/* ADV DTYP TUCMD MKRLOC/ISCSIHEDLEN */
tu_cmd |= (E1000_TXD_CMD_DEXT | E1000_ADVTXD_DTYP_CTXT);
if (protocol == htons(ETH_P_IP))
tu_cmd |= E1000_ADVTXD_TUCMD_IPV4;
tu_cmd |= E1000_ADVTXD_TUCMD_L4T_TCP;
context_desc->type_tucmd_mlhl = cpu_to_le32(tu_cmd);
/* MSS L4LEN IDX */
mss_l4len_idx = (skb_shinfo(skb)->gso_size << E1000_ADVTXD_MSS_SHIFT);
mss_l4len_idx |= (l4len << E1000_ADVTXD_L4LEN_SHIFT);
context_desc->mss_l4len_idx = cpu_to_le32(mss_l4len_idx);
context_desc->seqnum_seed = 0;
buffer_info->time_stamp = jiffies;
buffer_info->dma = 0;
i++;
if (i == tx_ring->count)
i = 0;
tx_ring->next_to_use = i;
return true;
}
static inline bool igbvf_tx_csum(struct igbvf_adapter *adapter,
struct igbvf_ring *tx_ring,
struct sk_buff *skb, u32 tx_flags,
__be16 protocol)
{
struct e1000_adv_tx_context_desc *context_desc;
unsigned int i;
struct igbvf_buffer *buffer_info;
u32 info = 0, tu_cmd = 0;
if ((skb->ip_summed == CHECKSUM_PARTIAL) ||
(tx_flags & IGBVF_TX_FLAGS_VLAN)) {
i = tx_ring->next_to_use;
buffer_info = &tx_ring->buffer_info[i];
context_desc = IGBVF_TX_CTXTDESC_ADV(*tx_ring, i);
if (tx_flags & IGBVF_TX_FLAGS_VLAN)
info |= (tx_flags & IGBVF_TX_FLAGS_VLAN_MASK);
info |= (skb_network_offset(skb) << E1000_ADVTXD_MACLEN_SHIFT);
if (skb->ip_summed == CHECKSUM_PARTIAL)
info |= (skb_transport_header(skb) -
skb_network_header(skb));
context_desc->vlan_macip_lens = cpu_to_le32(info);
tu_cmd |= (E1000_TXD_CMD_DEXT | E1000_ADVTXD_DTYP_CTXT);
if (skb->ip_summed == CHECKSUM_PARTIAL) {
switch (protocol) {
case htons(ETH_P_IP):
tu_cmd |= E1000_ADVTXD_TUCMD_IPV4;
if (ip_hdr(skb)->protocol == IPPROTO_TCP)
tu_cmd |= E1000_ADVTXD_TUCMD_L4T_TCP;
break;
case htons(ETH_P_IPV6):
if (ipv6_hdr(skb)->nexthdr == IPPROTO_TCP)
tu_cmd |= E1000_ADVTXD_TUCMD_L4T_TCP;
break;
default:
break;
}
}
context_desc->type_tucmd_mlhl = cpu_to_le32(tu_cmd);
context_desc->seqnum_seed = 0;
context_desc->mss_l4len_idx = 0;
buffer_info->time_stamp = jiffies;
buffer_info->dma = 0;
i++;
if (i == tx_ring->count)
i = 0;
tx_ring->next_to_use = i;
return true;
}
return false;
}
static int igbvf_maybe_stop_tx(struct net_device *netdev, int size)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
/* there is enough descriptors then we don't need to worry */
if (igbvf_desc_unused(adapter->tx_ring) >= size)
return 0;
netif_stop_queue(netdev);
/* Herbert's original patch had:
* smp_mb__after_netif_stop_queue();
* but since that doesn't exist yet, just open code it.
*/
smp_mb();
/* We need to check again just in case room has been made available */
if (igbvf_desc_unused(adapter->tx_ring) < size)
return -EBUSY;
netif_wake_queue(netdev);
++adapter->restart_queue;
return 0;
}
#define IGBVF_MAX_TXD_PWR 16
#define IGBVF_MAX_DATA_PER_TXD (1 << IGBVF_MAX_TXD_PWR)
static inline int igbvf_tx_map_adv(struct igbvf_adapter *adapter,
struct igbvf_ring *tx_ring,
struct sk_buff *skb)
{
struct igbvf_buffer *buffer_info;
struct pci_dev *pdev = adapter->pdev;
unsigned int len = skb_headlen(skb);
unsigned int count = 0, i;
unsigned int f;
i = tx_ring->next_to_use;
buffer_info = &tx_ring->buffer_info[i];
BUG_ON(len >= IGBVF_MAX_DATA_PER_TXD);
buffer_info->length = len;
/* set time_stamp *before* dma to help avoid a possible race */
buffer_info->time_stamp = jiffies;
buffer_info->mapped_as_page = false;
buffer_info->dma = dma_map_single(&pdev->dev, skb->data, len,
DMA_TO_DEVICE);
if (dma_mapping_error(&pdev->dev, buffer_info->dma))
goto dma_error;
for (f = 0; f < skb_shinfo(skb)->nr_frags; f++) {
const struct skb_frag_struct *frag;
count++;
i++;
if (i == tx_ring->count)
i = 0;
frag = &skb_shinfo(skb)->frags[f];
len = skb_frag_size(frag);
buffer_info = &tx_ring->buffer_info[i];
BUG_ON(len >= IGBVF_MAX_DATA_PER_TXD);
buffer_info->length = len;
buffer_info->time_stamp = jiffies;
buffer_info->mapped_as_page = true;
buffer_info->dma = skb_frag_dma_map(&pdev->dev, frag, 0, len,
DMA_TO_DEVICE);
if (dma_mapping_error(&pdev->dev, buffer_info->dma))
goto dma_error;
}
tx_ring->buffer_info[i].skb = skb;
return ++count;
dma_error:
dev_err(&pdev->dev, "TX DMA map failed\n");
/* clear timestamp and dma mappings for failed buffer_info mapping */
buffer_info->dma = 0;
buffer_info->time_stamp = 0;
buffer_info->length = 0;
buffer_info->mapped_as_page = false;
if (count)
count--;
/* clear timestamp and dma mappings for remaining portion of packet */
while (count--) {
if (i == 0)
i += tx_ring->count;
i--;
buffer_info = &tx_ring->buffer_info[i];
igbvf_put_txbuf(adapter, buffer_info);
}
return 0;
}
static inline void igbvf_tx_queue_adv(struct igbvf_adapter *adapter,
struct igbvf_ring *tx_ring,
int tx_flags, int count,
unsigned int first, u32 paylen,
u8 hdr_len)
{
union e1000_adv_tx_desc *tx_desc = NULL;
struct igbvf_buffer *buffer_info;
u32 olinfo_status = 0, cmd_type_len;
unsigned int i;
cmd_type_len = (E1000_ADVTXD_DTYP_DATA | E1000_ADVTXD_DCMD_IFCS |
E1000_ADVTXD_DCMD_DEXT);
if (tx_flags & IGBVF_TX_FLAGS_VLAN)
cmd_type_len |= E1000_ADVTXD_DCMD_VLE;
if (tx_flags & IGBVF_TX_FLAGS_TSO) {
cmd_type_len |= E1000_ADVTXD_DCMD_TSE;
/* insert tcp checksum */
olinfo_status |= E1000_TXD_POPTS_TXSM << 8;
/* insert ip checksum */
if (tx_flags & IGBVF_TX_FLAGS_IPV4)
olinfo_status |= E1000_TXD_POPTS_IXSM << 8;
} else if (tx_flags & IGBVF_TX_FLAGS_CSUM) {
olinfo_status |= E1000_TXD_POPTS_TXSM << 8;
}
olinfo_status |= ((paylen - hdr_len) << E1000_ADVTXD_PAYLEN_SHIFT);
i = tx_ring->next_to_use;
while (count--) {
buffer_info = &tx_ring->buffer_info[i];
tx_desc = IGBVF_TX_DESC_ADV(*tx_ring, i);
tx_desc->read.buffer_addr = cpu_to_le64(buffer_info->dma);
tx_desc->read.cmd_type_len =
cpu_to_le32(cmd_type_len | buffer_info->length);
tx_desc->read.olinfo_status = cpu_to_le32(olinfo_status);
i++;
if (i == tx_ring->count)
i = 0;
}
tx_desc->read.cmd_type_len |= cpu_to_le32(adapter->txd_cmd);
/* Force memory writes to complete before letting h/w
* know there are new descriptors to fetch. (Only
* applicable for weak-ordered memory model archs,
* such as IA-64).
*/
wmb();
tx_ring->buffer_info[first].next_to_watch = tx_desc;
tx_ring->next_to_use = i;
writel(i, adapter->hw.hw_addr + tx_ring->tail);
/* we need this if more than one processor can write to our tail
* at a time, it synchronizes IO on IA64/Altix systems
*/
mmiowb();
}
static netdev_tx_t igbvf_xmit_frame_ring_adv(struct sk_buff *skb,
struct net_device *netdev,
struct igbvf_ring *tx_ring)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
unsigned int first, tx_flags = 0;
u8 hdr_len = 0;
int count = 0;
int tso = 0;
__be16 protocol = vlan_get_protocol(skb);
if (test_bit(__IGBVF_DOWN, &adapter->state)) {
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
if (skb->len <= 0) {
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
/* need: count + 4 desc gap to keep tail from touching
* + 2 desc gap to keep tail from touching head,
* + 1 desc for skb->data,
* + 1 desc for context descriptor,
* head, otherwise try next time
*/
if (igbvf_maybe_stop_tx(netdev, skb_shinfo(skb)->nr_frags + 4)) {
/* this is a hard error */
return NETDEV_TX_BUSY;
}
if (skb_vlan_tag_present(skb)) {
tx_flags |= IGBVF_TX_FLAGS_VLAN;
tx_flags |= (skb_vlan_tag_get(skb) <<
IGBVF_TX_FLAGS_VLAN_SHIFT);
}
if (protocol == htons(ETH_P_IP))
tx_flags |= IGBVF_TX_FLAGS_IPV4;
first = tx_ring->next_to_use;
tso = skb_is_gso(skb) ?
igbvf_tso(adapter, tx_ring, skb, tx_flags, &hdr_len, protocol) : 0;
if (unlikely(tso < 0)) {
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
if (tso)
tx_flags |= IGBVF_TX_FLAGS_TSO;
else if (igbvf_tx_csum(adapter, tx_ring, skb, tx_flags, protocol) &&
(skb->ip_summed == CHECKSUM_PARTIAL))
tx_flags |= IGBVF_TX_FLAGS_CSUM;
/* count reflects descriptors mapped, if 0 then mapping error
* has occurred and we need to rewind the descriptor queue
*/
count = igbvf_tx_map_adv(adapter, tx_ring, skb);
if (count) {
igbvf_tx_queue_adv(adapter, tx_ring, tx_flags, count,
first, skb->len, hdr_len);
/* Make sure there is space in the ring for the next send. */
igbvf_maybe_stop_tx(netdev, MAX_SKB_FRAGS + 4);
} else {
dev_kfree_skb_any(skb);
tx_ring->buffer_info[first].time_stamp = 0;
tx_ring->next_to_use = first;
}
return NETDEV_TX_OK;
}
static netdev_tx_t igbvf_xmit_frame(struct sk_buff *skb,
struct net_device *netdev)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
struct igbvf_ring *tx_ring;
if (test_bit(__IGBVF_DOWN, &adapter->state)) {
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
tx_ring = &adapter->tx_ring[0];
return igbvf_xmit_frame_ring_adv(skb, netdev, tx_ring);
}
/**
* igbvf_tx_timeout - Respond to a Tx Hang
* @netdev: network interface device structure
**/
static void igbvf_tx_timeout(struct net_device *netdev)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
/* Do the reset outside of interrupt context */
adapter->tx_timeout_count++;
schedule_work(&adapter->reset_task);
}
static void igbvf_reset_task(struct work_struct *work)
{
struct igbvf_adapter *adapter;
adapter = container_of(work, struct igbvf_adapter, reset_task);
igbvf_reinit_locked(adapter);
}
/**
* igbvf_get_stats - Get System Network Statistics
* @netdev: network interface device structure
*
* Returns the address of the device statistics structure.
* The statistics are actually updated from the timer callback.
**/
static struct net_device_stats *igbvf_get_stats(struct net_device *netdev)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
/* only return the current stats */
return &adapter->net_stats;
}
/**
* igbvf_change_mtu - Change the Maximum Transfer Unit
* @netdev: network interface device structure
* @new_mtu: new value for maximum frame size
*
* Returns 0 on success, negative on failure
**/
static int igbvf_change_mtu(struct net_device *netdev, int new_mtu)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
int max_frame = new_mtu + ETH_HLEN + ETH_FCS_LEN;
if (new_mtu < 68 || new_mtu > INT_MAX - ETH_HLEN - ETH_FCS_LEN ||
max_frame > MAX_JUMBO_FRAME_SIZE)
return -EINVAL;
#define MAX_STD_JUMBO_FRAME_SIZE 9234
if (max_frame > MAX_STD_JUMBO_FRAME_SIZE) {
dev_err(&adapter->pdev->dev, "MTU > 9216 not supported.\n");
return -EINVAL;
}
while (test_and_set_bit(__IGBVF_RESETTING, &adapter->state))
usleep_range(1000, 2000);
/* igbvf_down has a dependency on max_frame_size */
adapter->max_frame_size = max_frame;
if (netif_running(netdev))
igbvf_down(adapter);
/* NOTE: netdev_alloc_skb reserves 16 bytes, and typically NET_IP_ALIGN
* means we reserve 2 more, this pushes us to allocate from the next
* larger slab size.
* i.e. RXBUFFER_2048 --> size-4096 slab
* However with the new *_jumbo_rx* routines, jumbo receives will use
* fragmented skbs
*/
if (max_frame <= 1024)
adapter->rx_buffer_len = 1024;
else if (max_frame <= 2048)
adapter->rx_buffer_len = 2048;
else
#if (PAGE_SIZE / 2) > 16384
adapter->rx_buffer_len = 16384;
#else
adapter->rx_buffer_len = PAGE_SIZE / 2;
#endif
/* adjust allocation if LPE protects us, and we aren't using SBP */
if ((max_frame == ETH_FRAME_LEN + ETH_FCS_LEN) ||
(max_frame == ETH_FRAME_LEN + VLAN_HLEN + ETH_FCS_LEN))
adapter->rx_buffer_len = ETH_FRAME_LEN + VLAN_HLEN +
ETH_FCS_LEN;
dev_info(&adapter->pdev->dev, "changing MTU from %d to %d\n",
netdev->mtu, new_mtu);
netdev->mtu = new_mtu;
if (netif_running(netdev))
igbvf_up(adapter);
else
igbvf_reset(adapter);
clear_bit(__IGBVF_RESETTING, &adapter->state);
return 0;
}
static int igbvf_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
{
switch (cmd) {
default:
return -EOPNOTSUPP;
}
}
static int igbvf_suspend(struct pci_dev *pdev, pm_message_t state)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct igbvf_adapter *adapter = netdev_priv(netdev);
#ifdef CONFIG_PM
int retval = 0;
#endif
netif_device_detach(netdev);
if (netif_running(netdev)) {
WARN_ON(test_bit(__IGBVF_RESETTING, &adapter->state));
igbvf_down(adapter);
igbvf_free_irq(adapter);
}
#ifdef CONFIG_PM
retval = pci_save_state(pdev);
if (retval)
return retval;
#endif
pci_disable_device(pdev);
return 0;
}
#ifdef CONFIG_PM
static int igbvf_resume(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct igbvf_adapter *adapter = netdev_priv(netdev);
u32 err;
pci_restore_state(pdev);
err = pci_enable_device_mem(pdev);
if (err) {
dev_err(&pdev->dev, "Cannot enable PCI device from suspend\n");
return err;
}
pci_set_master(pdev);
if (netif_running(netdev)) {
err = igbvf_request_irq(adapter);
if (err)
return err;
}
igbvf_reset(adapter);
if (netif_running(netdev))
igbvf_up(adapter);
netif_device_attach(netdev);
return 0;
}
#endif
static void igbvf_shutdown(struct pci_dev *pdev)
{
igbvf_suspend(pdev, PMSG_SUSPEND);
}
#ifdef CONFIG_NET_POLL_CONTROLLER
/* Polling 'interrupt' - used by things like netconsole to send skbs
* without having to re-enable interrupts. It's not called while
* the interrupt routine is executing.
*/
static void igbvf_netpoll(struct net_device *netdev)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
disable_irq(adapter->pdev->irq);
igbvf_clean_tx_irq(adapter->tx_ring);
enable_irq(adapter->pdev->irq);
}
#endif
/**
* igbvf_io_error_detected - called when PCI error is detected
* @pdev: Pointer to PCI device
* @state: The current pci connection state
*
* This function is called after a PCI bus error affecting
* this device has been detected.
*/
static pci_ers_result_t igbvf_io_error_detected(struct pci_dev *pdev,
pci_channel_state_t state)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct igbvf_adapter *adapter = netdev_priv(netdev);
netif_device_detach(netdev);
if (state == pci_channel_io_perm_failure)
return PCI_ERS_RESULT_DISCONNECT;
if (netif_running(netdev))
igbvf_down(adapter);
pci_disable_device(pdev);
/* Request a slot slot reset. */
return PCI_ERS_RESULT_NEED_RESET;
}
/**
* igbvf_io_slot_reset - called after the pci bus has been reset.
* @pdev: Pointer to PCI device
*
* Restart the card from scratch, as if from a cold-boot. Implementation
* resembles the first-half of the igbvf_resume routine.
*/
static pci_ers_result_t igbvf_io_slot_reset(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct igbvf_adapter *adapter = netdev_priv(netdev);
if (pci_enable_device_mem(pdev)) {
dev_err(&pdev->dev,
"Cannot re-enable PCI device after reset.\n");
return PCI_ERS_RESULT_DISCONNECT;
}
pci_set_master(pdev);
igbvf_reset(adapter);
return PCI_ERS_RESULT_RECOVERED;
}
/**
* igbvf_io_resume - called when traffic can start flowing again.
* @pdev: Pointer to PCI device
*
* This callback is called when the error recovery driver tells us that
* its OK to resume normal operation. Implementation resembles the
* second-half of the igbvf_resume routine.
*/
static void igbvf_io_resume(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct igbvf_adapter *adapter = netdev_priv(netdev);
if (netif_running(netdev)) {
if (igbvf_up(adapter)) {
dev_err(&pdev->dev,
"can't bring device back up after reset\n");
return;
}
}
netif_device_attach(netdev);
}
static void igbvf_print_device_info(struct igbvf_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
struct net_device *netdev = adapter->netdev;
struct pci_dev *pdev = adapter->pdev;
if (hw->mac.type == e1000_vfadapt_i350)
dev_info(&pdev->dev, "Intel(R) I350 Virtual Function\n");
else
dev_info(&pdev->dev, "Intel(R) 82576 Virtual Function\n");
dev_info(&pdev->dev, "Address: %pM\n", netdev->dev_addr);
}
static int igbvf_set_features(struct net_device *netdev,
netdev_features_t features)
{
struct igbvf_adapter *adapter = netdev_priv(netdev);
if (features & NETIF_F_RXCSUM)
adapter->flags &= ~IGBVF_FLAG_RX_CSUM_DISABLED;
else
adapter->flags |= IGBVF_FLAG_RX_CSUM_DISABLED;
return 0;
}
static const struct net_device_ops igbvf_netdev_ops = {
.ndo_open = igbvf_open,
.ndo_stop = igbvf_close,
.ndo_start_xmit = igbvf_xmit_frame,
.ndo_get_stats = igbvf_get_stats,
.ndo_set_rx_mode = igbvf_set_multi,
.ndo_set_mac_address = igbvf_set_mac,
.ndo_change_mtu = igbvf_change_mtu,
.ndo_do_ioctl = igbvf_ioctl,
.ndo_tx_timeout = igbvf_tx_timeout,
.ndo_vlan_rx_add_vid = igbvf_vlan_rx_add_vid,
.ndo_vlan_rx_kill_vid = igbvf_vlan_rx_kill_vid,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = igbvf_netpoll,
#endif
.ndo_set_features = igbvf_set_features,
};
/**
* igbvf_probe - Device Initialization Routine
* @pdev: PCI device information struct
* @ent: entry in igbvf_pci_tbl
*
* Returns 0 on success, negative on failure
*
* igbvf_probe initializes an adapter identified by a pci_dev structure.
* The OS initialization, configuring of the adapter private structure,
* and a hardware reset occur.
**/
static int igbvf_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
{
struct net_device *netdev;
struct igbvf_adapter *adapter;
struct e1000_hw *hw;
const struct igbvf_info *ei = igbvf_info_tbl[ent->driver_data];
static int cards_found;
int err, pci_using_dac;
err = pci_enable_device_mem(pdev);
if (err)
return err;
pci_using_dac = 0;
err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
if (!err) {
pci_using_dac = 1;
} else {
err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32));
if (err) {
dev_err(&pdev->dev,
"No usable DMA configuration, aborting\n");
goto err_dma;
}
}
err = pci_request_regions(pdev, igbvf_driver_name);
if (err)
goto err_pci_reg;
pci_set_master(pdev);
err = -ENOMEM;
netdev = alloc_etherdev(sizeof(struct igbvf_adapter));
if (!netdev)
goto err_alloc_etherdev;
SET_NETDEV_DEV(netdev, &pdev->dev);
pci_set_drvdata(pdev, netdev);
adapter = netdev_priv(netdev);
hw = &adapter->hw;
adapter->netdev = netdev;
adapter->pdev = pdev;
adapter->ei = ei;
adapter->pba = ei->pba;
adapter->flags = ei->flags;
adapter->hw.back = adapter;
adapter->hw.mac.type = ei->mac;
adapter->msg_enable = netif_msg_init(debug, DEFAULT_MSG_ENABLE);
/* PCI config space info */
hw->vendor_id = pdev->vendor;
hw->device_id = pdev->device;
hw->subsystem_vendor_id = pdev->subsystem_vendor;
hw->subsystem_device_id = pdev->subsystem_device;
hw->revision_id = pdev->revision;
err = -EIO;
adapter->hw.hw_addr = ioremap(pci_resource_start(pdev, 0),
pci_resource_len(pdev, 0));
if (!adapter->hw.hw_addr)
goto err_ioremap;
if (ei->get_variants) {
err = ei->get_variants(adapter);
if (err)
goto err_get_variants;
}
/* setup adapter struct */
err = igbvf_sw_init(adapter);
if (err)
goto err_sw_init;
/* construct the net_device struct */
netdev->netdev_ops = &igbvf_netdev_ops;
igbvf_set_ethtool_ops(netdev);
netdev->watchdog_timeo = 5 * HZ;
strncpy(netdev->name, pci_name(pdev), sizeof(netdev->name) - 1);
adapter->bd_number = cards_found++;
netdev->hw_features = NETIF_F_SG |
NETIF_F_IP_CSUM |
NETIF_F_IPV6_CSUM |
NETIF_F_TSO |
NETIF_F_TSO6 |
NETIF_F_RXCSUM;
netdev->features = netdev->hw_features |
NETIF_F_HW_VLAN_CTAG_TX |
NETIF_F_HW_VLAN_CTAG_RX |
NETIF_F_HW_VLAN_CTAG_FILTER;
if (pci_using_dac)
netdev->features |= NETIF_F_HIGHDMA;
netdev->vlan_features |= NETIF_F_TSO;
netdev->vlan_features |= NETIF_F_TSO6;
netdev->vlan_features |= NETIF_F_IP_CSUM;
netdev->vlan_features |= NETIF_F_IPV6_CSUM;
netdev->vlan_features |= NETIF_F_SG;
/*reset the controller to put the device in a known good state */
err = hw->mac.ops.reset_hw(hw);
if (err) {
dev_info(&pdev->dev,
"PF still in reset state. Is the PF interface up?\n");
} else {
err = hw->mac.ops.read_mac_addr(hw);
if (err)
dev_info(&pdev->dev, "Error reading MAC address.\n");
else if (is_zero_ether_addr(adapter->hw.mac.addr))
dev_info(&pdev->dev,
"MAC address not assigned by administrator.\n");
memcpy(netdev->dev_addr, adapter->hw.mac.addr,
netdev->addr_len);
}
if (!is_valid_ether_addr(netdev->dev_addr)) {
dev_info(&pdev->dev, "Assigning random MAC address.\n");
eth_hw_addr_random(netdev);
memcpy(adapter->hw.mac.addr, netdev->dev_addr,
netdev->addr_len);
}
setup_timer(&adapter->watchdog_timer, &igbvf_watchdog,
(unsigned long)adapter);
INIT_WORK(&adapter->reset_task, igbvf_reset_task);
INIT_WORK(&adapter->watchdog_task, igbvf_watchdog_task);
/* ring size defaults */
adapter->rx_ring->count = 1024;
adapter->tx_ring->count = 1024;
/* reset the hardware with the new settings */
igbvf_reset(adapter);
/* set hardware-specific flags */
if (adapter->hw.mac.type == e1000_vfadapt_i350)
adapter->flags |= IGBVF_FLAG_RX_LB_VLAN_BSWAP;
strcpy(netdev->name, "eth%d");
err = register_netdev(netdev);
if (err)
goto err_hw_init;
/* tell the stack to leave us alone until igbvf_open() is called */
netif_carrier_off(netdev);
netif_stop_queue(netdev);
igbvf_print_device_info(adapter);
igbvf_initialize_last_counter_stats(adapter);
return 0;
err_hw_init:
kfree(adapter->tx_ring);
kfree(adapter->rx_ring);
err_sw_init:
igbvf_reset_interrupt_capability(adapter);
err_get_variants:
iounmap(adapter->hw.hw_addr);
err_ioremap:
free_netdev(netdev);
err_alloc_etherdev:
pci_release_regions(pdev);
err_pci_reg:
err_dma:
pci_disable_device(pdev);
return err;
}
/**
* igbvf_remove - Device Removal Routine
* @pdev: PCI device information struct
*
* igbvf_remove is called by the PCI subsystem to alert the driver
* that it should release a PCI device. The could be caused by a
* Hot-Plug event, or because the driver is going to be removed from
* memory.
**/
static void igbvf_remove(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct igbvf_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
/* The watchdog timer may be rescheduled, so explicitly
* disable it from being rescheduled.
*/
set_bit(__IGBVF_DOWN, &adapter->state);
del_timer_sync(&adapter->watchdog_timer);
cancel_work_sync(&adapter->reset_task);
cancel_work_sync(&adapter->watchdog_task);
unregister_netdev(netdev);
igbvf_reset_interrupt_capability(adapter);
/* it is important to delete the NAPI struct prior to freeing the
* Rx ring so that you do not end up with null pointer refs
*/
netif_napi_del(&adapter->rx_ring->napi);
kfree(adapter->tx_ring);
kfree(adapter->rx_ring);
iounmap(hw->hw_addr);
if (hw->flash_address)
iounmap(hw->flash_address);
pci_release_regions(pdev);
free_netdev(netdev);
pci_disable_device(pdev);
}
/* PCI Error Recovery (ERS) */
static const struct pci_error_handlers igbvf_err_handler = {
.error_detected = igbvf_io_error_detected,
.slot_reset = igbvf_io_slot_reset,
.resume = igbvf_io_resume,
};
static const struct pci_device_id igbvf_pci_tbl[] = {
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_82576_VF), board_vf },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_I350_VF), board_i350_vf },
{ } /* terminate list */
};
MODULE_DEVICE_TABLE(pci, igbvf_pci_tbl);
/* PCI Device API Driver */
static struct pci_driver igbvf_driver = {
.name = igbvf_driver_name,
.id_table = igbvf_pci_tbl,
.probe = igbvf_probe,
.remove = igbvf_remove,
#ifdef CONFIG_PM
/* Power Management Hooks */
.suspend = igbvf_suspend,
.resume = igbvf_resume,
#endif
.shutdown = igbvf_shutdown,
.err_handler = &igbvf_err_handler
};
/**
* igbvf_init_module - Driver Registration Routine
*
* igbvf_init_module is the first routine called when the driver is
* loaded. All it does is register with the PCI subsystem.
**/
static int __init igbvf_init_module(void)
{
int ret;
pr_info("%s - version %s\n", igbvf_driver_string, igbvf_driver_version);
pr_info("%s\n", igbvf_copyright);
ret = pci_register_driver(&igbvf_driver);
return ret;
}
module_init(igbvf_init_module);
/**
* igbvf_exit_module - Driver Exit Cleanup Routine
*
* igbvf_exit_module is called just before the driver is removed
* from memory.
**/
static void __exit igbvf_exit_module(void)
{
pci_unregister_driver(&igbvf_driver);
}
module_exit(igbvf_exit_module);
MODULE_AUTHOR("Intel Corporation, <e1000-devel@lists.sourceforge.net>");
MODULE_DESCRIPTION("Intel(R) Gigabit Virtual Function Network Driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_VERSION);
/* netdev.c */
|
vladzcloudius/net-next
|
drivers/net/ethernet/intel/igbvf/netdev.c
|
C
|
gpl-2.0
| 77,706
|
<?php
class FB_Recommendations_Widget extends WP_Widget
{
function FB_Recommendations_Widget()
{
/* Widget settings. */
$widget_ops = array( 'classname' => 'share_links', 'description' => 'Display the Facebook Recommendations on your website.' );
/* Widget control settings. */
$control_ops = array( 'width' => 400, 'height' => 400, 'id_base' => 'fb-recommendations-widget' );
/* Create the widget. */
$this->WP_Widget( 'fb-recommendations-widget', 'Facebook Recommendations', $widget_ops, $control_ops );
}
function widget( $args, $instance )
{
extract( $args, EXTR_SKIP );
$title = apply_filters('widget_title', $instance['fb-recommendations-title'] );
echo $before_widget;
$title = empty($instance['fb-recommendations-title']) ? ' ' : apply_filters('widget_title', $instance['fb-recommendations-title']);
if (!empty($title))
echo $before_title . $title . $after_title;
$title = attribute_escape(strip_tags($instance['fb-recommendations-title']));
$width = attribute_escape(strip_tags($instance['fb-recommendations-width']));
if ($width == "") $width = "220";
$height = attribute_escape(strip_tags($instance['fb-recommendations-height']));
if ($height == "") $height = "300";
$showHeader = attribute_escape(strip_tags($instance['fb-recommendations-show-header']));
if ($showHeader == "on")
$showHeader = "true";
else
$showHeader = "false";
$colorScheme = attribute_escape(strip_tags($instance['fb-recommendations-color-scheme']));
if ($colorScheme == "") $colorScheme = "light";
$font = attribute_escape(strip_tags($instance['fb-recommendations-font']));
$borderColor = attribute_escape(strip_tags($instance['fb-recommendations-border-color']));
echo '<iframe src="http://www.facebook.com/plugins/recommendations.php?site=' .
get_bloginfo('wpurl').'&width='.$width.'&height='.$height.'&header='.$showHeader.'&colorscheme='.$colorScheme .
'&font='.$font.'&border_color='.$borderColor.'&" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:'.$width.'px; height:'.$height.'px;" allowTransparency="true"></iframe>';
echo $after_widget;
}
function update( $new_instance, $old_instance )
{
$instance = $old_instance;
$instance['fb-recommendations-title'] = strip_tags($new_instance['fb-recommendations-title']);
$instance['fb-recommendations-width'] = strip_tags($new_instance['fb-recommendations-width']);
$instance['fb-recommendations-height'] = strip_tags($new_instance['fb-recommendations-height']);
$instance['fb-recommendations-show-header'] = strip_tags($new_instance['fb-recommendations-show-header']);
$instance['fb-recommendations-color-scheme'] = strip_tags($new_instance['fb-recommendations-color-scheme']);
$instance['fb-recommendations-font'] = strip_tags($new_instance['fb-recommendations-font']);
$instance['fb-recommendations-border-color'] = strip_tags($new_instance['fb-recommendations-border-color']);
$instance[$layout] = strip_tags($new_instance[$layout]);
return $instance;
}
function form( $instance )
{
$title = attribute_escape(strip_tags($instance['fb-recommendations-title']));
$width = attribute_escape(strip_tags($instance['fb-recommendations-width']));
if ($width == "") $width = "220";
$height = attribute_escape(strip_tags($instance['fb-recommendations-height']));
if ($height == "") $height = "300";
$showHeader = attribute_escape(strip_tags($instance['fb-recommendations-show-header']));
$colorScheme = attribute_escape(strip_tags($instance['fb-recommendations-color-scheme']));
$font = attribute_escape(strip_tags($instance['fb-recommendations-font']));
$borderColor = attribute_escape(strip_tags($instance['fb-recommendations-border-color']));
?>
<table style="width:400px;" cellspacing="5px">
<tr><td colspan="4">Title:</td></tr>
<tr><td colspan="4"><input class="widefat" id="<?php echo $this->get_field_id('fb-recommendations-title'); ?>" name="<?php echo $this->get_field_name('fb-recommendations-title'); ?>" type="text" value="<?php echo $title; ?>" /></td></tr>
<tr><td colspan="4"><p> </p></td></tr>
<tr>
<td><label for="">Width:</label></td>
<td>
<input type="text" name="<?php echo $this->get_field_name('fb-recommendations-width'); ?>" id="<?php echo $this->get_field_id('fb-recommendations-width'); ?>" value="<?php echo $width; ?>" style="width:50px" /> px
</td>
</tr>
<tr>
<td><label for="">Height:</label></td>
<td>
<input type="text" name="<?php echo $this->get_field_name('fb-recommendations-height'); ?>" id="<?php echo $this->get_field_id('fb-recommendations-height'); ?>" value="<?php echo $height; ?>" style="width:50px" /> px
</td>
</tr>
<tr>
<td><label for="">Show Header?</label></td>
<td>
<input type="checkbox" name="<?php echo $this->get_field_name('fb-recommendations-show-header'); ?>" id="<?php echo $this->get_field_id('fb-recommendations-show-header'); ?>" <?php if ($showHeader == "on") echo "checked"; ?>/>
</td>
</tr>
<tr>
<td><label for="">Color Scheme:</label></td>
<td>
<select name="<?php echo $this->get_field_name('fb-recommendations-color-scheme'); ?>" id="<?php echo $this->get_field_id('fb-recommendations-color-scheme'); ?>" style="width:100px">
<?php
$options = array(array('light','Light'), array('dark','Dark'));
foreach($options as $index => $value)
{
echo '<option value="'.$value[0].'"';
if ($value[0] == $colorScheme)
echo ' selected';
echo '>'.$value[1].'</option>';
}
?>
</select>
</td>
</tr>
<tr>
<td><label for="">Font:</label></td>
<td>
<select name="<?php echo $this->get_field_name('fb-recommendations-font'); ?>" id="<?php echo $this->get_field_id('fb-recommendations-font'); ?>" style="width:100px">
<?php
$options = array(array('arial','Arial'), array('lucida grande','Lucida Grande'), array('segoe ui', 'Segoe UI'), array('tahoma', 'Tahoma'), array('trebuchet ms', 'Trebuchet MS'), array('verdana', 'Verdana'));
foreach($options as $index => $value)
{
echo '<option value="'.$value[0].'"';
if ($value[0] == $font)
echo ' selected';
echo '>'.$value[1].'</option>';
}
?>
</select>
</td>
</tr>
<tr>
<td><label for="">Border Color:</label></td>
<td>
<input type="text" name="<?php echo $this->get_field_name('fb-recommendations-border-color'); ?>" id="<?php echo $this->get_field_id('fb-recommendations-border-color'); ?>" value="<?php echo $borderColor; ?>" style="width:100px" />
</td>
</tr>
<tr><td colspan="4"><p> </p></td></tr>
</table>
<?php
}
}
?>
|
dhustlerz/dhustlerzBlog
|
wp-content/plugins/social-share/facebookwidgets/recommendations.inc.php
|
PHP
|
gpl-2.0
| 6,974
|
/*
* linux/drivers/clocksource/arm_arch_timer.c
*
* Copyright (C) 2011 ARM Ltd.
* All Rights Reserved
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/device.h>
#include <linux/smp.h>
#include <linux/cpu.h>
#include <linux/cpu_pm.h>
#include <linux/clockchips.h>
#include <linux/interrupt.h>
#include <linux/of_irq.h>
#include <linux/of_address.h>
#include <linux/io.h>
#include <linux/slab.h>
#include <linux/sched_clock.h>
#include <asm/arch_timer.h>
#include <asm/virt.h>
#include <clocksource/arm_arch_timer.h>
#define CNTTIDR 0x08
#define CNTTIDR_VIRT(n) (BIT(1) << ((n) * 4))
#define CNTPCT_LO 0x00
#define CNTPCT_HI 0x04
#define CNTVCT_LO 0x08
#define CNTVCT_HI 0x0c
#define CNTFRQ 0x10
#define CNTP_TVAL 0x28
#define CNTP_CTL 0x2c
#define CNTV_TVAL 0x38
#define CNTV_CTL 0x3c
#define ARCH_CP15_TIMER BIT(0)
#define ARCH_MEM_TIMER BIT(1)
static unsigned arch_timers_present __initdata;
static void __iomem *arch_counter_base;
struct arch_timer {
void __iomem *base;
struct clock_event_device evt;
};
#define to_arch_timer(e) container_of(e, struct arch_timer, evt)
static u32 arch_timer_rate;
enum ppi_nr {
PHYS_SECURE_PPI,
PHYS_NONSECURE_PPI,
VIRT_PPI,
HYP_PPI,
MAX_TIMER_PPI
};
static int arch_timer_ppi[MAX_TIMER_PPI];
static struct clock_event_device __percpu *arch_timer_evt;
static bool arch_timer_use_virtual = true;
static bool arch_timer_c3stop;
static bool arch_timer_mem_use_virtual;
/*
* Architected system timer support.
*/
static __always_inline
void arch_timer_reg_write(int access, enum arch_timer_reg reg, u32 val,
struct clock_event_device *clk)
{
if (access == ARCH_TIMER_MEM_PHYS_ACCESS) {
struct arch_timer *timer = to_arch_timer(clk);
switch (reg) {
case ARCH_TIMER_REG_CTRL:
writel_relaxed(val, timer->base + CNTP_CTL);
break;
case ARCH_TIMER_REG_TVAL:
writel_relaxed(val, timer->base + CNTP_TVAL);
break;
}
} else if (access == ARCH_TIMER_MEM_VIRT_ACCESS) {
struct arch_timer *timer = to_arch_timer(clk);
switch (reg) {
case ARCH_TIMER_REG_CTRL:
writel_relaxed(val, timer->base + CNTV_CTL);
break;
case ARCH_TIMER_REG_TVAL:
writel_relaxed(val, timer->base + CNTV_TVAL);
break;
}
} else {
arch_timer_reg_write_cp15(access, reg, val);
}
}
static __always_inline
u32 arch_timer_reg_read(int access, enum arch_timer_reg reg,
struct clock_event_device *clk)
{
u32 val;
if (access == ARCH_TIMER_MEM_PHYS_ACCESS) {
struct arch_timer *timer = to_arch_timer(clk);
switch (reg) {
case ARCH_TIMER_REG_CTRL:
val = readl_relaxed(timer->base + CNTP_CTL);
break;
case ARCH_TIMER_REG_TVAL:
val = readl_relaxed(timer->base + CNTP_TVAL);
break;
}
} else if (access == ARCH_TIMER_MEM_VIRT_ACCESS) {
struct arch_timer *timer = to_arch_timer(clk);
switch (reg) {
case ARCH_TIMER_REG_CTRL:
val = readl_relaxed(timer->base + CNTV_CTL);
break;
case ARCH_TIMER_REG_TVAL:
val = readl_relaxed(timer->base + CNTV_TVAL);
break;
}
} else {
val = arch_timer_reg_read_cp15(access, reg);
}
return val;
}
static __always_inline irqreturn_t timer_handler(const int access,
struct clock_event_device *evt)
{
unsigned long ctrl;
ctrl = arch_timer_reg_read(access, ARCH_TIMER_REG_CTRL, evt);
if (ctrl & ARCH_TIMER_CTRL_IT_STAT) {
ctrl |= ARCH_TIMER_CTRL_IT_MASK;
arch_timer_reg_write(access, ARCH_TIMER_REG_CTRL, ctrl, evt);
evt->event_handler(evt);
return IRQ_HANDLED;
}
return IRQ_NONE;
}
static irqreturn_t arch_timer_handler_virt(int irq, void *dev_id)
{
struct clock_event_device *evt = dev_id;
return timer_handler(ARCH_TIMER_VIRT_ACCESS, evt);
}
static irqreturn_t arch_timer_handler_phys(int irq, void *dev_id)
{
struct clock_event_device *evt = dev_id;
return timer_handler(ARCH_TIMER_PHYS_ACCESS, evt);
}
static irqreturn_t arch_timer_handler_phys_mem(int irq, void *dev_id)
{
struct clock_event_device *evt = dev_id;
return timer_handler(ARCH_TIMER_MEM_PHYS_ACCESS, evt);
}
static irqreturn_t arch_timer_handler_virt_mem(int irq, void *dev_id)
{
struct clock_event_device *evt = dev_id;
return timer_handler(ARCH_TIMER_MEM_VIRT_ACCESS, evt);
}
static __always_inline void timer_set_mode(const int access, int mode,
struct clock_event_device *clk)
{
unsigned long ctrl;
switch (mode) {
case CLOCK_EVT_MODE_UNUSED:
case CLOCK_EVT_MODE_SHUTDOWN:
ctrl = arch_timer_reg_read(access, ARCH_TIMER_REG_CTRL, clk);
ctrl &= ~ARCH_TIMER_CTRL_ENABLE;
arch_timer_reg_write(access, ARCH_TIMER_REG_CTRL, ctrl, clk);
break;
default:
break;
}
}
static void arch_timer_set_mode_virt(enum clock_event_mode mode,
struct clock_event_device *clk)
{
timer_set_mode(ARCH_TIMER_VIRT_ACCESS, mode, clk);
}
static void arch_timer_set_mode_phys(enum clock_event_mode mode,
struct clock_event_device *clk)
{
timer_set_mode(ARCH_TIMER_PHYS_ACCESS, mode, clk);
}
static void arch_timer_set_mode_virt_mem(enum clock_event_mode mode,
struct clock_event_device *clk)
{
timer_set_mode(ARCH_TIMER_MEM_VIRT_ACCESS, mode, clk);
}
static void arch_timer_set_mode_phys_mem(enum clock_event_mode mode,
struct clock_event_device *clk)
{
timer_set_mode(ARCH_TIMER_MEM_PHYS_ACCESS, mode, clk);
}
static __always_inline void set_next_event(const int access, unsigned long evt,
struct clock_event_device *clk)
{
unsigned long ctrl;
ctrl = arch_timer_reg_read(access, ARCH_TIMER_REG_CTRL, clk);
ctrl |= ARCH_TIMER_CTRL_ENABLE;
ctrl &= ~ARCH_TIMER_CTRL_IT_MASK;
arch_timer_reg_write(access, ARCH_TIMER_REG_TVAL, evt, clk);
arch_timer_reg_write(access, ARCH_TIMER_REG_CTRL, ctrl, clk);
}
static int arch_timer_set_next_event_virt(unsigned long evt,
struct clock_event_device *clk)
{
set_next_event(ARCH_TIMER_VIRT_ACCESS, evt, clk);
return 0;
}
static int arch_timer_set_next_event_phys(unsigned long evt,
struct clock_event_device *clk)
{
set_next_event(ARCH_TIMER_PHYS_ACCESS, evt, clk);
return 0;
}
static int arch_timer_set_next_event_virt_mem(unsigned long evt,
struct clock_event_device *clk)
{
set_next_event(ARCH_TIMER_MEM_VIRT_ACCESS, evt, clk);
return 0;
}
static int arch_timer_set_next_event_phys_mem(unsigned long evt,
struct clock_event_device *clk)
{
set_next_event(ARCH_TIMER_MEM_PHYS_ACCESS, evt, clk);
return 0;
}
static void __arch_timer_setup(unsigned type,
struct clock_event_device *clk)
{
clk->features = CLOCK_EVT_FEAT_ONESHOT;
if (type == ARCH_CP15_TIMER) {
if (arch_timer_c3stop)
clk->features |= CLOCK_EVT_FEAT_C3STOP;
clk->name = "arch_sys_timer";
clk->rating = 450;
clk->cpumask = cpumask_of(smp_processor_id());
if (arch_timer_use_virtual) {
clk->irq = arch_timer_ppi[VIRT_PPI];
clk->set_mode = arch_timer_set_mode_virt;
clk->set_next_event = arch_timer_set_next_event_virt;
} else {
clk->irq = arch_timer_ppi[PHYS_SECURE_PPI];
clk->set_mode = arch_timer_set_mode_phys;
clk->set_next_event = arch_timer_set_next_event_phys;
}
} else {
clk->name = "arch_mem_timer";
clk->rating = 400;
clk->cpumask = cpu_all_mask;
if (arch_timer_mem_use_virtual) {
clk->set_mode = arch_timer_set_mode_virt_mem;
clk->set_next_event =
arch_timer_set_next_event_virt_mem;
} else {
clk->set_mode = arch_timer_set_mode_phys_mem;
clk->set_next_event =
arch_timer_set_next_event_phys_mem;
}
}
clk->set_mode(CLOCK_EVT_MODE_SHUTDOWN, clk);
clockevents_config_and_register(clk, arch_timer_rate, 0xf, 0x7fffffff);
}
static void arch_timer_configure_evtstream(void)
{
int evt_stream_div, pos;
/* Find the closest power of two to the divisor */
evt_stream_div = arch_timer_rate / ARCH_TIMER_EVT_STREAM_FREQ;
pos = fls(evt_stream_div);
if (pos > 1 && !(evt_stream_div & (1 << (pos - 2))))
pos--;
/* enable event stream */
arch_timer_evtstrm_enable(min(pos, 15));
}
static int arch_timer_setup(struct clock_event_device *clk)
{
__arch_timer_setup(ARCH_CP15_TIMER, clk);
if (arch_timer_use_virtual)
enable_percpu_irq(arch_timer_ppi[VIRT_PPI], 0);
else {
enable_percpu_irq(arch_timer_ppi[PHYS_SECURE_PPI], 0);
if (arch_timer_ppi[PHYS_NONSECURE_PPI])
enable_percpu_irq(arch_timer_ppi[PHYS_NONSECURE_PPI], 0);
}
arch_counter_set_user_access();
if (IS_ENABLED(CONFIG_ARM_ARCH_TIMER_EVTSTREAM))
arch_timer_configure_evtstream();
return 0;
}
static void
arch_timer_detect_rate(void __iomem *cntbase, struct device_node *np)
{
/* Who has more than one independent system counter? */
if (arch_timer_rate)
return;
/* Try to determine the frequency from the device tree or CNTFRQ */
if (of_property_read_u32(np, "clock-frequency", &arch_timer_rate)) {
if (cntbase)
arch_timer_rate = readl_relaxed(cntbase + CNTFRQ);
else
arch_timer_rate = arch_timer_get_cntfrq();
}
/* Check the timer frequency. */
if (arch_timer_rate == 0)
pr_warn("Architected timer frequency not available\n");
}
static void arch_timer_banner(unsigned type)
{
pr_info("Architected %s%s%s timer(s) running at %lu.%02luMHz (%s%s%s).\n",
type & ARCH_CP15_TIMER ? "cp15" : "",
type == (ARCH_CP15_TIMER | ARCH_MEM_TIMER) ? " and " : "",
type & ARCH_MEM_TIMER ? "mmio" : "",
(unsigned long)arch_timer_rate / 1000000,
(unsigned long)(arch_timer_rate / 10000) % 100,
type & ARCH_CP15_TIMER ?
arch_timer_use_virtual ? "virt" : "phys" :
"",
type == (ARCH_CP15_TIMER | ARCH_MEM_TIMER) ? "/" : "",
type & ARCH_MEM_TIMER ?
arch_timer_mem_use_virtual ? "virt" : "phys" :
"");
}
u32 arch_timer_get_rate(void)
{
return arch_timer_rate;
}
static u64 arch_counter_get_cntvct_mem(void)
{
u32 vct_lo, vct_hi, tmp_hi;
do {
vct_hi = readl_relaxed(arch_counter_base + CNTVCT_HI);
vct_lo = readl_relaxed(arch_counter_base + CNTVCT_LO);
tmp_hi = readl_relaxed(arch_counter_base + CNTVCT_HI);
} while (vct_hi != tmp_hi);
return ((u64) vct_hi << 32) | vct_lo;
}
static u64 arch_counter_get_cntpct_mem(void)
{
u32 pct_lo, pct_hi, tmp_hi;
do {
pct_hi = readl_relaxed(arch_counter_base + CNTPCT_HI);
pct_lo = readl_relaxed(arch_counter_base + CNTPCT_LO);
tmp_hi = readl_relaxed(arch_counter_base + CNTPCT_HI);
} while (pct_hi != tmp_hi);
return ((u64) pct_hi << 32) | pct_lo;
}
/*
* Default to cp15 based access because arm64 uses this function for
* sched_clock() before DT is probed and the cp15 method is guaranteed
* to exist on arm64. arm doesn't use this before DT is probed so even
* if we don't have the cp15 accessors we won't have a problem.
*/
u64 (*arch_timer_read_counter)(void) = arch_counter_get_cntvct;
static cycle_t arch_counter_read(struct clocksource *cs)
{
return arch_timer_read_counter();
}
static cycle_t arch_counter_read_cc(const struct cyclecounter *cc)
{
return arch_timer_read_counter();
}
static struct clocksource clocksource_counter = {
.name = "arch_sys_counter",
.rating = 400,
.read = arch_counter_read,
.mask = CLOCKSOURCE_MASK(56),
.flags = CLOCK_SOURCE_IS_CONTINUOUS | CLOCK_SOURCE_SUSPEND_NONSTOP,
};
static struct cyclecounter cyclecounter = {
.read = arch_counter_read_cc,
.mask = CLOCKSOURCE_MASK(56),
};
static struct timecounter timecounter;
struct timecounter *arch_timer_get_timecounter(void)
{
return &timecounter;
}
static void __init arch_counter_register(unsigned type)
{
u64 start_count;
/* Register the CP15 based counter if we have one */
if (type & ARCH_CP15_TIMER) {
if (arch_timer_use_virtual)
arch_timer_read_counter = arch_counter_get_cntvct;
else
arch_timer_read_counter = arch_counter_get_cntpct;
} else {
if (arch_timer_use_virtual)
arch_timer_read_counter = arch_counter_get_cntvct_mem;
else
arch_timer_read_counter = arch_counter_get_cntpct_mem;
}
start_count = arch_timer_read_counter();
clocksource_register_hz(&clocksource_counter, arch_timer_rate);
cyclecounter.mult = clocksource_counter.mult;
cyclecounter.shift = clocksource_counter.shift;
timecounter_init(&timecounter, &cyclecounter, start_count);
/* 56 bits minimum, so we assume worst case rollover */
sched_clock_register(arch_timer_read_counter, 56, arch_timer_rate);
}
static void arch_timer_stop(struct clock_event_device *clk)
{
pr_debug("arch_timer_teardown disable IRQ%d cpu #%d\n",
clk->irq, smp_processor_id());
if (arch_timer_use_virtual)
disable_percpu_irq(arch_timer_ppi[VIRT_PPI]);
else {
disable_percpu_irq(arch_timer_ppi[PHYS_SECURE_PPI]);
if (arch_timer_ppi[PHYS_NONSECURE_PPI])
disable_percpu_irq(arch_timer_ppi[PHYS_NONSECURE_PPI]);
}
clk->set_mode(CLOCK_EVT_MODE_UNUSED, clk);
}
static int arch_timer_cpu_notify(struct notifier_block *self,
unsigned long action, void *hcpu)
{
/*
* Grab cpu pointer in each case to avoid spurious
* preemptible warnings
*/
switch (action & ~CPU_TASKS_FROZEN) {
case CPU_STARTING:
arch_timer_setup(this_cpu_ptr(arch_timer_evt));
break;
case CPU_DYING:
arch_timer_stop(this_cpu_ptr(arch_timer_evt));
break;
}
return NOTIFY_OK;
}
static struct notifier_block arch_timer_cpu_nb = {
.notifier_call = arch_timer_cpu_notify,
};
#ifdef CONFIG_CPU_PM
static unsigned int saved_cntkctl;
static int arch_timer_cpu_pm_notify(struct notifier_block *self,
unsigned long action, void *hcpu)
{
if (action == CPU_PM_ENTER)
saved_cntkctl = arch_timer_get_cntkctl();
else if (action == CPU_PM_ENTER_FAILED || action == CPU_PM_EXIT)
arch_timer_set_cntkctl(saved_cntkctl);
return NOTIFY_OK;
}
static struct notifier_block arch_timer_cpu_pm_notifier = {
.notifier_call = arch_timer_cpu_pm_notify,
};
static int __init arch_timer_cpu_pm_init(void)
{
return cpu_pm_register_notifier(&arch_timer_cpu_pm_notifier);
}
#else
static int __init arch_timer_cpu_pm_init(void)
{
return 0;
}
#endif
static int __init arch_timer_register(void)
{
int err;
int ppi;
arch_timer_evt = alloc_percpu(struct clock_event_device);
if (!arch_timer_evt) {
err = -ENOMEM;
goto out;
}
if (arch_timer_use_virtual) {
ppi = arch_timer_ppi[VIRT_PPI];
err = request_percpu_irq(ppi, arch_timer_handler_virt,
"arch_timer", arch_timer_evt);
} else {
ppi = arch_timer_ppi[PHYS_SECURE_PPI];
err = request_percpu_irq(ppi, arch_timer_handler_phys,
"arch_timer", arch_timer_evt);
if (!err && arch_timer_ppi[PHYS_NONSECURE_PPI]) {
ppi = arch_timer_ppi[PHYS_NONSECURE_PPI];
err = request_percpu_irq(ppi, arch_timer_handler_phys,
"arch_timer", arch_timer_evt);
if (err)
free_percpu_irq(arch_timer_ppi[PHYS_SECURE_PPI],
arch_timer_evt);
}
}
if (err) {
pr_err("arch_timer: can't register interrupt %d (%d)\n",
ppi, err);
goto out_free;
}
err = register_cpu_notifier(&arch_timer_cpu_nb);
if (err)
goto out_free_irq;
err = arch_timer_cpu_pm_init();
if (err)
goto out_unreg_notify;
/* Immediately configure the timer on the boot CPU */
arch_timer_setup(this_cpu_ptr(arch_timer_evt));
return 0;
out_unreg_notify:
unregister_cpu_notifier(&arch_timer_cpu_nb);
out_free_irq:
if (arch_timer_use_virtual)
free_percpu_irq(arch_timer_ppi[VIRT_PPI], arch_timer_evt);
else {
free_percpu_irq(arch_timer_ppi[PHYS_SECURE_PPI],
arch_timer_evt);
if (arch_timer_ppi[PHYS_NONSECURE_PPI])
free_percpu_irq(arch_timer_ppi[PHYS_NONSECURE_PPI],
arch_timer_evt);
}
out_free:
free_percpu(arch_timer_evt);
out:
return err;
}
static int __init arch_timer_mem_register(void __iomem *base, unsigned int irq)
{
int ret;
irq_handler_t func;
struct arch_timer *t;
t = kzalloc(sizeof(*t), GFP_KERNEL);
if (!t)
return -ENOMEM;
t->base = base;
t->evt.irq = irq;
__arch_timer_setup(ARCH_MEM_TIMER, &t->evt);
if (arch_timer_mem_use_virtual)
func = arch_timer_handler_virt_mem;
else
func = arch_timer_handler_phys_mem;
ret = request_irq(irq, func, IRQF_TIMER, "arch_mem_timer", &t->evt);
if (ret) {
pr_err("arch_timer: Failed to request mem timer irq\n");
kfree(t);
}
return ret;
}
static const struct of_device_id arch_timer_of_match[] __initconst = {
{ .compatible = "arm,armv7-timer", },
{ .compatible = "arm,armv8-timer", },
{},
};
static const struct of_device_id arch_timer_mem_of_match[] __initconst = {
{ .compatible = "arm,armv7-timer-mem", },
{},
};
static void __init arch_timer_common_init(void)
{
unsigned mask = ARCH_CP15_TIMER | ARCH_MEM_TIMER;
/* Wait until both nodes are probed if we have two timers */
if ((arch_timers_present & mask) != mask) {
if (of_find_matching_node(NULL, arch_timer_mem_of_match) &&
!(arch_timers_present & ARCH_MEM_TIMER))
return;
if (of_find_matching_node(NULL, arch_timer_of_match) &&
!(arch_timers_present & ARCH_CP15_TIMER))
return;
}
arch_timer_banner(arch_timers_present);
arch_counter_register(arch_timers_present);
arch_timer_arch_init();
}
static void __init arch_timer_init(struct device_node *np)
{
int i;
void __iomem *timer7_base_addr;
timer7_base_addr = ioremap(0xff810020, 0x20);
if (!timer7_base_addr) {
pr_err("%s: could not map timer registers\n", __func__);
return;
}
writel(0, timer7_base_addr + 0x10);
writel(0xFFFFFFFF, timer7_base_addr + 0x00);
writel(0xFFFFFFFF, timer7_base_addr + 0x04);
writel(1, timer7_base_addr + 0x10);
if (arch_timers_present & ARCH_CP15_TIMER) {
pr_warn("arch_timer: multiple nodes in dt, skipping\n");
return;
}
arch_timers_present |= ARCH_CP15_TIMER;
for (i = PHYS_SECURE_PPI; i < MAX_TIMER_PPI; i++)
arch_timer_ppi[i] = irq_of_parse_and_map(np, i);
arch_timer_detect_rate(NULL, np);
#ifdef CONFIG_ARM
if (of_property_read_bool(np, "arm,use-physical-timer"))
arch_timer_use_virtual = false;
#endif
/*
* If HYP mode is available, we know that the physical timer
* has been configured to be accessible from PL1. Use it, so
* that a guest can use the virtual timer instead.
*
* If no interrupt provided for virtual timer, we'll have to
* stick to the physical timer. It'd better be accessible...
*/
if (is_hyp_mode_available() || !arch_timer_ppi[VIRT_PPI]) {
arch_timer_use_virtual = false;
if (!arch_timer_ppi[PHYS_SECURE_PPI] ||
!arch_timer_ppi[PHYS_NONSECURE_PPI]) {
pr_warn("arch_timer: No interrupt available, giving up\n");
return;
}
}
arch_timer_c3stop = !of_property_read_bool(np, "always-on");
arch_timer_register();
arch_timer_common_init();
}
CLOCKSOURCE_OF_DECLARE(armv7_arch_timer, "arm,armv7-timer", arch_timer_init);
CLOCKSOURCE_OF_DECLARE(armv8_arch_timer, "arm,armv8-timer", arch_timer_init);
static void __init arch_timer_mem_init(struct device_node *np)
{
struct device_node *frame, *best_frame = NULL;
void __iomem *cntctlbase, *base;
unsigned int irq;
u32 cnttidr;
arch_timers_present |= ARCH_MEM_TIMER;
cntctlbase = of_iomap(np, 0);
if (!cntctlbase) {
pr_err("arch_timer: Can't find CNTCTLBase\n");
return;
}
cnttidr = readl_relaxed(cntctlbase + CNTTIDR);
iounmap(cntctlbase);
/*
* Try to find a virtual capable frame. Otherwise fall back to a
* physical capable frame.
*/
for_each_available_child_of_node(np, frame) {
int n;
if (of_property_read_u32(frame, "frame-number", &n)) {
pr_err("arch_timer: Missing frame-number\n");
of_node_put(best_frame);
of_node_put(frame);
return;
}
if (cnttidr & CNTTIDR_VIRT(n)) {
of_node_put(best_frame);
best_frame = frame;
arch_timer_mem_use_virtual = true;
break;
}
of_node_put(best_frame);
best_frame = of_node_get(frame);
}
base = arch_counter_base = of_iomap(best_frame, 0);
if (!base) {
pr_err("arch_timer: Can't map frame's registers\n");
of_node_put(best_frame);
return;
}
if (arch_timer_mem_use_virtual)
irq = irq_of_parse_and_map(best_frame, 1);
else
irq = irq_of_parse_and_map(best_frame, 0);
of_node_put(best_frame);
if (!irq) {
pr_err("arch_timer: Frame missing %s irq",
arch_timer_mem_use_virtual ? "virt" : "phys");
return;
}
arch_timer_detect_rate(base, np);
arch_timer_mem_register(base, irq);
arch_timer_common_init();
}
CLOCKSOURCE_OF_DECLARE(armv7_arch_timer_mem, "arm,armv7-timer-mem",
arch_timer_mem_init);
|
markyzq/linux-3.14
|
drivers/clocksource/arm_arch_timer.c
|
C
|
gpl-2.0
| 20,205
|
/*
* This program source code file is part of KiCad, a free EDA CAD application.
*
* Copyright (C) 2012 Jean-Pierre Charras, jean-pierre.charras@ujf-grenoble.fr
* Copyright (C) 2012 SoftPLC Corporation, Dick Hollenbeck <dick@softplc.com>
* Copyright (C) 2012 Wayne Stambaugh <stambaughw@verizon.net>
* Copyright (C) 1992-2012 KiCad Developers, see AUTHORS.txt for contributors.
*
* 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, you may find one here:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
* or you may search the http://www.gnu.org website for the version 2 license,
* or you may write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
/**
* @file pcbnew/controle.cpp
*/
#include <fctsys.h>
#include <class_drawpanel.h>
#include <wxPcbStruct.h>
#include <pcbcommon.h>
#include <pcbnew_id.h>
#include <class_board.h>
#include <class_module.h>
#include <pcbnew.h>
#include <protos.h>
#include <collectors.h>
#include <menus_helpers.h>
//external functions used here:
extern bool Magnetize( PCB_EDIT_FRAME* frame, int aCurrentTool,
wxSize aGridSize, wxPoint on_grid, wxPoint* curpos );
/**
* Function AllAreModulesAndReturnSmallestIfSo
* tests that all items in the collection are MODULEs and if so, returns the
* smallest MODULE.
* @return BOARD_ITEM* - The smallest or NULL.
*/
static BOARD_ITEM* AllAreModulesAndReturnSmallestIfSo( GENERAL_COLLECTOR* aCollector )
{
#if 0 // Dick: this is not consistent with name of this function, and does not
// work correctly using 'M' (move hotkey) when another module's (2nd module) reference
// is under a module (first module) and you want to move the reference.
// Another way to fix this would be to
// treat module text as copper layer content, and put the module text into
// the primary list. I like the coded behavior best. If it breaks something
// perhaps you need a different test before calling this function, which should
// do what its name says it does.
int count = aCollector->GetPrimaryCount(); // try to use preferred layer
if( 0 == count ) count = aCollector->GetCount();
#else
int count = aCollector->GetCount();
#endif
for( int i = 0; i<count; ++i )
{
if( (*aCollector)[i]->Type() != PCB_MODULE_T )
return NULL;
}
// all are modules, now find smallest MODULE
int minDim = 0x7FFFFFFF;
int minNdx = 0;
for( int i = 0; i<count; ++i )
{
MODULE* module = (MODULE*) (*aCollector)[i];
int lx = module->GetBoundingBox().GetWidth();
int ly = module->GetBoundingBox().GetHeight();
int lmin = std::min( lx, ly );
if( lmin < minDim )
{
minDim = lmin;
minNdx = i;
}
}
return (*aCollector)[minNdx];
}
BOARD_ITEM* PCB_BASE_FRAME::PcbGeneralLocateAndDisplay( int aHotKeyCode )
{
BOARD_ITEM* item;
GENERAL_COLLECTORS_GUIDE guide = GetCollectorsGuide();
// Assign to scanList the proper item types desired based on tool type
// or hotkey that is in play.
const KICAD_T* scanList = NULL;
if( aHotKeyCode )
{
// @todo: add switch here and add calls to PcbGeneralLocateAndDisplay( int aHotKeyCode )
// when searching is needed from a hotkey handler
}
else if( GetToolId() == ID_NO_TOOL_SELECTED )
{
if( m_mainToolBar->GetToolToggled( ID_TOOLBARH_PCB_MODE_MODULE ) )
scanList = GENERAL_COLLECTOR::ModuleItems;
else
scanList = (DisplayOpt.DisplayZonesMode == 0) ?
GENERAL_COLLECTOR::AllBoardItems :
GENERAL_COLLECTOR::AllButZones;
}
else
{
switch( GetToolId() )
{
case ID_PCB_SHOW_1_RATSNEST_BUTT:
scanList = GENERAL_COLLECTOR::PadsOrModules;
break;
case ID_TRACK_BUTT:
scanList = GENERAL_COLLECTOR::Tracks;
break;
case ID_PCB_MODULE_BUTT:
scanList = GENERAL_COLLECTOR::ModuleItems;
break;
case ID_PCB_ZONES_BUTT:
case ID_PCB_KEEPOUT_AREA_BUTT:
scanList = GENERAL_COLLECTOR::Zones;
break;
default:
scanList = DisplayOpt.DisplayZonesMode == 0 ?
GENERAL_COLLECTOR::AllBoardItems :
GENERAL_COLLECTOR::AllButZones;
}
}
m_Collector->Collect( m_Pcb, scanList, RefPos( true ), guide );
#if 0
// debugging: print out the collected items, showing their priority order too.
for( int i = 0; i<m_Collector->GetCount(); ++i )
(*m_Collector)[i]->Show( 0, std::cout );
#endif
/* Remove redundancies: sometime, zones are found twice,
* because zones can be filled by overlapping segments (this is a fill option)
*/
time_t timestampzone = 0;
for( int ii = 0; ii < m_Collector->GetCount(); ii++ )
{
item = (*m_Collector)[ii];
if( item->Type() != PCB_ZONE_T )
continue;
// Found a TYPE ZONE
if( item->GetTimeStamp() == timestampzone ) // Remove it, redundant, zone already found
{
m_Collector->Remove( ii );
ii--;
}
else
{
timestampzone = item->GetTimeStamp();
}
}
if( m_Collector->GetCount() <= 1 )
{
item = (*m_Collector)[0];
SetCurItem( item );
}
// If the count is 2, and first item is a pad or module text, and the 2nd item is its
// parent module:
else if( m_Collector->GetCount() == 2
&& ( (*m_Collector)[0]->Type() == PCB_PAD_T || (*m_Collector)[0]->Type() ==
PCB_MODULE_TEXT_T )
&& (*m_Collector)[1]->Type() == PCB_MODULE_T && (*m_Collector)[0]->GetParent()==
(*m_Collector)[1] )
{
item = (*m_Collector)[0];
SetCurItem( item );
}
// if all are modules, find the smallest one among the primary choices
else if( ( item = AllAreModulesAndReturnSmallestIfSo( m_Collector ) ) != NULL )
{
SetCurItem( item );
}
else // we can't figure out which item user wants, do popup menu so user can choose
{
wxMenu itemMenu;
// Give a title to the selection menu. This is also a cancel menu item
wxMenuItem * item_title = new wxMenuItem( &itemMenu, -1, _( "Selection Clarification" ) );
#ifdef __WINDOWS__
wxFont bold_font( *wxNORMAL_FONT );
bold_font.SetWeight( wxFONTWEIGHT_BOLD );
bold_font.SetStyle( wxFONTSTYLE_ITALIC );
item_title->SetFont( bold_font );
#endif
itemMenu.Append( item_title );
itemMenu.AppendSeparator();
int limit = std::min( MAX_ITEMS_IN_PICKER, m_Collector->GetCount() );
for( int i = 0; i<limit; ++i )
{
wxString text;
item = (*m_Collector)[i];
text = item->GetSelectMenuText();
BITMAP_DEF xpm = item->GetMenuImage();
AddMenuItem( &itemMenu, ID_POPUP_PCB_ITEM_SELECTION_START + i, text, KiBitmap( xpm ) );
}
/* @todo: rather than assignment to true, these should be increment and decrement
* operators throughout _everywhere_.
* That way we can handle nesting.
* But I tried that and found there cases where the assignment to true (converted to
* a m_IgnoreMouseEvents++ )
* was not balanced with the -- (now m_IgnoreMouseEvents=false), so I had to revert.
* Somebody should track down these and make them balanced.
* m_canvas->SetIgnoreMouseEvents( true );
*/
// this menu's handler is void PCB_BASE_FRAME::ProcessItemSelection()
// and it calls SetCurItem() which in turn calls DisplayInfo() on the item.
m_canvas->SetAbortRequest( true ); // changed in false if an item is selected
PopupMenu( &itemMenu );
m_canvas->MoveCursorToCrossHair();
// The function ProcessItemSelection() has set the current item, return it.
if( m_canvas->GetAbortRequest() ) // Nothing selected
item = NULL;
else
item = GetCurItem();
}
return item;
}
void PCB_EDIT_FRAME::GeneralControl( wxDC* aDC, const wxPoint& aPosition, int aHotKey )
{
wxRealPoint gridSize;
wxPoint oldpos;
wxPoint pos = aPosition;
// when moving mouse, use the "magnetic" grid, unless the shift+ctrl keys is pressed
// for next cursor position
// ( shift or ctrl key down are PAN command with mouse wheel)
bool snapToGrid = true;
if( !aHotKey && wxGetKeyState( WXK_SHIFT ) && wxGetKeyState( WXK_CONTROL ) )
snapToGrid = false;
if( snapToGrid )
pos = GetNearestGridPosition( pos );
oldpos = GetCrossHairPosition();
gridSize = GetScreen()->GetGridSize();
switch( aHotKey )
{
case WXK_NUMPAD8:
case WXK_UP:
pos.y -= KiROUND( gridSize.y );
m_canvas->MoveCursor( pos );
break;
case WXK_NUMPAD2:
case WXK_DOWN:
pos.y += KiROUND( gridSize.y );
m_canvas->MoveCursor( pos );
break;
case WXK_NUMPAD4:
case WXK_LEFT:
pos.x -= KiROUND( gridSize.x );
m_canvas->MoveCursor( pos );
break;
case WXK_NUMPAD6:
case WXK_RIGHT:
pos.x += KiROUND( gridSize.x );
m_canvas->MoveCursor( pos );
break;
default:
break;
}
// Put cursor in new position, according to the zoom keys (if any).
SetCrossHairPosition( pos, snapToGrid );
/* Put cursor on grid or a pad centre if requested. If the tool DELETE is active the
* cursor is left off grid this is better to reach items to delete off grid,
*/
if( GetToolId() == ID_PCB_DELETE_ITEM_BUTT )
snapToGrid = false;
// Cursor is left off grid if no block in progress
if( GetScreen()->m_BlockLocate.GetState() != STATE_NO_BLOCK )
snapToGrid = true;
wxPoint curs_pos = pos;
wxSize igridsize;
igridsize.x = KiROUND( gridSize.x );
igridsize.y = KiROUND( gridSize.y );
if( Magnetize( this, GetToolId(), igridsize, curs_pos, &pos ) )
{
SetCrossHairPosition( pos, false );
}
else
{
// If there's no intrusion and DRC is active, we pass the cursor
// "as is", and let ShowNewTrackWhenMovingCursor figure out what to do.
if( !g_Drc_On || !g_CurrentTrackSegment ||
(BOARD_ITEM*)g_CurrentTrackSegment != this->GetCurItem() ||
!LocateIntrusion( m_Pcb->m_Track, g_CurrentTrackSegment,
GetScreen()->m_Active_Layer, RefPos( true ) ) )
{
SetCrossHairPosition( curs_pos, snapToGrid );
}
}
if( oldpos != GetCrossHairPosition() )
{
pos = GetCrossHairPosition();
SetCrossHairPosition( oldpos, false );
m_canvas->CrossHairOff( aDC );
SetCrossHairPosition( pos, false );
m_canvas->CrossHairOn( aDC );
if( m_canvas->IsMouseCaptured() )
{
#ifdef USE_WX_OVERLAY
wxDCOverlay oDC( m_overlay, (wxWindowDC*)aDC );
oDC.Clear();
m_canvas->CallMouseCapture( aDC, aPosition, false );
#else
m_canvas->CallMouseCapture( aDC, aPosition, true );
#endif
}
#ifdef USE_WX_OVERLAY
else
{
m_overlay.Reset();
}
#endif
}
if( aHotKey )
{
OnHotKey( aDC, aHotKey, aPosition );
}
UpdateStatusBar(); // Display new cursor coordinates
}
|
johnbeard/kicad-git
|
pcbnew/controle.cpp
|
C++
|
gpl-2.0
| 12,246
|
static int cmp1(const void *p, const void *q);
int main (int argc, char *argv[]) {
int i,y;
int NrOfLots;
int *lots;
if (argc < 5) {
printf("Dette programet splitter opp en urdil pasert på hovedlot.\n\n\tUsage:\n\tSplittUdfileByLot udfile filmedLoter filutenlotter lotnomre...\n\n");
exit(0);
}
NrOfLots = argc -4;
printf("NrOfLots: %i\n",NrOfLots);
//allokerer minne til en array over lottene
lots = malloc(sizeof(int) * NrOfLots);
//legger inn lotene
y = 0;
for (i=4;i<argc;i++) {
printf("lotnr %s\n",argv[i]);
lots[y] = atoi(argv[i]);
y++;
}
//sorterer lottene
qsort(lots,NrOfLots,sizeof(int),cmp1);
for(i=0;i<NrOfLots;i++) {
printf("lotsorted: %i\n",lots[i]);
}
free(lots);
}
static int cmp1(const void *p, const void *q)
{
return *(const int *) p - *(const int *) q;
}
|
bowlofstew/enterprise-search
|
src/SplittUdfileByLot/main.c
|
C
|
gpl-2.0
| 872
|
/* uinfo.cc: user info (uid, gid, etc...)
This file is part of Cygwin.
This software is a copyrighted work licensed under the terms of the
Cygwin license. Please consult the file "CYGWIN_LICENSE" for
details. */
#include "winsup.h"
#include <iptypes.h>
#include <lm.h>
#include <ntsecapi.h>
#include <wininet.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <wchar.h>
#include <sys/cygwin.h>
#include "cygerrno.h"
#include "pinfo.h"
#include "path.h"
#include "fhandler.h"
#include "dtable.h"
#include "cygheap.h"
#include "shared_info.h"
#include "registry.h"
#include "child_info.h"
#include "environ.h"
#include "tls_pbuf.h"
#include "miscfuncs.h"
#include "ntdll.h"
#include "ldap.h"
#include "cygserver_pwdgrp.h"
/* Initialize the part of cygheap_user that does not depend on files.
The information is used in shared.cc to create the shared user_info
region. Final initialization occurs in uinfo_init */
void
cygheap_user::init ()
{
WCHAR user_name[UNLEN + 1];
DWORD user_name_len = UNLEN + 1;
/* This method is only called if a Cygwin process gets started by a
native Win32 process. Try to get the username from the environment,
first USERNAME (Win32), then USER (POSIX). If that fails (which is
very unlikely), it only has an impact if we don't have an entry in
/etc/passwd for this user either. In that case the username sticks
to "unknown". Since this is called early in initialization, and
since we don't want to pull in a dependency to any other DLL except
ntdll and kernel32 at this early stage, don't call GetUserName,
GetUserNameEx, NetWkstaUserGetInfo, etc. */
if (GetEnvironmentVariableW (L"USERNAME", user_name, user_name_len)
|| GetEnvironmentVariableW (L"USER", user_name, user_name_len))
{
char mb_user_name[user_name_len = sys_wcstombs (NULL, 0, user_name) + 1];
sys_wcstombs (mb_user_name, user_name_len, user_name);
set_name (mb_user_name);
}
else
set_name ("unknown");
NTSTATUS status;
ULONG size;
PSECURITY_DESCRIPTOR psd;
status = NtQueryInformationToken (hProcToken, TokenPrimaryGroup,
&groups.pgsid, sizeof (cygsid), &size);
if (!NT_SUCCESS (status))
system_printf ("NtQueryInformationToken (TokenPrimaryGroup), %y", status);
/* Get the SID from current process and store it in effec_cygsid */
status = NtQueryInformationToken (hProcToken, TokenUser, &effec_cygsid,
sizeof (cygsid), &size);
if (!NT_SUCCESS (status))
{
system_printf ("NtQueryInformationToken (TokenUser), %y", status);
return;
}
/* Set token owner to the same value as token user */
status = NtSetInformationToken (hProcToken, TokenOwner, &effec_cygsid,
sizeof (cygsid));
if (!NT_SUCCESS (status))
debug_printf ("NtSetInformationToken (TokenOwner), %y", status);
/* Standard way to build a security descriptor with the usual DACL */
PSECURITY_ATTRIBUTES sa_buf = (PSECURITY_ATTRIBUTES) alloca (1024);
psd = (PSECURITY_DESCRIPTOR)
(sec_user_nih (sa_buf, sid()))->lpSecurityDescriptor;
BOOLEAN acl_exists, dummy;
TOKEN_DEFAULT_DACL dacl;
status = RtlGetDaclSecurityDescriptor (psd, &acl_exists, &dacl.DefaultDacl,
&dummy);
if (NT_SUCCESS (status) && acl_exists && dacl.DefaultDacl)
{
/* Set the default DACL and the process DACL */
status = NtSetInformationToken (hProcToken, TokenDefaultDacl, &dacl,
sizeof (dacl));
if (!NT_SUCCESS (status))
system_printf ("NtSetInformationToken (TokenDefaultDacl), %y", status);
if ((status = NtSetSecurityObject (NtCurrentProcess (),
DACL_SECURITY_INFORMATION, psd)))
system_printf ("NtSetSecurityObject, %y", status);
}
else
system_printf("Cannot get dacl, %E");
}
/* Check if sid is an enabled SID in the token group list of the current
effective token. Note that we only check for ENABLED groups, not for
INTEGRITY_ENABLED. The latter just doesn't make sense in our scenario
of using the group as primary group.
This needs careful checking should we use check_token_membership in other
circumstances. */
bool
check_token_membership (PSID sid)
{
NTSTATUS status;
ULONG size;
tmp_pathbuf tp;
PTOKEN_GROUPS groups = (PTOKEN_GROUPS) tp.w_get ();
/* If impersonated, use impersonation token. */
HANDLE tok = cygheap->user.issetuid () ? cygheap->user.primary_token ()
: hProcToken;
status = NtQueryInformationToken (tok, TokenGroups, groups, 2 * NT_MAX_PATH,
&size);
if (!NT_SUCCESS (status))
debug_printf ("NtQueryInformationToken (TokenGroups) %y", status);
else
{
for (DWORD pg = 0; pg < groups->GroupCount; ++pg)
if (RtlEqualSid (sid, groups->Groups[pg].Sid)
&& (groups->Groups[pg].Attributes & SE_GROUP_ENABLED))
return true;
}
return false;
}
static void
internal_getlogin (cygheap_user &user)
{
struct passwd *pwd;
struct group *pgrp, *grp, *grp2;
cyg_ldap cldap;
/* Fetch (and potentially generate) passwd and group entries for the user
and the primary group in the token. */
pwd = internal_getpwsid (user.sid (), &cldap);
pgrp = internal_getgrsid (user.groups.pgsid, &cldap);
if (!cygheap->pg.nss_cygserver_caching ())
internal_getgroups (0, NULL, &cldap);
if (!pwd)
debug_printf ("user not found in passwd DB");
else
{
cygsid gsid;
user.set_name (pwd->pw_name);
myself->uid = pwd->pw_uid;
myself->gid = pwd->pw_gid;
/* If the primary group in the passwd DB is different from the primary
group in the user token, we have to find the SID of that group and
try to override the token primary group. */
if (!pgrp || myself->gid != pgrp->gr_gid)
{
if (gsid.getfromgr (grp = internal_getgrgid (pwd->pw_gid, &cldap)))
{
/* We might have a group file with a group entry for the current
user's primary group, but the current user has no entry in
passwd. If so, pw_gid is taken from windows and might
disagree with gr_gid from the group file. Overwrite it. */
if ((grp2 = internal_getgrsid (gsid, &cldap)) && grp2 != grp)
myself->gid = pwd->pw_gid = grp2->gr_gid;
/* Set primary group to the group in /etc/passwd, *iff*
the group in /etc/passwd is in the token *and* enabled. */
if (gsid != user.groups.pgsid)
{
NTSTATUS status = STATUS_INVALID_PARAMETER;
if (check_token_membership (gsid))
{
status = NtSetInformationToken (hProcToken,
TokenPrimaryGroup,
&gsid, sizeof gsid);
if (!NT_SUCCESS (status))
debug_printf ("NtSetInformationToken "
"(TokenPrimaryGroup), %y", status);
}
if (!NT_SUCCESS (status))
{
/* Revert the primary group setting and override the
setting in the passwd entry. */
if (pgrp)
myself->gid = pwd->pw_gid = pgrp->gr_gid;
}
else
user.groups.pgsid = gsid;
clear_procimptoken ();
}
}
else
debug_printf ("group not found in group DB");
}
}
cygheap->user.ontherange (CH_HOME, pwd);
}
void
uinfo_init ()
{
if (child_proc_info && !cygheap->user.has_impersonation_tokens ())
return;
if (!child_proc_info)
internal_getlogin (cygheap->user); /* Set cygheap->user. */
/* Conditions must match those in spawn to allow starting child
processes with ruid != euid and rgid != egid. */
else if (cygheap->user.issetuid ()
&& cygheap->user.saved_uid == cygheap->user.real_uid
&& cygheap->user.saved_gid == cygheap->user.real_gid
&& !cygheap->user.groups.issetgroups ()
&& !cygheap->user.setuid_to_restricted)
{
cygheap->user.reimpersonate ();
return;
}
else
cygheap->user.close_impersonation_tokens ();
cygheap->user.saved_uid = cygheap->user.real_uid = myself->uid;
cygheap->user.saved_gid = cygheap->user.real_gid = myself->gid;
cygheap->user.external_token = NO_IMPERSONATION;
cygheap->user.internal_token = NO_IMPERSONATION;
cygheap->user.curr_primary_token = NO_IMPERSONATION;
cygheap->user.curr_imp_token = NO_IMPERSONATION;
cygheap->user.ext_token_is_restricted = false;
cygheap->user.curr_token_is_restricted = false;
cygheap->user.setuid_to_restricted = false;
cygheap->user.set_saved_sid (); /* Update the original sid */
cygheap->user.deimpersonate ();
}
extern "C" int
getlogin_r (char *name, size_t namesize)
{
const char *login = cygheap->user.name ();
size_t len = strlen (login) + 1;
if (len > namesize)
return ERANGE;
__try
{
strncpy (name, login, len);
}
__except (NO_ERROR)
{
return EFAULT;
}
__endtry
return 0;
}
extern "C" char *
getlogin (void)
{
static char username[UNLEN];
int ret = getlogin_r (username, UNLEN);
if (ret)
{
set_errno (ret);
return NULL;
}
return username;
}
extern "C" uid_t
getuid32 (void)
{
return cygheap->user.real_uid;
}
#ifdef __i386__
extern "C" __uid16_t
getuid (void)
{
return cygheap->user.real_uid;
}
#else
EXPORT_ALIAS (getuid32, getuid)
#endif
extern "C" gid_t
getgid32 (void)
{
return cygheap->user.real_gid;
}
#ifdef __i386__
extern "C" __gid16_t
getgid (void)
{
return cygheap->user.real_gid;
}
#else
EXPORT_ALIAS (getgid32, getgid)
#endif
extern "C" uid_t
geteuid32 (void)
{
return myself->uid;
}
#ifdef __i386__
extern "C" uid_t
geteuid (void)
{
return myself->uid;
}
#else
EXPORT_ALIAS (geteuid32, geteuid)
#endif
extern "C" gid_t
getegid32 (void)
{
return myself->gid;
}
#ifdef __i386__
extern "C" __gid16_t
getegid (void)
{
return myself->gid;
}
#else
EXPORT_ALIAS (getegid32, getegid)
#endif
/* Not quite right - cuserid can change, getlogin can't */
extern "C" char *
cuserid (char *src)
{
if (!src)
return getlogin ();
strcpy (src, getlogin ());
return src;
}
const char *
cygheap_user::ontherange (homebodies what, struct passwd *pw)
{
char homedrive_env_buf[3];
char *newhomedrive = NULL;
char *newhomepath = NULL;
tmp_pathbuf tp;
debug_printf ("what %d, pw %p", what, pw);
if (what == CH_HOME)
{
char *p;
if ((p = getenv ("HOME")))
debug_printf ("HOME is already in the environment %s", p);
if (!p)
{
if (pw && pw->pw_dir && *pw->pw_dir)
{
debug_printf ("Set HOME (from account db) to %s", pw->pw_dir);
setenv ("HOME", pw->pw_dir, 1);
}
else
{
char home[strlen (name ()) + 8];
debug_printf ("Set HOME to default /home/USER");
__small_sprintf (home, "/home/%s", name ());
setenv ("HOME", home, 1);
}
}
}
if (what != CH_HOME && homepath == NULL)
{
WCHAR wuser[UNLEN + 1];
WCHAR wlogsrv[INTERNET_MAX_HOST_NAME_LENGTH + 3];
PUSER_INFO_3 ui = NULL;
char *homepath_env_buf = tp.c_get ();
WCHAR profile[MAX_PATH];
WCHAR win_id[UNLEN + 1]; /* Large enough for SID */
homepath_env_buf[0] = homepath_env_buf[1] = '\0';
/* Use Cygwin home as HOMEDRIVE/HOMEPATH in the first place. This
should cover it completely, in theory. Still, it might be the
wrong choice in the long run, which might demand to set HOMEDRIVE/
HOMEPATH to the correct values per Windows. Keep the entire rest
of the code mainly for this reason, so switching is easy. */
pw = internal_getpwsid (sid ());
if (pw && pw->pw_dir && *pw->pw_dir)
cygwin_conv_path (CCP_POSIX_TO_WIN_A, pw->pw_dir, homepath_env_buf,
NT_MAX_PATH);
/* First fallback: Windows path per Windows user DB. */
else if (logsrv ())
{
sys_mbstowcs (wlogsrv, sizeof (wlogsrv) / sizeof (*wlogsrv),
logsrv ());
sys_mbstowcs (wuser, sizeof wuser / sizeof *wuser, winname ());
if (NetUserGetInfo (wlogsrv, wuser, 3, (LPBYTE *) &ui)
== NERR_Success)
{
if (ui->usri3_home_dir_drive && *ui->usri3_home_dir_drive)
{
sys_wcstombs (homepath_env_buf, NT_MAX_PATH,
ui->usri3_home_dir_drive);
strcat (homepath_env_buf, "\\");
}
else if (ui->usri3_home_dir && *ui->usri3_home_dir)
sys_wcstombs (homepath_env_buf, NT_MAX_PATH,
ui->usri3_home_dir);
}
if (ui)
NetApiBufferFree (ui);
}
/* Second fallback: Windows profile dir. */
if (!homepath_env_buf[0]
&& get_user_profile_directory (get_windows_id (win_id),
profile, MAX_PATH))
sys_wcstombs (homepath_env_buf, NT_MAX_PATH, profile);
/* Last fallback: Cygwin root dir. */
if (!homepath_env_buf[0])
cygwin_conv_path (CCP_POSIX_TO_WIN_A | CCP_ABSOLUTE,
"/", homepath_env_buf, NT_MAX_PATH);
if (homepath_env_buf[1] != ':')
{
newhomedrive = almost_null;
newhomepath = homepath_env_buf;
}
else
{
homedrive_env_buf[0] = homepath_env_buf[0];
homedrive_env_buf[1] = homepath_env_buf[1];
homedrive_env_buf[2] = '\0';
newhomedrive = homedrive_env_buf;
newhomepath = homepath_env_buf + 2;
}
}
if (newhomedrive && newhomedrive != homedrive)
cfree_and_set (homedrive, (newhomedrive == almost_null)
? almost_null : cstrdup (newhomedrive));
if (newhomepath && newhomepath != homepath)
cfree_and_set (homepath, cstrdup (newhomepath));
switch (what)
{
case CH_HOMEDRIVE:
return homedrive;
case CH_HOMEPATH:
return homepath;
default:
return homepath;
}
}
const char *
cygheap_user::test_uid (char *&what, const char *name, size_t namelen)
{
if (!what && !issetuid ())
what = getwinenveq (name, namelen, HEAP_STR);
return what;
}
const char *
cygheap_user::env_logsrv (const char *name, size_t namelen)
{
if (test_uid (plogsrv, name, namelen))
return plogsrv;
const char *mydomain = domain ();
const char *myname = winname ();
if (!mydomain || ascii_strcasematch (myname, "SYSTEM"))
return almost_null;
WCHAR wdomain[MAX_DOMAIN_NAME_LEN + 1];
WCHAR wlogsrv[INTERNET_MAX_HOST_NAME_LENGTH + 3];
sys_mbstowcs (wdomain, MAX_DOMAIN_NAME_LEN + 1, mydomain);
cfree_and_set (plogsrv, almost_null);
if (get_logon_server (wdomain, wlogsrv, DS_IS_FLAT_NAME))
sys_wcstombs_alloc (&plogsrv, HEAP_STR, wlogsrv);
return plogsrv;
}
const char *
cygheap_user::env_domain (const char *name, size_t namelen)
{
if (pwinname && test_uid (pdomain, name, namelen))
return pdomain;
DWORD ulen = UNLEN + 1;
WCHAR username[ulen];
DWORD dlen = MAX_DOMAIN_NAME_LEN + 1;
WCHAR userdomain[dlen];
SID_NAME_USE use;
cfree_and_set (pwinname, almost_null);
cfree_and_set (pdomain, almost_null);
if (!LookupAccountSidW (NULL, sid (), username, &ulen,
userdomain, &dlen, &use))
__seterrno ();
else
{
sys_wcstombs_alloc (&pwinname, HEAP_STR, username);
sys_wcstombs_alloc (&pdomain, HEAP_STR, userdomain);
}
return pdomain;
}
const char *
cygheap_user::env_userprofile (const char *name, size_t namelen)
{
if (test_uid (puserprof, name, namelen))
return puserprof;
/* User profile path is never longer than MAX_PATH. */
WCHAR profile[MAX_PATH];
WCHAR win_id[UNLEN + 1]; /* Large enough for SID */
cfree_and_set (puserprof, almost_null);
if (get_user_profile_directory (get_windows_id (win_id), profile, MAX_PATH))
sys_wcstombs_alloc (&puserprof, HEAP_STR, profile);
return puserprof;
}
const char *
cygheap_user::env_homepath (const char *name, size_t namelen)
{
return ontherange (CH_HOMEPATH);
}
const char *
cygheap_user::env_homedrive (const char *name, size_t namelen)
{
return ontherange (CH_HOMEDRIVE);
}
const char *
cygheap_user::env_name (const char *name, size_t namelen)
{
if (!test_uid (pwinname, name, namelen))
domain ();
return pwinname;
}
const char *
cygheap_user::env_systemroot (const char *name, size_t namelen)
{
if (!psystemroot)
{
int size = GetSystemWindowsDirectoryW (NULL, 0);
if (size > 0)
{
WCHAR wsystemroot[size];
size = GetSystemWindowsDirectoryW (wsystemroot, size);
if (size > 0)
sys_wcstombs_alloc (&psystemroot, HEAP_STR, wsystemroot);
}
if (size <= 0)
debug_printf ("GetSystemWindowsDirectoryW(), %E");
}
return psystemroot;
}
char *
pwdgrp::next_str (char c)
{
char *res = lptr;
lptr = strchrnul (lptr, c);
if (*lptr)
*lptr++ = '\0';
return res;
}
bool
pwdgrp::next_num (unsigned long& n)
{
char *p = next_str (':');
char *cp;
n = strtoul (p, &cp, 10);
return p != cp && !*cp;
}
char *
pwdgrp::add_line (char *eptr)
{
if (eptr)
{
if (curr_lines >= max_lines)
{
max_lines += 10;
pwdgrp_buf = crealloc_abort (pwdgrp_buf,
max_lines * pwdgrp_buf_elem_size);
}
lptr = eptr;
if (!(this->*parse) ())
return NULL;
curr_lines++;
}
return eptr;
}
void
cygheap_pwdgrp::init ()
{
pwd_cache.cygserver.init_pwd ();
pwd_cache.file.init_pwd ();
pwd_cache.win.init_pwd ();
grp_cache.cygserver.init_grp ();
grp_cache.file.init_grp ();
grp_cache.win.init_grp ();
/* Default settings (excluding fallbacks):
passwd: files db
group: files db
db_prefix: auto DISABLED
db_separator: + DISABLED
db_enum: cache builtin
*/
pwd_src = (NSS_SRC_FILES | NSS_SRC_DB);
grp_src = (NSS_SRC_FILES | NSS_SRC_DB);
prefix = NSS_PFX_AUTO;
separator[0] = L'+';
enums = (ENUM_CACHE | ENUM_BUILTIN);
enum_tdoms = NULL;
caching = true; /* INTERNAL ONLY */
}
#define NSS_NCMP(s) (!strncmp(c, (s), sizeof(s)-1))
#define NSS_CMP(s) (!strncmp(c, (s), sizeof(s)-1) \
&& strchr (" \t", c[sizeof(s)-1]))
/* The /etc/nsswitch.conf file is read exactly once by the root process of a
process tree. We can't afford methodical changes during the lifetime of a
process tree. */
void
cygheap_pwdgrp::nss_init_line (const char *line)
{
const char *c = line + strspn (line, " \t");
char *comment = strchr (c, '#');
if (comment)
*comment = '\0';
switch (*c)
{
case 'p':
case 'g':
{
uint32_t *src = NULL;
if (NSS_NCMP ("passwd:"))
src = &pwd_src;
else if (NSS_NCMP ("group:"))
src = &grp_src;
c = strchr (c, ':') + 1;
if (src)
{
*src = 0;
while (*(c += strspn (c, " \t")))
{
if (NSS_CMP ("files"))
{
*src |= NSS_SRC_FILES;
c += 5;
}
else if (NSS_CMP ("db"))
{
*src |= NSS_SRC_DB;
c += 2;
}
else
{
c += strcspn (c, " \t");
debug_printf ("Invalid nsswitch.conf content: %s", line);
}
}
if (*src == 0)
*src = (NSS_SRC_FILES | NSS_SRC_DB);
}
}
break;
case 'd':
if (!NSS_NCMP ("db_"))
{
debug_printf ("Invalid nsswitch.conf content: %s", line);
break;
}
c += 3;
#if 0 /* Disable setting prefix and separator from nsswitch.conf for now.
Remove if nobody complains too loudly. */
if (NSS_NCMP ("prefix:"))
{
c = strchr (c, ':') + 1;
c += strspn (c, " \t");
if (NSS_CMP ("auto"))
prefix = NSS_AUTO;
else if (NSS_CMP ("primary"))
prefix = NSS_PRIMARY;
else if (NSS_CMP ("always"))
prefix = NSS_ALWAYS;
else
debug_printf ("Invalid nsswitch.conf content: %s", line);
}
else if (NSS_NCMP ("separator:"))
{
c = strchr (c, ':') + 1;
c += strspn (c, " \t");
if ((unsigned char) *c <= 0x7f && *c != ':' && strchr (" \t", c[1]))
separator[0] = (unsigned char) *c;
else
debug_printf ("Invalid nsswitch.conf content: %s", line);
}
else
#endif
if (NSS_NCMP ("enum:"))
{
tmp_pathbuf tp;
char *tdoms = tp.c_get ();
char *td = tdoms;
int new_enums = ENUM_NONE;
td[0] = '\0';
c = strchr (c, ':') + 1;
c += strspn (c, " \t");
while (!strchr (" \t", *c))
{
const char *e = c + strcspn (c, " \t");
if (NSS_CMP ("none"))
new_enums = ENUM_NONE;
else if (NSS_CMP ("builtin"))
new_enums |= ENUM_BUILTIN;
else if (NSS_CMP ("cache"))
new_enums |= ENUM_CACHE;
else if (NSS_CMP ("files"))
new_enums |= ENUM_FILES;
else if (NSS_CMP ("local"))
new_enums |= ENUM_LOCAL;
else if (NSS_CMP ("primary"))
new_enums |= ENUM_PRIMARY;
else if (NSS_CMP ("alltrusted"))
new_enums |= ENUM_TDOMS | ENUM_TDOMS_ALL;
else if (NSS_CMP ("all"))
new_enums |= ENUM_ALL;
else
{
td = stpcpy (stpncpy (td, c, e - c), " ");
new_enums |= ENUM_TDOMS;
}
c = e;
c += strspn (c, " \t");
}
if ((new_enums & (ENUM_TDOMS | ENUM_TDOMS_ALL)) == ENUM_TDOMS)
{
if (td > tdoms)
{
PWCHAR spc;
sys_mbstowcs_alloc (&enum_tdoms, HEAP_BUF, tdoms);
/* Convert string to REG_MULTI_SZ-style. */
while ((spc = wcsrchr (enum_tdoms, L' ')))
*spc = L'\0';
}
else
new_enums &= ~(ENUM_TDOMS | ENUM_TDOMS_ALL);
}
enums = new_enums;
}
else
{
nss_scheme_t *scheme = NULL;
if (NSS_NCMP ("home:"))
scheme = home_scheme;
else if (NSS_NCMP ("shell:"))
scheme = shell_scheme;
else if (NSS_NCMP ("gecos:"))
scheme = gecos_scheme;
if (scheme)
{
for (uint16_t idx = 0; idx < NSS_SCHEME_MAX; ++idx)
scheme[idx].method = NSS_SCHEME_FALLBACK;
c = strchr (c, ':') + 1;
c += strspn (c, " \t");
for (uint16_t idx = 0; *c && idx < NSS_SCHEME_MAX; ++idx)
{
if (NSS_CMP ("windows"))
scheme[idx].method = NSS_SCHEME_WINDOWS;
else if (NSS_CMP ("cygwin"))
scheme[idx].method = NSS_SCHEME_CYGWIN;
else if (NSS_CMP ("unix"))
scheme[idx].method = NSS_SCHEME_UNIX;
else if (NSS_CMP ("desc"))
scheme[idx].method = NSS_SCHEME_DESC;
else if (NSS_NCMP ("/"))
{
const char *e = c + strcspn (c, " \t");
scheme[idx].method = NSS_SCHEME_PATH;
sys_mbstowcs_alloc (&scheme[idx].attrib, HEAP_STR,
c, e - c);
}
else if (NSS_NCMP ("@") && isalnum ((unsigned) *++c))
{
const char *e = c + strcspn (c, " \t");
scheme[idx].method = NSS_SCHEME_FREEATTR;
sys_mbstowcs_alloc (&scheme[idx].attrib, HEAP_STR,
c, e - c);
}
else
{
debug_printf ("Invalid nsswitch.conf content: %s", line);
--idx;
}
c += strcspn (c, " \t");
c += strspn (c, " \t");
}
}
else
debug_printf ("Invalid nsswitch.conf content: %s", line);
}
break;
case '\0':
break;
default:
debug_printf ("Invalid nsswitch.conf content: %s", line);
break;
}
}
static char *
fetch_windows_home (cyg_ldap *pldap, PUSER_INFO_3 ui, cygpsid &sid,
PCWSTR dnsdomain)
{
PCWSTR home_from_db = NULL;
char *home = NULL;
if (pldap)
{
if (pldap->fetch_ad_account (sid, false, dnsdomain))
{
#if 0
/* Disable preferring homeDrive for now. The drive letter may not
be available when it's needed. */
home_from_db = pldap->get_string_attribute (L"homeDrive");
if (!home_from_db || !*home_from_db)
#endif
home_from_db = pldap->get_string_attribute (L"homeDirectory");
}
}
else if (ui)
{
#if 0
/* Ditto. */
if (ui->usri3_home_dir_drive && *ui->usri3_home_dir_drive)
home_from_db = ui->usri3_home_dir_drive;
else
#endif
if (ui->usri3_home_dir && *ui->usri3_home_dir)
home_from_db = ui->usri3_home_dir;
}
if (home_from_db && *home_from_db)
home = (char *) cygwin_create_path (CCP_WIN_W_TO_POSIX, home_from_db);
else
{
/* The db fields are empty, so we have to evaluate the local profile
path, which is the same thing as the default home directory on
Windows. So what we do here is to try to find out if the user
already has a profile on this machine.
Note that we don't try to generate the profile if it doesn't exist.
Think what would happen if we actually have the permissions to do
so and call getpwent... in a domain environment. The problem is,
of course, that we can't know the profile path, unless the OS
created it.
The only reason this could occur is if a user account, which never
logged on to the machine before, tries to logon via a Cygwin service
like sshd. */
WCHAR profile[MAX_PATH];
WCHAR sidstr[128];
if (get_user_profile_directory (sid.string (sidstr), profile, MAX_PATH))
home = (char *) cygwin_create_path (CCP_WIN_W_TO_POSIX, profile);
}
return home;
}
/* Local SAM accounts have only a handful attributes available to home users.
Therefore, allow to fetch additional passwd/group attributes from the
"Comment" field in XML short style. For symmetry, this is also allowed
from the equivalent "description" AD attribute. */
static char *
fetch_from_description (PCWSTR desc, PCWSTR search, size_t len)
{
PWCHAR s, e;
char *ret = NULL;
if ((s = wcsstr (desc, L"<cygwin ")) && (e = wcsstr (s + 8, L"/>")))
{
s += 8;
while (s && s < e)
{
while (*s == L' ')
++s;
if (!wcsncmp (s, search, len)) /* Found what we're searching? */
{
s += len;
if ((e = wcschr (s, L'"')))
{
sys_wcstombs_alloc (&ret, HEAP_NOTHEAP, s, e - s);
s = e + 1;
}
break;
}
else /* Skip the current foo="bar" string. */
if ((s = wcschr (s, L'"')) && (s = wcschr (s + 1, L'"')))
++s;
}
}
return ret;
}
static char *
fetch_from_path (cyg_ldap *pldap, PUSER_INFO_3 ui, cygpsid &sid, PCWSTR str,
PCWSTR dom, PCWSTR dnsdomain, PCWSTR name, bool full_qualified)
{
tmp_pathbuf tp;
PWCHAR wpath = tp.w_get ();
PWCHAR w = wpath;
PWCHAR we = wpath + NT_MAX_PATH - 1;
char *home;
char *ret = NULL;
while (*str && w < we)
{
if (*str != L'%')
*w++ = *str++;
else
{
switch (*++str)
{
case L'u':
if (full_qualified)
{
w = wcpncpy (w, dom, we - w);
if (w < we)
*w++ = cygheap->pg.nss_separator ()[0];
}
w = wcpncpy (w, name, we - w);
break;
case L'U':
w = wcpncpy (w, name, we - w);
break;
case L'D':
w = wcpncpy (w, dom, we - w);
break;
case L'H':
home = fetch_windows_home (pldap, ui, sid, dnsdomain);
if (home)
{
/* Drop one leading slash to accommodate home being an
absolute path. We don't check for broken usage of
%H here, of course. */
if (w > wpath && w[-1] == L'/')
--w;
w += sys_mbstowcs (w, we - w, home) - 1;
free (home);
}
break;
case L'_':
*w++ = L' ';
break;
default:
*w++ = *str;
break;
}
++str;
}
}
*w = L'\0';
sys_wcstombs_alloc (&ret, HEAP_NOTHEAP, wpath);
return ret;
}
char *
cygheap_pwdgrp::get_home (cyg_ldap *pldap, cygpsid &sid, PCWSTR dom,
PCWSTR dnsdomain, PCWSTR name, bool full_qualified)
{
PWCHAR val;
char *home = NULL;
for (uint16_t idx = 0; !home && idx < NSS_SCHEME_MAX; ++idx)
{
switch (home_scheme[idx].method)
{
case NSS_SCHEME_FALLBACK:
return NULL;
case NSS_SCHEME_WINDOWS:
if (pldap->fetch_ad_account (sid, false, dnsdomain))
home = fetch_windows_home (pldap, NULL, sid, dnsdomain);
break;
case NSS_SCHEME_CYGWIN:
if (pldap->fetch_ad_account (sid, false, dnsdomain))
{
val = pldap->get_string_attribute (L"cygwinHome");
if (val && *val)
sys_wcstombs_alloc (&home, HEAP_NOTHEAP, val);
}
break;
case NSS_SCHEME_UNIX:
if (pldap->fetch_ad_account (sid, false, dnsdomain))
{
val = pldap->get_string_attribute (L"unixHomeDirectory");
if (val && *val)
sys_wcstombs_alloc (&home, HEAP_NOTHEAP, val);
}
break;
case NSS_SCHEME_DESC:
if (pldap->fetch_ad_account (sid, false, dnsdomain))
{
val = pldap->get_string_attribute (L"description");
if (val && *val)
home = fetch_from_description (val, L"home=\"", 6);
}
break;
case NSS_SCHEME_PATH:
home = fetch_from_path (pldap, NULL, sid, home_scheme[idx].attrib,
dom, dnsdomain, name, full_qualified);
break;
case NSS_SCHEME_FREEATTR:
if (pldap->fetch_ad_account (sid, false, dnsdomain))
{
val = pldap->get_string_attribute (home_scheme[idx].attrib);
if (val && *val)
{
if (isdrive (val) || *val == '\\')
home = (char *)
cygwin_create_path (CCP_WIN_W_TO_POSIX, val);
else
sys_wcstombs_alloc (&home, HEAP_NOTHEAP, val);
}
}
break;
}
}
return home;
}
char *
cygheap_pwdgrp::get_home (PUSER_INFO_3 ui, cygpsid &sid, PCWSTR dom,
PCWSTR name, bool full_qualified)
{
char *home = NULL;
for (uint16_t idx = 0; !home && idx < NSS_SCHEME_MAX; ++idx)
{
switch (home_scheme[idx].method)
{
case NSS_SCHEME_FALLBACK:
return NULL;
case NSS_SCHEME_WINDOWS:
home = fetch_windows_home (NULL, ui, sid, NULL);
break;
case NSS_SCHEME_CYGWIN:
case NSS_SCHEME_UNIX:
case NSS_SCHEME_FREEATTR:
break;
case NSS_SCHEME_DESC:
if (ui)
home = fetch_from_description (ui->usri3_comment, L"home=\"", 6);
break;
case NSS_SCHEME_PATH:
home = fetch_from_path (NULL, ui, sid, home_scheme[idx].attrib,
dom, NULL, name, full_qualified);
break;
}
}
return home;
}
char *
cygheap_pwdgrp::get_shell (cyg_ldap *pldap, cygpsid &sid, PCWSTR dom,
PCWSTR dnsdomain, PCWSTR name, bool full_qualified)
{
PWCHAR val;
char *shell = NULL;
for (uint16_t idx = 0; !shell && idx < NSS_SCHEME_MAX; ++idx)
{
switch (shell_scheme[idx].method)
{
case NSS_SCHEME_FALLBACK:
return NULL;
case NSS_SCHEME_WINDOWS:
break;
case NSS_SCHEME_CYGWIN:
if (pldap->fetch_ad_account (sid, false, dnsdomain))
{
val = pldap->get_string_attribute (L"cygwinShell");
if (val && *val)
sys_wcstombs_alloc (&shell, HEAP_NOTHEAP, val);
}
break;
case NSS_SCHEME_UNIX:
if (pldap->fetch_ad_account (sid, false, dnsdomain))
{
val = pldap->get_string_attribute (L"loginShell");
if (val && *val)
sys_wcstombs_alloc (&shell, HEAP_NOTHEAP, val);
}
break;
case NSS_SCHEME_DESC:
if (pldap->fetch_ad_account (sid, false, dnsdomain))
{
val = pldap->get_string_attribute (L"description");
if (val && *val)
shell = fetch_from_description (val, L"shell=\"", 7);
}
break;
case NSS_SCHEME_PATH:
shell = fetch_from_path (pldap, NULL, sid, shell_scheme[idx].attrib,
dom, dnsdomain, name, full_qualified);
break;
case NSS_SCHEME_FREEATTR:
if (pldap->fetch_ad_account (sid, false, dnsdomain))
{
val = pldap->get_string_attribute (shell_scheme[idx].attrib);
if (val && *val)
{
if (isdrive (val) || *val == '\\')
shell = (char *)
cygwin_create_path (CCP_WIN_W_TO_POSIX, val);
else
sys_wcstombs_alloc (&shell, HEAP_NOTHEAP, val);
}
}
break;
}
}
return shell;
}
char *
cygheap_pwdgrp::get_shell (PUSER_INFO_3 ui, cygpsid &sid, PCWSTR dom,
PCWSTR name, bool full_qualified)
{
char *shell = NULL;
for (uint16_t idx = 0; !shell && idx < NSS_SCHEME_MAX; ++idx)
{
switch (shell_scheme[idx].method)
{
case NSS_SCHEME_FALLBACK:
return NULL;
case NSS_SCHEME_WINDOWS:
case NSS_SCHEME_CYGWIN:
case NSS_SCHEME_UNIX:
case NSS_SCHEME_FREEATTR:
break;
case NSS_SCHEME_DESC:
if (ui)
shell = fetch_from_description (ui->usri3_comment, L"shell=\"", 7);
break;
case NSS_SCHEME_PATH:
shell = fetch_from_path (NULL, ui, sid, shell_scheme[idx].attrib,
dom, NULL, name, full_qualified);
break;
}
}
return shell;
}
/* Helper function to replace colons with semicolons in pw_gecos field. */
static inline void
colon_to_semicolon (char *str)
{
char *cp = str;
while ((cp = strchr (cp, L':')) != NULL)
*cp++ = L';';
}
char *
cygheap_pwdgrp::get_gecos (cyg_ldap *pldap, cygpsid &sid, PCWSTR dom,
PCWSTR dnsdomain, PCWSTR name, bool full_qualified)
{
PWCHAR val;
char *gecos = NULL;
for (uint16_t idx = 0; !gecos && idx < NSS_SCHEME_MAX; ++idx)
{
switch (gecos_scheme[idx].method)
{
case NSS_SCHEME_FALLBACK:
return NULL;
case NSS_SCHEME_WINDOWS:
if (pldap->fetch_ad_account (sid, false, dnsdomain))
{
val = pldap->get_string_attribute (L"displayName");
if (val && *val)
sys_wcstombs_alloc (&gecos, HEAP_NOTHEAP, val);
}
break;
case NSS_SCHEME_CYGWIN:
if (pldap->fetch_ad_account (sid, false, dnsdomain))
{
val = pldap->get_string_attribute (L"cygwinGecos");
if (val && *val)
sys_wcstombs_alloc (&gecos, HEAP_NOTHEAP, val);
}
break;
case NSS_SCHEME_UNIX:
if (pldap->fetch_ad_account (sid, false, dnsdomain))
{
val = pldap->get_string_attribute (L"gecos");
if (val && *val)
sys_wcstombs_alloc (&gecos, HEAP_NOTHEAP, val);
}
break;
case NSS_SCHEME_DESC:
if (pldap->fetch_ad_account (sid, false, dnsdomain))
{
val = pldap->get_string_attribute (L"description");
if (val && *val)
gecos = fetch_from_description (val, L"gecos=\"", 7);
}
break;
case NSS_SCHEME_PATH:
gecos = fetch_from_path (pldap, NULL, sid,
gecos_scheme[idx].attrib + 1,
dom, dnsdomain, name, full_qualified);
break;
case NSS_SCHEME_FREEATTR:
if (pldap->fetch_ad_account (sid, false, dnsdomain))
{
val = pldap->get_string_attribute (gecos_scheme[idx].attrib);
if (val && *val)
sys_wcstombs_alloc (&gecos, HEAP_NOTHEAP, val);
}
break;
}
}
if (gecos)
colon_to_semicolon (gecos);
return gecos;
}
char *
cygheap_pwdgrp::get_gecos (PUSER_INFO_3 ui, cygpsid &sid, PCWSTR dom,
PCWSTR name, bool full_qualified)
{
char *gecos = NULL;
for (uint16_t idx = 0; !gecos && idx < NSS_SCHEME_MAX; ++idx)
{
switch (gecos_scheme[idx].method)
{
case NSS_SCHEME_FALLBACK:
return NULL;
case NSS_SCHEME_WINDOWS:
if (ui && ui->usri3_full_name && *ui->usri3_full_name)
sys_wcstombs_alloc (&gecos, HEAP_NOTHEAP, ui->usri3_full_name);
break;
case NSS_SCHEME_CYGWIN:
case NSS_SCHEME_UNIX:
case NSS_SCHEME_FREEATTR:
break;
case NSS_SCHEME_DESC:
if (ui)
gecos = fetch_from_description (ui->usri3_comment, L"gecos=\"", 7);
break;
case NSS_SCHEME_PATH:
gecos = fetch_from_path (NULL, ui, sid, gecos_scheme[idx].attrib + 1,
dom, NULL, name, full_qualified);
break;
}
}
if (gecos)
colon_to_semicolon (gecos);
return gecos;
}
void
cygheap_pwdgrp::_nss_init ()
{
UNICODE_STRING path;
OBJECT_ATTRIBUTES attr;
NT_readline rl;
tmp_pathbuf tp;
char *buf = tp.c_get ();
PCWSTR rel_path = L"\\etc\\nsswitch.conf";
path.Length = cygheap->installation_root.Length
+ wcslen (rel_path) * sizeof (WCHAR);
path.MaximumLength = path.Length + sizeof (WCHAR);
path.Buffer = (PWCHAR) alloca (path.MaximumLength);
wcpcpy (wcpcpy (path.Buffer, cygheap->installation_root.Buffer), rel_path);
InitializeObjectAttributes (&attr, &path, OBJ_CASE_INSENSITIVE,
NULL, NULL);
if (rl.init (&attr, buf, NT_MAX_PATH))
while ((buf = rl.gets ()))
nss_init_line (buf);
nss_inited = true;
}
/* Override the ParentIndex value of the PDS_DOMAIN_TRUSTSW entry with the
PosixOffset. */
#define PosixOffset ParentIndex
bool
cygheap_domain_info::init ()
{
HANDLE lsa;
NTSTATUS status;
ULONG ret;
/* We *have* to copy the information. Apart from our wish to have the
stuff in the cygheap, even when not calling LsaFreeMemory on the result,
the data will be overwritten later. From what I gather, the information
is, in fact, stored on the stack. */
PPOLICY_DNS_DOMAIN_INFO pdom;
PPOLICY_ACCOUNT_DOMAIN_INFO adom;
PDS_DOMAIN_TRUSTSW td;
ULONG tdom_cnt;
if (adom_name)
return true;
lsa = lsa_open_policy (NULL, POLICY_VIEW_LOCAL_INFORMATION);
if (!lsa)
{
system_printf ("lsa_open_policy(NULL) failed");
return false;
}
/* Fetch primary domain information from local LSA. */
status = LsaQueryInformationPolicy (lsa, PolicyDnsDomainInformation,
(PVOID *) &pdom);
if (status != STATUS_SUCCESS)
{
system_printf ("LsaQueryInformationPolicy(Primary) %y", status);
return false;
}
/* Copy primary domain info to cygheap. */
pdom_name = cwcsdup (pdom->Name.Buffer);
pdom_dns_name = pdom->DnsDomainName.Length
? cwcsdup (pdom->DnsDomainName.Buffer) : NULL;
pdom_sid = pdom->Sid;
LsaFreeMemory (pdom);
/* Fetch account domain information from local LSA. */
status = LsaQueryInformationPolicy (lsa, PolicyAccountDomainInformation,
(PVOID *) &adom);
if (status != STATUS_SUCCESS)
{
system_printf ("LsaQueryInformationPolicy(Account) %y", status);
return false;
}
/* Copy account domain info to cygheap. If we're running on a DC the account
domain is identical to the primary domain. This leads to confusion when
trying to compute the uid/gid values. Therefore we invalidate the account
domain name if we're running on a DC. */
adom_sid = adom->DomainSid;
adom_name = cwcsdup (pdom_sid == adom_sid ? L"@" : adom->DomainName.Buffer);
LsaFreeMemory (adom);
lsa_close_policy (lsa);
if (cygheap->dom.member_machine ())
{
ret = DsEnumerateDomainTrustsW (NULL, DS_DOMAIN_DIRECT_INBOUND
| DS_DOMAIN_DIRECT_OUTBOUND
| DS_DOMAIN_IN_FOREST,
&td, &tdom_cnt);
if (ret != ERROR_SUCCESS)
{
SetLastError (ret);
debug_printf ("DsEnumerateDomainTrusts: %E");
return true;
}
if (tdom_cnt == 0)
{
return true;
}
/* Copy trusted domain info to cygheap, setting PosixOffset on the fly. */
tdom = (PDS_DOMAIN_TRUSTSW)
cmalloc_abort (HEAP_BUF, tdom_cnt * sizeof (DS_DOMAIN_TRUSTSW));
memcpy (tdom, td, tdom_cnt * sizeof (DS_DOMAIN_TRUSTSW));
for (ULONG idx = 0; idx < tdom_cnt; ++idx)
{
/* Copy... */
tdom[idx].NetbiosDomainName = cwcsdup (td[idx].NetbiosDomainName);
/* DnsDomainName as well as DomainSid can be NULL. The reason is
usually a domain of type TRUST_TYPE_DOWNLEVEL. This can be an
old pre-AD domain, or a Netware domain, etc. If DnsDomainName
is NULL, just set it to NetbiosDomainName. This simplifies
subsequent code which doesn't have to check for a NULL pointer. */
tdom[idx].DnsDomainName = td[idx].DnsDomainName
? cwcsdup (td[idx].DnsDomainName)
: tdom[idx].NetbiosDomainName;
if (td[idx].DomainSid)
{
ULONG len = RtlLengthSid (td[idx].DomainSid);
tdom[idx].DomainSid = cmalloc_abort(HEAP_BUF, len);
RtlCopySid (len, tdom[idx].DomainSid, td[idx].DomainSid);
}
/* ...and set PosixOffset to 0. This */
tdom[idx].PosixOffset = 0;
}
NetApiBufferFree (td);
tdom_count = tdom_cnt;
}
/* If we have Microsoft Client for NFS installed, we make use of a name
mapping server. This can be either Active Directory to map uids/gids
directly to Windows SIDs, or an AD LDS or other RFC 2307 compatible
identity store. The name of the mapping domain can be fetched from the
registry key created by the NFS client installation and entered by the
user via nfsadmin or the "Services For NFS" MMC snap-in.
Reference:
http://blogs.technet.com/b/filecab/archive/2012/10/09/nfs-identity-mapping-in-windows-server-2012.aspx
Note that we neither support UNMP nor local passwd/group file mapping,
nor UUUA.
This function returns the mapping server from the aforementioned registry
key, or, if none is configured, NULL, which will be resolved to the
primary domain of the machine by the ldap_init function.
The latter is useful to get an RFC 2307 mapping for Samba UNIX accounts,
even if no NFS name mapping is configured on the machine. Fortunately,
the posixAccount and posixGroup schemas are already available in the
Active Directory default setup. */
reg_key reg (HKEY_LOCAL_MACHINE, KEY_READ | KEY_WOW64_64KEY,
L"SOFTWARE", L"Microsoft", L"ServicesForNFS", NULL);
if (!reg.error ())
{
DWORD rfc2307 = reg.get_dword (L"Rfc2307", 0);
if (rfc2307)
{
rfc2307_domain_buf = (PWCHAR) ccalloc_abort (HEAP_STR, 257,
sizeof (WCHAR));
reg.get_string (L"Rfc2307Domain", rfc2307_domain_buf, 257, L"");
if (!rfc2307_domain_buf[0])
{
cfree (rfc2307_domain_buf);
rfc2307_domain_buf = NULL;
}
}
}
return true;
}
PDS_DOMAIN_TRUSTSW
cygheap_domain_info::add_domain (PCWSTR domain, PSID sid)
{
PDS_DOMAIN_TRUSTSW new_tdom;
cygsid tsid (sid);
new_tdom = (PDS_DOMAIN_TRUSTSW) crealloc (tdom, (tdom_count + 1)
* sizeof (DS_DOMAIN_TRUSTSW));
if (!new_tdom)
return NULL;
tdom = new_tdom;
new_tdom = &tdom[tdom_count];
new_tdom->DnsDomainName = new_tdom->NetbiosDomainName = cwcsdup (domain);
--*RtlSubAuthorityCountSid (tsid);
ULONG len = RtlLengthSid (tsid);
new_tdom->DomainSid = cmalloc_abort(HEAP_BUF, len);
RtlCopySid (len, new_tdom->DomainSid, tsid);
new_tdom->PosixOffset = 0;
++tdom_count;
return new_tdom;
}
/* Per session, so it changes potentially when switching the user context. */
static cygsid logon_sid ("");
static void
get_logon_sid ()
{
if (PSID (logon_sid) == NO_SID)
{
NTSTATUS status;
ULONG size;
tmp_pathbuf tp;
PTOKEN_GROUPS groups = (PTOKEN_GROUPS) tp.w_get ();
status = NtQueryInformationToken (hProcToken, TokenGroups, groups,
2 * NT_MAX_PATH, &size);
if (!NT_SUCCESS (status))
debug_printf ("NtQueryInformationToken (TokenGroups) %y", status);
else
{
for (DWORD pg = 0; pg < groups->GroupCount; ++pg)
if (groups->Groups[pg].Attributes & SE_GROUP_LOGON_ID)
{
logon_sid = groups->Groups[pg].Sid;
break;
}
}
}
}
/* Fetch special AzureAD group, which is part of the token group list but
*not* recognized by LookupAccountSid (ERROR_NONE_MAPPED). */
static cygsid azure_grp_sid ("");
static void
get_azure_grp_sid ()
{
if (PSID (azure_grp_sid) == NO_SID)
{
NTSTATUS status;
ULONG size;
tmp_pathbuf tp;
PTOKEN_GROUPS groups = (PTOKEN_GROUPS) tp.w_get ();
status = NtQueryInformationToken (hProcToken, TokenGroups, groups,
2 * NT_MAX_PATH, &size);
if (!NT_SUCCESS (status))
debug_printf ("NtQueryInformationToken (TokenGroups) %y", status);
else
{
for (DWORD pg = 0; pg < groups->GroupCount; ++pg)
if (sid_id_auth (groups->Groups[pg].Sid) == 12)
{
azure_grp_sid = groups->Groups[pg].Sid;
break;
}
}
}
}
void *
pwdgrp::add_account_post_fetch (char *line, bool lock)
{
void *ret = NULL;
if (line)
{
if (lock)
pglock.init ("pglock")->acquire ();
if (add_line (line))
ret = ((char *) pwdgrp_buf) + (curr_lines - 1) * pwdgrp_buf_elem_size;
if (lock)
pglock.release ();
}
return ret;
}
void *
pwdgrp::add_account_from_file (cygpsid &sid)
{
if (!path.MaximumLength)
return NULL;
fetch_user_arg_t arg;
arg.type = SID_arg;
arg.sid = &sid;
char *line = fetch_account_from_file (arg);
return (struct passwd *) add_account_post_fetch (line, true);
}
void *
pwdgrp::add_account_from_file (const char *name)
{
if (!path.MaximumLength)
return NULL;
fetch_user_arg_t arg;
arg.type = NAME_arg;
arg.name = name;
char *line = fetch_account_from_file (arg);
return (struct passwd *) add_account_post_fetch (line, true);
}
void *
pwdgrp::add_account_from_file (uint32_t id)
{
if (!path.MaximumLength)
return NULL;
fetch_user_arg_t arg;
arg.type = ID_arg;
arg.id = id;
char *line = fetch_account_from_file (arg);
return (struct passwd *) add_account_post_fetch (line, true);
}
void *
pwdgrp::add_account_from_windows (cygpsid &sid, cyg_ldap *pldap)
{
fetch_user_arg_t arg;
arg.type = SID_arg;
arg.sid = &sid;
char *line = fetch_account_from_windows (arg, pldap);
if (!line)
return NULL;
return add_account_post_fetch (line, true);
}
void *
pwdgrp::add_account_from_windows (const char *name, cyg_ldap *pldap)
{
fetch_user_arg_t arg;
arg.type = NAME_arg;
arg.name = name;
char *line = fetch_account_from_windows (arg, pldap);
if (!line)
return NULL;
return add_account_post_fetch (line, true);
}
void *
pwdgrp::add_account_from_windows (uint32_t id, cyg_ldap *pldap)
{
fetch_user_arg_t arg;
arg.type = ID_arg;
arg.id = id;
char *line = fetch_account_from_windows (arg, pldap);
if (!line)
return NULL;
return add_account_post_fetch (line, true);
}
/* Called from internal_getgrfull, in turn called from internal_getgroups. */
struct group *
pwdgrp::add_group_from_windows (fetch_acc_t &full_acc, cyg_ldap *pldap)
{
fetch_user_arg_t arg;
arg.type = FULL_acc_arg;
arg.full_acc = &full_acc;
char *line = fetch_account_from_windows (arg, pldap);
if (!line)
return NULL;
return (struct group *) add_account_post_fetch (line, true);
}
/* Check if file exists and if it has been written to since last checked.
If file has been changed, invalidate the current cache.
If the file doesn't exist when this function is called the first time,
by the first Cygwin process in a process tree, the file will never be
visited again by any process in this process tree. This is important,
because we cannot allow a change of UID/GID values for the lifetime
of a process tree.
If the file gets deleted or unreadable, the file cache will stay in
place, but we won't try to read new accounts from the file.
The return code indicates to the calling function if the file exists. */
bool
pwdgrp::check_file ()
{
FILE_BASIC_INFORMATION fbi;
NTSTATUS status;
if (!path.Buffer)
{
PCWSTR rel_path = is_group () ? L"\\etc\\group" : L"\\etc\\passwd";
path.Length = cygheap->installation_root.Length
+ wcslen (rel_path) * sizeof (WCHAR);
path.MaximumLength = path.Length + sizeof (WCHAR);
path.Buffer = (PWCHAR) cmalloc_abort (HEAP_BUF, path.MaximumLength);
wcpcpy (wcpcpy (path.Buffer, cygheap->installation_root.Buffer),
rel_path);
InitializeObjectAttributes (&attr, &path, OBJ_CASE_INSENSITIVE,
NULL, NULL);
}
else if (path.MaximumLength == 0) /* Indicates that the file doesn't exist. */
return false;
status = NtQueryAttributesFile (&attr, &fbi);
if (!NT_SUCCESS (status))
{
if (last_modified.QuadPart)
last_modified.QuadPart = 0LL;
else
path.MaximumLength = 0;
return false;
}
if (fbi.LastWriteTime.QuadPart > last_modified.QuadPart)
{
last_modified.QuadPart = fbi.LastWriteTime.QuadPart;
if (curr_lines > 0)
{
pglock.init ("pglock")->acquire ();
int curr = curr_lines;
curr_lines = 0;
for (int i = 0; i < curr; ++i)
cfree (is_group () ? this->group ()[i].g.gr_name
: this->passwd ()[i].p.pw_name);
pglock.release ();
}
}
return true;
}
char *
pwdgrp::fetch_account_from_line (fetch_user_arg_t &arg, const char *line)
{
char *p, *e;
switch (arg.type)
{
case SID_arg:
/* Ignore fields, just scan for SID string. */
if (!(p = strstr (line, arg.name)) || p[arg.len] != ':')
return NULL;
break;
case NAME_arg:
/* First field is always name. */
if (!strncasematch (line, arg.name, arg.len) || line[arg.len] != ':')
return NULL;
break;
case ID_arg:
/* Skip to third field. */
if (!(p = strchr (line, ':')) || !(p = strchr (p + 1, ':')))
return NULL;
if (strtoul (p + 1, &e, 10) != arg.id || !e || *e != ':')
return NULL;
break;
default:
return NULL;
}
return cstrdup (line);
}
char *
pwdgrp::fetch_account_from_file (fetch_user_arg_t &arg)
{
NT_readline rl;
tmp_pathbuf tp;
char *buf = tp.c_get ();
char str[128];
char *ret = NULL;
/* Create search string. */
switch (arg.type)
{
case SID_arg:
/* Override SID with SID string. */
arg.sid->string (str);
arg.name = str;
fallthrough;
case NAME_arg:
arg.len = strlen (arg.name);
break;
case ID_arg:
break;
default:
return NULL;
}
if (rl.init (&attr, buf, NT_MAX_PATH))
while ((buf = rl.gets ()))
if ((ret = fetch_account_from_line (arg, buf)))
return ret;
return NULL;
}
static ULONG
fetch_posix_offset (PDS_DOMAIN_TRUSTSW td, cyg_ldap *cldap)
{
uint32_t id_val = UINT32_MAX;
if (!td->PosixOffset && !(td->Flags & DS_DOMAIN_PRIMARY) && td->DomainSid)
{
if (cldap->open (NULL) == NO_ERROR)
id_val = cldap->fetch_posix_offset_for_domain (td->DnsDomainName);
if (id_val < PRIMARY_POSIX_OFFSET)
{
/* If the offset is less than the primay domain offset, we're bound
to suffer collisions with system and local accounts. Move offset
to a fixed replacement fake offset. This may result in collisions
between other domains all of which were moved to this replacement
offset, but we can't fix all problems caused by careless admins. */
id_val = UNUSABLE_POSIX_OFFSET;
}
else if (id_val == UINT32_MAX)
{
/* We're probably running under a local account, so we're not allowed
to fetch any information from AD beyond the most obvious. Fake a
reasonable posix offset as above and hope for the best. */
id_val = NOACCESS_POSIX_OFFSET;
}
td->PosixOffset = id_val;
}
return td->PosixOffset;
}
/* If LookupAccountName fails, we check the name for a known constructed name
with this function. Return true if we could create a valid SID from name
in sid. sep is either a pointer to thr backslash in name, or NULL if name
is not a qualified DOMAIN\\name string. */
bool
pwdgrp::construct_sid_from_name (cygsid &sid, wchar_t *name, wchar_t *sep)
{
unsigned long rid;
wchar_t *endptr;
if (sep && wcscmp (name, L"no\\body") == 0)
{
/* Special case "nobody" for reproducible construction of a
nobody SID for WinFsp and similar services. We use the
value 65534 which is -2 with 16 bit uid/gids. */
sid.create (0, 1, 0xfffe);
return true;
}
if (sep && wcscmp (name, L"AzureAD\\Group") == 0)
{
get_azure_grp_sid ();
if (PSID (logon_sid) != NO_SID)
{
sid = azure_grp_sid;
return true;
}
return false;
}
if (!sep && wcscmp (name, L"CurrentSession") == 0)
{
get_logon_sid ();
if (PSID (logon_sid) == NO_SID)
return false;
sid = logon_sid;
return true;
}
if (!sep && wcscmp (name, L"Authentication authority asserted identity") == 0)
{
sid.create (18, 1, 1);
return true;
}
if (!sep && wcscmp (name, L"Service asserted identity") == 0)
{
sid.create (18, 1, 2);
return true;
}
if (sep && wcsncmp (name, L"Unix_", 5) == 0)
{
int type;
if (wcsncmp (name + 5, L"User\\", 5) == 0)
type = 1;
else if (wcsncmp (name + 5, L"Group\\", 6) == 0)
type = 2;
else
return false;
rid = wcstoul (sep + 1, &endptr, 10);
if (*endptr == L'\0')
{
sid.create (22, 2, type, rid);
return true;
}
return false;
}
/* At this point we have to check if the domain name is one of the
known domains, and if the account name is one of "User(DWORD)"
or "Group(DWORD)". */
if (sep)
{
wchar_t *numstr = NULL;
bool have_domain = false;
if (wcsncmp (sep + 1, L"User(", 5) == 0)
numstr = sep + 1 + 5;
else if (wcsncmp (sep + 1, L"Group(", 6) == 0)
numstr = sep + 1 + 6;
if (!numstr)
return false;
rid = wcstoul (numstr, &endptr, 10);
if (wcscmp (endptr, L")") != 0)
return false;
if (wcsncasecmp (name, cygheap->dom.account_flat_name (), sep - name)
== 0)
{
sid = cygheap->dom.account_sid ();
have_domain = true;
}
else if (wcsncasecmp (name, cygheap->dom.primary_flat_name (), sep - name)
== 0)
{
sid = cygheap->dom.primary_sid ();
have_domain = true;
}
else
{
PDS_DOMAIN_TRUSTSW td = NULL;
for (ULONG idx = 0; (td = cygheap->dom.trusted_domain (idx)); ++idx)
{
if (wcsncasecmp (name, td->NetbiosDomainName, sep - name) == 0)
{
sid = td->DomainSid;
have_domain = true;
break;
}
}
}
if (have_domain)
{
sid.append (rid);
return true;
}
}
return false;
}
char *
pwdgrp::fetch_account_from_windows (fetch_user_arg_t &arg, cyg_ldap *pldap)
{
/* Used in LookupAccount calls. */
WCHAR namebuf[DNLEN + 1 + UNLEN + 1], *name = namebuf;
WCHAR dom[DNLEN + 1] = L"";
cygsid csid;
DWORD nlen = UNLEN + 1;
DWORD dlen = DNLEN + 1;
DWORD slen = SECURITY_MAX_SID_SIZE;
cygpsid sid (NO_SID);
SID_NAME_USE acc_type;
BOOL ret = false;
/* Cygwin user name style. */
bool fully_qualified_name = false;
/* Computed stuff. */
uid_t uid = ILLEGAL_UID;
gid_t gid = ILLEGAL_GID;
bool is_domain_account = true;
PCWSTR domain = NULL;
bool is_current_user = false;
char *shell = NULL;
char *home = NULL;
char *gecos = NULL;
/* Temporary stuff. */
PWCHAR p;
PWCHAR val;
WCHAR sidstr[128];
ULONG posix_offset = 0;
uint32_t id_val;
cyg_ldap loc_ldap;
cyg_ldap *cldap = pldap ?: &loc_ldap;
/* Initialize */
if (!cygheap->dom.init ())
return NULL;
switch (arg.type)
{
case FULL_acc_arg:
{
sid = arg.full_acc->sid;
*wcpncpy (name, arg.full_acc->name->Buffer,
arg.full_acc->name->Length / sizeof (WCHAR)) = L'\0';
*wcpncpy (dom, arg.full_acc->dom->Buffer,
arg.full_acc->dom->Length / sizeof (WCHAR)) = L'\0';
acc_type = arg.full_acc->acc_type;
ret = acc_type != SidTypeUnknown;
}
break;
case SID_arg:
sid = *arg.sid;
ret = LookupAccountSidW (NULL, sid, name, &nlen, dom, &dlen, &acc_type);
if (!ret
&& cygheap->dom.member_machine ()
&& sid_id_auth (sid) == 5 /* SECURITY_NT_AUTHORITY */
&& sid_sub_auth (sid, 0) == SECURITY_BUILTIN_DOMAIN_RID)
{
/* LookupAccountSid called on a non-DC cannot resolve aliases which
are not defined in the local SAM. If we encounter an alias which
can't be resolved, and if we're a domain member machine, ask a DC.
Do *not* use LookupAccountSidW. It can take ages when called on a
DC for some weird reason. Use LDAP instead. */
if (cldap->fetch_ad_account (sid, true)
&& (val = cldap->get_account_name ()))
{
wcpcpy (name, val);
wcpcpy (dom, L"BUILTIN");
acc_type = SidTypeAlias;
ret = true;
}
}
if (!ret)
debug_printf ("LookupAccountSid(%W), %E", sid.string (sidstr));
break;
case NAME_arg:
bool fq_name;
fq_name = false;
/* Copy over to wchar for search. */
sys_mbstowcs (name, UNLEN + 1, arg.name);
/* If the incoming name has a backslash or at sign, and neither backslash
nor at are the domain separator chars, the name is invalid. */
if ((p = wcspbrk (name, L"\\@")) && *p != cygheap->pg.nss_separator ()[0])
{
debug_printf ("Invalid account name <%s> (backslash/at)", arg.name);
return NULL;
}
/* Replace domain separator char with backslash and make sure p is NULL
or points to the backslash. */
if ((p = wcschr (name, cygheap->pg.nss_separator ()[0])))
{
fq_name = true;
*p = L'\\';
}
sid = csid;
ret = LookupAccountNameW (NULL, name, sid, &slen, dom, &dlen, &acc_type);
/* If this is a name-only S-1-5-21 account *and* it's a machine account
on a domain member machine, then we found the wrong one. Another
weird, but perfectly valid case is, if the group name is identical
to the domain name. Try again with domain name prepended. */
if (ret
&& !fq_name
&& sid_id_auth (sid) == 5 /* SECURITY_NT_AUTHORITY */
&& sid_sub_auth (sid, 0) == SECURITY_NT_NON_UNIQUE
&& cygheap->dom.member_machine ()
&& (wcscasecmp (dom, cygheap->dom.account_flat_name ()) == 0
|| acc_type == SidTypeDomain))
{
p = wcpcpy (name, cygheap->dom.primary_flat_name ());
*p = L'\\';
sys_mbstowcs (p + 1, UNLEN + 1, arg.name);
slen = SECURITY_MAX_SID_SIZE;
dlen = DNLEN + 1;
sid = csid;
ret = LookupAccountNameW (NULL, name, sid, &slen, dom, &dlen,
&acc_type);
}
if (!ret)
{
/* For accounts which can't be resolved by Windows, try if
it's one of the special names we use for special accounts. */
if (construct_sid_from_name (csid, name, p))
break;
debug_printf ("LookupAccountNameW (%W), %E", name);
return NULL;
}
/* We can skip the backslash in the rest of this function. */
if (p)
name = p + 1;
/* Last but not least, some validity checks on the name style. */
if (!fq_name)
{
/* AzureAD user must be prepended by "domain" name. */
if (sid_id_auth (sid) == 12)
return NULL;
/* name_only only if db_prefix is auto. */
if (!cygheap->pg.nss_prefix_auto ())
{
debug_printf ("Invalid account name <%s> (name only/"
"db_prefix not auto)", arg.name);
return NULL;
}
/* name_only account is either builtin or primary domain, or
account domain on non-domain machines. */
if (sid_id_auth (sid) == 5 /* SECURITY_NT_AUTHORITY */
&& sid_sub_auth (sid, 0) == SECURITY_NT_NON_UNIQUE)
{
if (cygheap->dom.member_machine ())
{
if (wcscasecmp (dom, cygheap->dom.primary_flat_name ()) != 0)
{
debug_printf ("Invalid account name <%s> (name only/"
"non primary on domain machine)", arg.name);
return NULL;
}
}
else if (wcscasecmp (dom, cygheap->dom.account_flat_name ()) != 0)
{
debug_printf ("Invalid account name <%s> (name only/"
"non machine on non-domain machine)", arg.name);
return NULL;
}
}
}
else
{
/* All is well if db_prefix is always. */
if (cygheap->pg.nss_prefix_always ())
break;
/* AzureAD accounts should be fully qualifed either. */
if (sid_id_auth (sid) == 12)
break;
/* Otherwise, no fully_qualified for builtin accounts, except for
NT SERVICE, for which we require the prefix. Note that there's
no equivalent test in the `if (!fq_name)' branch above, because
LookupAccountName never returns NT SERVICE accounts if they are
not prependend with the domain anyway. */
if (sid_id_auth (sid) != 5 /* SECURITY_NT_AUTHORITY */
|| (sid_sub_auth (sid, 0) != SECURITY_NT_NON_UNIQUE
&& sid_sub_auth (sid, 0) != SECURITY_SERVICE_ID_BASE_RID))
{
debug_printf ("Invalid account name <%s> (fully qualified/"
"not NON_UNIQUE or NT_SERVICE)", arg.name);
return NULL;
}
/* All is well if db_prefix is primary. */
if (cygheap->pg.nss_prefix_primary ())
break;
/* Domain member and domain == primary domain? */
if (cygheap->dom.member_machine ())
{
if (!wcscasecmp (dom, cygheap->dom.primary_flat_name ()))
{
debug_printf ("Invalid account name <%s> (fully qualified/"
"primary domain account)", arg.name);
return NULL;
}
}
/* Not domain member and domain == account domain? */
else if (!wcscasecmp (dom, cygheap->dom.account_flat_name ()))
{
debug_printf ("Invalid account name <%s> (fully qualified/"
"local account)", arg.name);
return NULL;
}
}
break;
case ID_arg:
/* Construct SID from ID using the SFU rules, just like the code below
goes the opposite route. */
#ifndef INTERIX_COMPATIBLE
/* Except for Builtin and Alias groups in the SECURITY_NT_AUTHORITY.
We create uid/gid values compatible with the old values generated
by mkpasswd/mkgroup. */
if (arg.id < 0x200)
csid.create (5, 1, arg.id & 0x1ff);
else if (arg.id <= 0x3e7)
csid.create (5, 2, 32, arg.id & 0x3ff);
else if (arg.id == 0x3e8) /* Special case "Other Organization" */
csid.create (5, 1, 1000);
else
#endif
if (arg.id == 0xffe)
{
/* OtherSession != Logon SID. */
get_logon_sid ();
/* LookupAccountSidW will fail. */
sid = csid = logon_sid;
sid_sub_auth_rid (sid) = 0;
break;
}
else if (arg.id == 0xfff)
{
/* CurrentSession == Logon SID. */
get_logon_sid ();
/* LookupAccountSidW will fail. */
sid = logon_sid;
break;
}
else if (arg.id == 0x1000)
{
/* AzureAD S-1-12-1-W-X-Y-Z user */
csid = cygheap->user.saved_sid ();
}
else if (arg.id == 0x1001)
{
/* Special AzureAD group SID */
get_azure_grp_sid ();
/* LookupAccountSidW will fail. */
sid = csid = azure_grp_sid;
break;
}
else if (arg.id == 0xfffe)
{
/* Special case "nobody" for reproducible construction of a
nobody SID for WinFsp and similar services. We use the
value 65534 which is -2 with 16 bit uid/gids. */
csid.create (0, 1, 0xfffe);
sid = csid;
break;
}
else if (arg.id < 0x10000)
{
/* Nothing. */
debug_printf ("Invalid POSIX id %u", arg.id);
return NULL;
}
else if (arg.id < 0x20000)
{
/* Well-Known Group */
arg.id -= 0x10000;
/* SECURITY_APP_PACKAGE_AUTHORITY */
if (arg.id >= 0xf20 && arg.id <= 0xf3f)
csid.create (15, 2, (arg.id >> 4) & 0xf, arg.id & 0xf);
else
csid.create (arg.id >> 8, 1, arg.id & 0xff);
}
else if (arg.id >= 0x30000 && arg.id < 0x40000)
{
/* Account domain user or group. */
csid = cygheap->dom.account_sid ();
csid.append (arg.id & 0xffff);
}
else if (arg.id < 0x60000)
{
/* Builtin Alias */
csid.create (5, 2, arg.id >> 12, arg.id & 0xffff);
}
else if (arg.id < 0x70000)
{
/* Mandatory Label. */
csid.create (16, 1, arg.id & 0xffff);
}
else if (arg.id < 0x80000)
{
/* Identity assertion SIDs. */
csid.create (18, 1, arg.id & 0xffff);
}
else if (arg.id < PRIMARY_POSIX_OFFSET)
{
/* Nothing. */
debug_printf ("Invalid POSIX id %u", arg.id);
return NULL;
}
else if (arg.id == ILLEGAL_UID)
{
/* Just some fake. */
sid = csid.create (99, 1, 0);
break;
}
else if (arg.id >= UNIX_POSIX_OFFSET)
{
/* UNIX (unknown NFS or Samba) user account. */
csid.create (22, 2, is_group () ? 2 : 1, arg.id & UNIX_POSIX_MASK);
/* LookupAccountSidW will fail. */
sid = csid;
break;
}
else
{
/* Some trusted domain? */
PDS_DOMAIN_TRUSTSW td = NULL, this_td = NULL;
for (ULONG idx = 0; (td = cygheap->dom.trusted_domain (idx)); ++idx)
{
fetch_posix_offset (td, &loc_ldap);
if (td->PosixOffset > posix_offset && td->PosixOffset <= arg.id)
posix_offset = (this_td = td)->PosixOffset;
}
if (this_td)
{
csid = this_td->DomainSid;
csid.append (arg.id - posix_offset);
}
else
{
/* Primary domain */
csid = cygheap->dom.primary_sid ();
csid.append (arg.id - PRIMARY_POSIX_OFFSET);
}
posix_offset = 0;
}
sid = csid;
ret = LookupAccountSidW (NULL, sid, name, &nlen, dom, &dlen, &acc_type);
if (!ret)
{
debug_printf ("LookupAccountSidW (%W), %E", sid.string (sidstr));
return NULL;
}
break;
}
if (ret)
{
/* Builtin account? SYSTEM, for instance, is returned as SidTypeUser,
if a process is running as LocalSystem service.
Microsoft Account? These show up in the user's group list, using the
undocumented security authority 11. Even though this is officially a
user account, it only matters as part of the group list, so we convert
it to a well-known group here. */
if (acc_type == SidTypeUser
&& (sid_sub_auth_count (sid) <= 3 || sid_id_auth (sid) == 11))
acc_type = SidTypeWellKnownGroup;
switch ((int) acc_type)
{
case SidTypeUser:
if (is_group ())
{
/* Don't allow users as group. While this is technically
possible, it doesn't make sense in a POSIX scenario.
Microsoft Accounts as well as AzureAD accounts have the
primary group SID in their user token set to their own
user SID.
Those we let pass, but no others. */
bool its_ok = false;
if (sid_id_auth (sid) == 12)
its_ok = true;
else if (wincap.has_microsoft_accounts ())
{
USER_INFO_24 *ui24;
if (NetUserGetInfo (NULL, name, 24, (PBYTE *) &ui24)
== NERR_Success)
{
if (ui24->usri24_internet_identity)
its_ok = true;
NetApiBufferFree (ui24);
}
}
if (!its_ok)
return NULL;
}
fallthrough;
case SidTypeGroup:
case SidTypeAlias:
/* Predefined alias? */
if (acc_type == SidTypeAlias
&& sid_sub_auth (sid, 0) != SECURITY_NT_NON_UNIQUE)
{
#ifdef INTERIX_COMPATIBLE
posix_offset = 0x30000;
uid = 0x1000 * sid_sub_auth (sid, 0)
+ (sid_sub_auth_rid (sid) & 0xffff);
#else
posix_offset = 0;
#endif
fully_qualified_name = cygheap->pg.nss_prefix_always ();
is_domain_account = false;
}
/* Account domain account? */
else if (!wcscasecmp (dom, cygheap->dom.account_flat_name ()))
{
posix_offset = 0x30000;
if (cygheap->dom.member_machine ()
|| !cygheap->pg.nss_prefix_auto ())
fully_qualified_name = true;
is_domain_account = false;
}
/* Domain member machine? */
else if (cygheap->dom.member_machine ())
{
/* Primary domain account? */
if (!wcscasecmp (dom, cygheap->dom.primary_flat_name ()))
{
posix_offset = PRIMARY_POSIX_OFFSET;
/* In theory domain should have been set to
cygheap->dom.primary_dns_name (), but it turns out that
not setting the domain here has advantages. We open the
ldap connection to NULL (== some DC of our primary domain)
anyway. So the domain is only used later on. So, don't
set domain here to non-NULL, unless you're sure you have
also changed subsequent assumptions that domain is NULL
if it's a primary domain account. */
if (!cygheap->pg.nss_prefix_auto ())
fully_qualified_name = true;
}
else
{
/* No, fetch POSIX offset. */
PDS_DOMAIN_TRUSTSW td = NULL;
fully_qualified_name = true;
for (ULONG idx = 0;
(td = cygheap->dom.trusted_domain (idx));
++idx)
if (!wcscasecmp (dom, td->NetbiosDomainName))
{
domain = td->DnsDomainName;
break;
}
if (!domain)
{
/* This shouldn't happen, in theory, but it does. There
are cases where the user's logon domain does not show
up in the list of trusted domains. We're desperately
trying to workaround that here by adding an entry for
this domain to the trusted domains and ask the DC for
a posix_offset. There's a good chance this doesn't
work either, but at least we tried, and the user can
work. */
debug_printf ("Unknown domain %W", dom);
td = cygheap->dom.add_domain (dom, sid);
if (td)
domain = td->DnsDomainName;
}
if (domain)
posix_offset = fetch_posix_offset (td, &loc_ldap);
}
}
/* AzureAD S-1-12-1-W-X-Y-Z user */
else if (sid_id_auth (sid) == 12)
{
uid = gid = 0x1000;
fully_qualified_name = true;
home = cygheap->pg.get_home ((PUSER_INFO_3) NULL, sid, dom, name,
fully_qualified_name);
shell = cygheap->pg.get_shell ((PUSER_INFO_3) NULL, sid, dom,
name, fully_qualified_name);
gecos = cygheap->pg.get_gecos ((PUSER_INFO_3) NULL, sid, dom,
name, fully_qualified_name);
break;
}
/* If the domain returned by LookupAccountSid is not our machine
name, and if our machine is no domain member, we lose. We have
nobody to ask for the POSIX offset. */
else
{
debug_printf ("Unknown domain %W", dom);
return NULL;
}
/* Generate uid/gid values. */
if (uid == ILLEGAL_UID)
uid = posix_offset + sid_sub_auth_rid (sid);
if (!is_group () && acc_type == SidTypeUser)
{
/* Default primary group. If the sid is the current user, fetch
the default group from the current user token, otherwise make
the educated guess that the user is in group "Domain Users"
or "None". */
if (sid == cygheap->user.sid ())
{
is_current_user = true;
gid = posix_offset
+ sid_sub_auth_rid (cygheap->user.groups.pgsid);
}
else
gid = posix_offset + DOMAIN_GROUP_RID_USERS;
}
if (is_domain_account)
{
/* Skip this when creating group entries and for non-users. */
if (is_group() || acc_type != SidTypeUser)
break;
/* On AD machines, use LDAP to fetch domain account infos. */
if (cygheap->dom.primary_dns_name ())
{
/* For the current user we got correctly cased username and
the primary group via process token. For any other user
we fetch it from AD and overwrite it. */
if (!is_current_user
&& cldap->fetch_ad_account (sid, false, domain))
{
if ((val = cldap->get_account_name ()))
wcscpy (name, val);
if ((id_val = cldap->get_primary_gid ()) != ILLEGAL_GID)
gid = posix_offset + id_val;
}
home = cygheap->pg.get_home (cldap, sid, dom, domain,
name, fully_qualified_name);
shell = cygheap->pg.get_shell (cldap, sid, dom, domain,
name,
fully_qualified_name);
gecos = cygheap->pg.get_gecos (cldap, sid, dom, domain,
name, fully_qualified_name);
/* Check and, if necessary, add unix<->windows id mapping
on the fly, unless we're called from getpwent. */
if (!pldap && cldap->is_open ())
{
id_val = cldap->get_unix_uid ();
if (id_val != ILLEGAL_UID
&& cygheap->ugid_cache.get_uid (id_val)
== ILLEGAL_UID)
cygheap->ugid_cache.add_uid (id_val, uid);
}
}
/* If primary_dns_name() is empty, we're likely running under an
NT4 domain, so we can't use LDAP. For user accounts fall back
to NetUserGetInfo. This isn't overly fast, but keep in mind
that NT4 domains are mostly replaced by AD these days. */
else
{
WCHAR server[INTERNET_MAX_HOST_NAME_LENGTH + 3];
NET_API_STATUS nas;
PUSER_INFO_3 ui;
if (!get_logon_server (cygheap->dom.primary_flat_name (),
server, DS_IS_FLAT_NAME))
break;
nas = NetUserGetInfo (server, name, 3, (PBYTE *) &ui);
if (nas != NERR_Success)
{
debug_printf ("NetUserGetInfo(%W) %u", name, nas);
break;
}
/* Overwrite name to be sure case is same as in SAM */
wcscpy (name, ui->usri3_name);
gid = posix_offset + ui->usri3_primary_group_id;
home = cygheap->pg.get_home (ui, sid, dom, name,
fully_qualified_name);
shell = cygheap->pg.get_shell (ui, sid, dom, name,
fully_qualified_name);
gecos = cygheap->pg.get_gecos (ui, sid, dom, name,
fully_qualified_name);
}
}
/* Otherwise check account domain (local SAM).*/
else
{
NET_API_STATUS nas;
PUSER_INFO_3 ui;
PLOCALGROUP_INFO_1 gi;
char *pgrp = NULL;
char *uxid = NULL;
if (acc_type == SidTypeUser)
{
nas = NetUserGetInfo (NULL, name, 3, (PBYTE *) &ui);
if (nas != NERR_Success)
{
debug_printf ("NetUserGetInfo(%W) %u", name, nas);
break;
}
/* Overwrite name to be sure case is same as in SAM */
wcscpy (name, ui->usri3_name);
/* Fetch user attributes. */
home = cygheap->pg.get_home (ui, sid, dom, name,
fully_qualified_name);
shell = cygheap->pg.get_shell (ui, sid, dom, name,
fully_qualified_name);
gecos = cygheap->pg.get_gecos (ui, sid, dom, name,
fully_qualified_name);
uxid = fetch_from_description (ui->usri3_comment,
L"unix=\"", 6);
pgrp = fetch_from_description (ui->usri3_comment,
L"group=\"", 7);
}
else /* acc_type == SidTypeAlias */
{
nas = NetLocalGroupGetInfo (NULL, name, 1, (PBYTE *) &gi);
if (nas != NERR_Success)
{
debug_printf ("NetLocalGroupGetInfo(%W) %u", name, nas);
break;
}
/* Overwrite name to be sure case is same as in SAM */
wcscpy (name, gi->lgrpi1_name);
/* Fetch unix gid from comment field. */
uxid = fetch_from_description (gi->lgrpi1_comment,
L"unix=\"", 6);
}
if (acc_type == SidTypeUser)
NetApiBufferFree (ui);
else
NetApiBufferFree (gi);
if (pgrp)
{
/* Set primary group from the "Description" field. Prepend
account domain if this is a domain member machine or the
db_prefix setting requires it. */
char gname[2 * DNLEN + strlen (pgrp) + 1], *gp = gname;
struct group *gr;
if (cygheap->dom.member_machine ()
|| !cygheap->pg.nss_prefix_auto ())
{
gp = gname
+ sys_wcstombs (gname, sizeof gname,
cygheap->dom.account_flat_name ());
*gp++ = cygheap->pg.nss_separator ()[0];
}
stpcpy (gp, pgrp);
if ((gr = internal_getgrnam (gname, cldap)))
gid = gr->gr_gid;
}
char *e;
if (!pldap && uxid && ((id_val = strtoul (uxid, &e, 10)), !*e))
{
if (acc_type == SidTypeUser)
{
if (cygheap->ugid_cache.get_uid (id_val) == ILLEGAL_UID)
cygheap->ugid_cache.add_uid (id_val, uid);
}
else if (cygheap->ugid_cache.get_gid (id_val) == ILLEGAL_GID)
cygheap->ugid_cache.add_gid (id_val, uid);
}
if (pgrp)
free (pgrp);
if (uxid)
free (uxid);
}
break;
case SidTypeWellKnownGroup:
fully_qualified_name = (cygheap->pg.nss_prefix_always ()
/* NT SERVICE Account */
|| (sid_id_auth (sid) == 5 /* SECURITY_NT_AUTHORITY */
&& sid_sub_auth (sid, 0) == SECURITY_SERVICE_ID_BASE_RID)
/* Microsoft Account */
|| sid_id_auth (sid) == 11);
#ifdef INTERIX_COMPATIBLE
if (sid_id_auth (sid) == 5 /* SECURITY_NT_AUTHORITY */
&& sid_sub_auth_count (sid) > 1)
{
uid = 0x1000 * sid_sub_auth (sid, 0)
+ (sid_sub_auth_rid (sid) & 0xffff);
fully_qualified_name = true;
}
else
uid = 0x10000 + 0x100 * sid_id_auth (sid)
+ (sid_sub_auth_rid (sid) & 0xff);
#else
if (sid_id_auth (sid) == 15 /* SECURITY_APP_PACKAGE_AUTHORITY */)
uid = 0x10000 + 0x100 * sid_id_auth (sid)
+ 0x10 * sid_sub_auth (sid, 0)
+ (sid_sub_auth_rid (sid) & 0xf);
else if (sid_id_auth (sid) != 5 /* SECURITY_NT_AUTHORITY */)
uid = 0x10000 + 0x100 * sid_id_auth (sid)
+ (sid_sub_auth_rid (sid) & 0xff);
else if (sid_sub_auth (sid, 0) < SECURITY_PACKAGE_BASE_RID
|| sid_sub_auth (sid, 0) > SECURITY_MAX_BASE_RID)
uid = sid_sub_auth_rid (sid) & 0x7ff;
else
{
uid = 0x1000 * sid_sub_auth (sid, 0)
+ (sid_sub_auth_rid (sid) & 0xffff);
}
#endif
/* Special case for "NULL SID", S-1-0-0 and "Everyone", S-1-1-0.
Never return "NULL SID" or Everyone as user or group. */
if (uid == 0x10000 || uid == 0x10100)
return NULL;
break;
case SidTypeLogonSession:
/* Starting with Windows 10, LookupAccountSid/Name return valid
info for the login session with new SID_NAME_USE value
SidTypeLogonSession. To return the same info as on
pre-Windows 10, we have to handle this type explicitely here
now and convert the name to "CurrentSession". */
get_logon_sid ();
if (PSID (logon_sid) == NO_SID)
return NULL;
if (RtlEqualSid (sid, logon_sid))
{
uid = 0xfff;
wcpcpy (name = namebuf, L"CurrentSession");
}
else
{
uid = 0xffe;
wcpcpy (name = namebuf, L"OtherSession");
}
break;
case SidTypeLabel:
uid = 0x60000 + sid_sub_auth_rid (sid);
fully_qualified_name = cygheap->pg.nss_prefix_always ();
break;
default:
return NULL;
}
}
else if (sid_id_auth (sid) == 0 && sid_sub_auth (sid, 0) == 0xfffe)
{
/* Special case "nobody" for reproducible construction of a
nobody SID for WinFsp and similar services. We use the
value 65534 which is -2 with 16 bit uid/gids. */
uid = gid = 0xfffe;
wcpcpy (dom, L"no");
wcpcpy (name = namebuf, L"body");
fully_qualified_name = true;
acc_type = SidTypeUnknown;
}
else if (sid_id_auth (sid) == 12 && sid_sub_auth (sid, 0) == 1)
{
/* Special AzureAD group SID which can't be resolved by
LookupAccountSid (ERROR_NONE_MAPPED). This is only allowed
as group entry, not as passwd entry. */
if (is_passwd ())
return NULL;
uid = gid = 0x1001;
wcpcpy (dom, L"AzureAD");
wcpcpy (name = namebuf, L"Group");
fully_qualified_name = true;
acc_type = SidTypeUnknown;
}
else if (sid_id_auth (sid) == 5 /* SECURITY_NT_AUTHORITY */
&& sid_sub_auth (sid, 0) == SECURITY_LOGON_IDS_RID)
{
/* Logon ID. Mine or other? */
get_logon_sid ();
if (PSID (logon_sid) == NO_SID)
return NULL;
if (RtlEqualSid (sid, logon_sid))
{
uid = 0xfff;
wcpcpy (name = namebuf, L"CurrentSession");
}
else
{
uid = 0xffe;
wcpcpy (name = namebuf, L"OtherSession");
}
acc_type = SidTypeUnknown;
}
else if (sid_id_auth (sid) == 18)
{
/* Authentication assertion SIDs.
Available when using a 2012R2 DC, but not supported by
LookupAccountXXX on pre Windows 8/2012 machines */
uid = 0x11200 + sid_sub_auth_rid (sid);
wcpcpy (name = namebuf, sid_sub_auth_rid (sid) == 1
? (PWCHAR) L"Authentication authority asserted identity"
: (PWCHAR) L"Service asserted identity");
fully_qualified_name = false;
acc_type = SidTypeUnknown;
}
else if (sid_id_auth (sid) == 22)
{
/* Samba UNIX Users/Groups
This *might* collide with a posix_offset of some trusted domain.
It's just very unlikely. */
uid = MAP_UNIX_TO_CYGWIN_ID (sid_sub_auth_rid (sid));
/* Unfortunately we have no access to the file server from here,
so we can't generate correct user names. */
p = wcpcpy (dom, L"Unix_");
wcpcpy (p, sid_sub_auth (sid, 0) == 1 ? L"User" : L"Group");
__small_swprintf (name = namebuf, L"%d", uid & UNIX_POSIX_MASK);
fully_qualified_name = true;
acc_type = SidTypeUnknown;
}
else
{
if (cygheap->dom.member_machine ()
&& sid_id_auth (sid) == 5 /* SECURITY_NT_AUTHORITY */
&& sid_sub_auth (sid, 0) == SECURITY_NT_NON_UNIQUE)
{
/* Check if we know the domain. If so, create a passwd/group
entry with domain prefix and RID as username. */
PDS_DOMAIN_TRUSTSW td = NULL;
sid_sub_auth_count (sid) = sid_sub_auth_count (sid) - 1;
if (RtlEqualSid (sid, cygheap->dom.primary_sid ()))
{
domain = cygheap->dom.primary_flat_name ();
posix_offset = PRIMARY_POSIX_OFFSET;
}
else
for (ULONG idx = 0; (td = cygheap->dom.trusted_domain (idx)); ++idx)
if (td->DomainSid && RtlEqualSid (sid, td->DomainSid))
{
domain = td->NetbiosDomainName;
posix_offset = fetch_posix_offset (td, &loc_ldap);
break;
}
sid_sub_auth_count (sid) = sid_sub_auth_count (sid) + 1;
}
if (domain)
{
wcscpy (dom, domain);
__small_swprintf (name = namebuf, L"%W(%u)",
is_group () ? L"Group" : L"User",
sid_sub_auth_rid (sid));
uid = posix_offset + sid_sub_auth_rid (sid);
}
else
{
wcpcpy (dom, L"Unknown");
wcpcpy (name = namebuf, is_group () ? L"Group" : L"User");
}
fully_qualified_name = true;
acc_type = SidTypeUnknown;
}
tmp_pathbuf tp;
char *linebuf = tp.c_get ();
char *line = NULL;
WCHAR posix_name[UNLEN + 1 + DNLEN + 1];
p = posix_name;
if (gid == ILLEGAL_GID)
gid = uid;
if (fully_qualified_name)
p = wcpcpy (wcpcpy (p, dom), cygheap->pg.nss_separator ());
wcpcpy (p, name);
if (is_group ())
__small_sprintf (linebuf, "%W:%s:%u:",
posix_name, sid.string ((char *) sidstr), uid);
/* For non-users, create a passwd entry which doesn't allow interactive
logon. Unless it's the SYSTEM account. This conveniently allows to
logon interactively as SYSTEM for debugging purposes. */
else if (acc_type != SidTypeUser && sid != well_known_system_sid)
__small_sprintf (linebuf, "%W:*:%u:%u:U-%W\\%W,%s:/:/sbin/nologin",
posix_name, uid, gid,
dom, name,
sid.string ((char *) sidstr));
else
__small_sprintf (linebuf, "%W:*:%u:%u:%s%sU-%W\\%W,%s:%s%W:%s",
posix_name, uid, gid,
gecos ?: "", gecos ? "," : "",
dom, name,
sid.string ((char *) sidstr),
home ?: "/home/", home ? L"" : name,
shell ?: "/bin/bash");
if (gecos)
free (gecos);
if (home)
free (home);
if (shell)
free (shell);
line = cstrdup (linebuf);
debug_printf ("line: <%s>", line);
return line;
}
client_request_pwdgrp::client_request_pwdgrp (fetch_user_arg_t &arg, bool group)
: client_request (CYGSERVER_REQUEST_PWDGRP, &_parameters, sizeof (_parameters))
{
size_t len = 0;
char *p;
_parameters.in.group = group;
_parameters.in.type = arg.type;
switch (arg.type)
{
case SID_arg:
RtlCopySid (sizeof (DBGSID), (PSID) &_parameters.in.arg.sid, *arg.sid);
len = RtlLengthSid (*arg.sid);
break;
case NAME_arg:
p = stpcpy (_parameters.in.arg.name, arg.name);
len = p - _parameters.in.arg.name + 1;
break;
case ID_arg:
_parameters.in.arg.id = arg.id;
len = sizeof (uint32_t);
break;
default:
api_fatal ("Fetching account info from cygserver with wrong arg.type "
"%d", arg.type);
}
msglen (__builtin_offsetof (struct _pwdgrp_param_t::_pwdgrp_in_t, arg) + len);
}
char *
pwdgrp::fetch_account_from_cygserver (fetch_user_arg_t &arg)
{
client_request_pwdgrp request (arg, is_group ());
if (request.make_request () == -1 || request.error_code ())
{
/* Cygserver not running? Don't try again. This will automatically
avoid an endless loop in cygserver itself. */
if (request.error_code () == ENOSYS)
cygheap->pg.nss_disable_cygserver_caching ();
return NULL;
}
if (!request.line ())
return NULL;
return cstrdup (request.line ());
}
void *
pwdgrp::add_account_from_cygserver (cygpsid &sid)
{
/* No, Everyone is no group in terms of POSIX. */
if (sid_id_auth (sid) == 1 /* SECURITY_WORLD_SID_AUTHORITY */
&& sid_sub_auth (sid, 0) == SECURITY_WORLD_RID)
return NULL;
fetch_user_arg_t arg;
arg.type = SID_arg;
arg.sid = &sid;
char *line = fetch_account_from_cygserver (arg);
return add_account_post_fetch (line, true);
}
void *
pwdgrp::add_account_from_cygserver (const char *name)
{
fetch_user_arg_t arg;
arg.type = NAME_arg;
arg.name = name;
char *line = fetch_account_from_cygserver (arg);
return add_account_post_fetch (line, true);
}
void *
pwdgrp::add_account_from_cygserver (uint32_t id)
{
fetch_user_arg_t arg;
arg.type = ID_arg;
arg.id = id;
char *line = fetch_account_from_cygserver (arg);
return add_account_post_fetch (line, true);
}
|
travisg/newlib
|
winsup/cygwin/uinfo.cc
|
C++
|
gpl-2.0
| 82,403
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.